text stringlengths 2 1.04M | meta dict |
|---|---|
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>C++/CLI on A Developer's Experience</title>
<link>/categories/c++/cli/</link>
<description>Recent content in C++/CLI on A Developer's Experience</description>
<generator>Hugo -- gohugo.io</generator>
<language>en</language><atom:link href="/categories/c++/cli/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>Publishing C++/CLI on LeanPub</title>
<link>/2016/01/19/publishing-ccli-on-leanpub/</link>
<pubDate>Tue, 19 Jan 2016 03:07:03 +0000</pubDate>
<guid>/2016/01/19/publishing-ccli-on-leanpub/</guid>
<description>I came across LeanPub a few months back. I believe it was through hanselman – blog, video or something.</description>
</item>
</channel>
</rss>
| {
"content_hash": "84027af421b70b5d1e5a30cbb420a716",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 136,
"avg_line_length": 48.73684210526316,
"alnum_prop": 0.6544276457883369,
"repo_name": "VivekRagunathan/vivekragunathan.github.io",
"id": "ec30e3ef0b449d4bdd6c39e8f7fbbb68dbf179f2",
"size": "928",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/categories/c++/cli/index.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12372"
},
{
"name": "HTML",
"bytes": "22333"
}
],
"symlink_target": ""
} |
require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin'),
autoprefixer = require('autoprefixer'),
BrowserSyncPlugin = require('browser-sync-webpack-plugin'),
path = require('path'),
nodeModulesPath = path.resolve('./node_modules'),
buildPath = path.resolve(__dirname, 'public', 'scripts'),
mainPath = [
path.resolve(nodeModulesPath, 'stylus-mixins', 'index.styl'),
path.resolve(__dirname, 'assets', 'styles', 'index.styl'),
path.resolve(__dirname, 'assets', 'scripts', 'main.js')
],
config = {
// Makes sure errors in console map to the correct file
// and line number
devtool: 'eval',
entry: mainPath,
output: {
// We need to give Webpack a path. It does not actually need it,
// because files are kept in memory in webpack-dev-server, but an
// error will occur if nothing is specified. We use the buildPath
// as that points to where the files will eventually be bundled
// in production
path: buildPath,
filename: 'main.js',
// Everything related to Webpack should go through a build path,
// localhost:3000/scripts. That makes proxying easier to handle
publicPath: '/scripts/'
},
module: {
loaders: [
// I highly recommend using the babel-loader as it gives you ES6/7 syntax and JSX transpiling out of the box
// if you want to use React for example.
{
test: /\.js$/,
loader: 'babel?presets[]=es2015',
exclude: [ nodeModulesPath ]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader')
},
{
test: /\.styl$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader!stylus-loader')
}
]
},
postcss: function () {
return [ autoprefixer({ browsers: [ 'last 4 versions' ] }) ];
},
plugins: [
new ExtractTextPlugin('../styles/[name].css'),
new BrowserSyncPlugin(
// BrowserSync options
{
// browse to http://localhost:3001/ during development
host: 'localhost',
port: 3001,
// Express server is running on port 3000
proxy: 'http://localhost:3000/'
},
{
reload: true
}
)
]
};
module.exports = config;
| {
"content_hash": "b768ba6e83299d2ea2676967af8fc224",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 114,
"avg_line_length": 31.383561643835616,
"alnum_prop": 0.6219991270187691,
"repo_name": "niallobrien/briskjs",
"id": "46e4bf8bcb9f7f31824be8d0784d3aee420e0b08",
"size": "2291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webpack.config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37494"
},
{
"name": "HTML",
"bytes": "47084"
},
{
"name": "JavaScript",
"bytes": "77540"
},
{
"name": "Smarty",
"bytes": "630"
}
],
"symlink_target": ""
} |
<style>
iframe {
width: 100%;
margin: 0;
padding: 0;
border: 0;
}
</style>
<h1>Welcome to the IFRAME TEST</h1>
<p>
In order to properly test this, you should serve this page at a different
address (even just a different port) from our application stuff. Otherwise
you won't get the full cross-origin restrictions.
</p>
<iframe id="member-form" src="//localhost:8080/self-serve/combo" width="100%" scrolling="no"></iframe>
<script type="text/javascript" src="//localhost:8080/js/self-serve-parent.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<p>
This is the bottom of the parent page.
</p>
| {
"content_hash": "efc6ee5be9dcbeed2dadd23407f36849",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 102,
"avg_line_length": 26.68,
"alnum_prop": 0.7031484257871065,
"repo_name": "adam-p/danforth-east",
"id": "9278734f88b793811aa0e213ba3a5f9e8cb163e4",
"size": "667",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iframe-test.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2472"
},
{
"name": "HTML",
"bytes": "64694"
},
{
"name": "JavaScript",
"bytes": "32568"
},
{
"name": "Python",
"bytes": "106327"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<id>requerer-permissao-de-lavra-garimpeira</id>
<dbId>2745</dbId>
<nome>Requerer Permissão de Lavra Garimpeira</nome>
<sigla></sigla>
<nomes-populares>
<item id="2157">não</item>
</nomes-populares>
<descricao>Requerimento, por meio de formulário padronizado de pré-requerimento eletrônico, a ser preenchido no sítio do DNPM na internet, impresso e protocolizado no DNPM.O pré-requerimento deve ser protocolizado em até 30 dias, contados do seu preenchimento. Para acessar o formulário do pré-requerimento, faz-se necessário o prévio cadastro no CTDM - cadastro de titulares de direito minerário. Requerimento que pleiteia a permissão de aproveitamento mineral pelo regime de permissão de lavra garimpeira, voltado para substâncias minerais com aproveitamento imediato do jazimento mineral que, por sua natureza, dimensão, localização e utilização econômica, possa ser lavrado, independentemente de prévios trabalhos de pesquisa. A permissão de lavra garimpeira pode ser requerida por brasileiros, pessoa física, cooperativa de garimpeiros ou firma individual. Decreto-Lei nº 227/1967 (Código Mineração) Lei nº 7.805/1989 Decreto nº 98.812/1990 Portaria DNPM nº 155/2016</descricao>
<contato></contato>
<gratuito>false</gratuito>
<porcentagem-manual>false</porcentagem-manual>
<servico-digital>false</servico-digital>
<link-servico-digital></link-servico-digital>
<solicitantes>
<solicitante id="3316">
<tipo>Garimpeiros, cooperativas e associações de garimpeiros</tipo>
<requisitos></requisitos>
</solicitante>
</solicitantes>
<tempo-total-estimado>
<entre min="60" max="90" unidade="dias-corridos"/>
<descricao></descricao>
</tempo-total-estimado>
<validade-documento>
<descricao></descricao>
</validade-documento>
<etapas>
<etapa id="6394">
<titulo>Inscrever no Cadastro de Titulares de direitos Minerários.</titulo>
<descricao></descricao>
<documentos>
<default>
<item id="8036">Ata de fundação</item>
<item id="8037">Carteira de identidade</item>
<item id="8038">Carteira de trabalho</item>
<item id="8039">Certidão de casamento</item>
<item id="8040">Certidões da Receita Federal</item>
<item id="8041">Certificado de antecedentes criminais</item>
<item id="8042">CNPJ</item>
<item id="8043">Comprovante de endereço/residência</item>
<item id="8044">Comprovante de pagamento</item>
<item id="8045">Comprovante de quitação eleitoral</item>
<item id="8046">Contrato Social</item>
<item id="8047">CPF</item>
<item id="8048">Procuração do representante legal</item>
<item id="8049">Registro da Junta Comercial</item>
</default>
</documentos>
<custos>
<default/>
</custos>
<canais-de-prestacao>
<default>
<canal-de-prestacao id="6441" tipo="web">
<descricao>https://sistemas.dnpm.gov.br/SCM/Extra/site/requerimento/preencherFichaCadastral.aspx</descricao>
</canal-de-prestacao>
</default>
</canais-de-prestacao>
</etapa>
<etapa id="6395">
<titulo>Preencher formulário eletrônico</titulo>
<descricao></descricao>
<documentos>
<default>
<item id="8050">CPF ou CNPJ do requerente</item>
<item id="8051">CPF ou CNPJ do representante legal</item>
<item id="8052">CPF ou CNPJ do responsável técnico</item>
<item id="8053">Dados da lavra</item>
</default>
</documentos>
<custos>
<default/>
</custos>
<canais-de-prestacao>
<default>
<canal-de-prestacao id="6442" tipo="web">
<descricao>https://sistemas.dnpm.gov.br/SCM/Extra/site/requerimento/preencherRequerimento.aspx?codigoTipoRequerimento=2</descricao>
</canal-de-prestacao>
</default>
</canais-de-prestacao>
</etapa>
<etapa id="6396">
<titulo>Protocolar requerimento</titulo>
<descricao></descricao>
<documentos>
<default>
<item id="8054">Formulário eletrônico preenchido, impresso e assinado.</item>
<item id="8055">Mesma documentação pedida na primeira etapa.</item>
<item id="8056">Comprovante de pagamento</item>
</default>
</documentos>
<custos>
<default>
<custo id="443">
<descricao>Emolumentos</descricao>
<moeda>R$</moeda>
<valor>176,29</valor>
<valorVariavel></valorVariavel>
<statusCustoVariavel>0</statusCustoVariavel>
</custo>
</default>
</custos>
<canais-de-prestacao>
<default>
<canal-de-prestacao id="6443" tipo="presencial">
<descricao>**Departamento Nacional de Produção Mineral (Edifício Sede)** - S.A.N. Quadra 01 Bloco B - CEP: 70041-903 - Brasília/DF</descricao>
</canal-de-prestacao>
<canal-de-prestacao id="6444" tipo="postal">
<descricao>**Departamento Nacional de Produção Mineral (Edifício Sede)** - S.A.N. Quadra 01 Bloco B - CEP: 70041-903 - Brasília/DF</descricao>
</canal-de-prestacao>
</default>
</canais-de-prestacao>
</etapa>
</etapas>
<orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/1918" dbId="23734">
<nomeOrgao>Departamento Nacional de Produção Mineral (DNPM)</nomeOrgao>
</orgao>
<segmentos-da-sociedade>
<item idSegmento="1" idServicoSegmento="6292">Cidadãos</item>
<item idSegmento="4" idServicoSegmento="6293">Demais segmentos (ONGs, organizações sociais, etc)</item>
</segmentos-da-sociedade>
<areas-de-interesse>
<item>Comércio e Serviços</item>
<item>Indústria</item>
<item>Mineração</item>
<item>Fiscalização do Estado</item>
</areas-de-interesse>
<palavras-chave>
<item id="12003">garimpo</item>
<item id="12004">ouro</item>
<item id="12005">pedras preciosas</item>
</palavras-chave>
</servico>
| {
"content_hash": "3701e1e94e272e4c8e415919b7976968",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 987,
"avg_line_length": 52.91111111111111,
"alnum_prop": 0.5816883662326754,
"repo_name": "servicosgovbr/cartas-de-servico",
"id": "3ac97d885670ca927919225596090ad771030ac8",
"size": "7216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cartas-servico/v3/servicos/requerer-permissao-de-lavra-garimpeira.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "906"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Frontend\User\Listener;
use Dot\AnnotatedServices\Annotation\Inject;
use Dot\AnnotatedServices\Annotation\Service;
use Dot\User\Entity\ConfirmTokenEntity;
use Dot\User\Entity\ResetTokenEntity;
use Dot\User\Event\TokenEvent;
use Dot\User\Event\TokenEventListenerInterface;
use Dot\User\Event\TokenEventListenerTrait;
use Dot\User\Event\UserEvent;
use Dot\User\Event\UserEventListenerInterface;
use Dot\User\Event\UserEventListenerTrait;
use Dot\User\Service\TokenService;
use Dot\User\Service\UserService;
use Frontend\User\Entity\UserEntity;
use Frontend\User\Service\UserMailerService;
use Zend\EventManager\EventManagerInterface;
/**
* Class UserEventsListener
* @package Frontend\User\Listener
*
* @Service
*/
class UserEventsListener implements UserEventListenerInterface, TokenEventListenerInterface
{
use UserEventListenerTrait,
TokenEventListenerTrait {
UserEventListenerTrait::attach as userEventAttach;
UserEventListenerTrait::detach as userEventDetach;
TokenEventListenerTrait::attach as tokenEventAttach;
TokenEventListenerTrait::detach as tokenEventDetach;
}
/** @var UserMailerService */
protected $userMailer;
/**
* UserEventsListener constructor.
* @param UserMailerService $userMailer
*
* @Inject({UserMailerService::class})
*/
public function __construct(UserMailerService $userMailer)
{
$this->userMailer = $userMailer;
}
/**
* @param UserEvent $e
*/
public function onAfterRegistration(UserEvent $e)
{
// send an email if registration is with confirmation
$token = $e->getParam('token');
if ($token instanceof ConfirmTokenEntity) {
/** @var UserEntity $user */
$user = $e->getParam('user');
$this->userMailer->sendActivationEmail($user, $token);
}
}
/**
* @param TokenEvent $e
*/
public function onAfterSaveResetToken(TokenEvent $e)
{
$token = $e->getParam('token');
if ($token instanceof ResetTokenEntity) {
/** @var UserEntity $user */
$user = $e->getParam('user');
$this->userMailer->sendPasswordRecoveryEmail($user, $token);
}
}
/**
* @param EventManagerInterface $events
* @param int $priority
*/
public function attach(EventManagerInterface $events, $priority = 1)
{
$identifiers = $events->getIdentifiers();
if (in_array(UserService::class, $identifiers)) {
$this->userEventAttach($events, $priority);
}
if (in_array(TokenService::class, $identifiers)) {
$this->tokenEventAttach($events, $priority);
}
}
/**
* @param EventManagerInterface $events
*/
public function detach(EventManagerInterface $events)
{
$identifiers = $events->getIdentifiers();
if (in_array(UserService::class, $identifiers)) {
$this->userEventDetach($events);
}
if (in_array(TokenService::class, $identifiers)) {
$this->tokenEventDetach($events);
}
}
}
| {
"content_hash": "ea35c2cc16b0a4ed5a9c9e9ef2a37426",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 91,
"avg_line_length": 28.64864864864865,
"alnum_prop": 0.6550314465408805,
"repo_name": "lajoskovago/cjab",
"id": "f735f6cc333201406c7017f6c5465ff898262415",
"size": "3424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/User/src/Listener/UserEventsListener.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "709"
},
{
"name": "CSS",
"bytes": "14432"
},
{
"name": "HTML",
"bytes": "57681"
},
{
"name": "JavaScript",
"bytes": "665"
},
{
"name": "PHP",
"bytes": "79280"
}
],
"symlink_target": ""
} |
import datetime
import re
import pytz
HS_DATE_PATT = "^(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})"
HS_DATE_PATT += "T(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}):(?P<second>[0-9]{2})"
HS_DATE_PATT += "T(?P<tz>\S+)$"
HS_DATE_RE = re.compile(HS_DATE_PATT)
HS_DATE_ISO_PATT = "^(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})"
HS_DATE_ISO_PATT += "[T\s](?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}):(?P<second>[0-9]{2})(?P<microsecond>\.[0-9]+){0,1}"
HS_DATE_ISO_PATT += "(?P<tz>\S+)$"
HS_DATE_ISO_RE = re.compile(HS_DATE_ISO_PATT)
HS_DATE_NOTZ_PATT = "^(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})"
HS_DATE_NOTZ_PATT += "T(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}):(?P<second>[0-9]{2})$"
HS_DATE_NOTZ_RE = re.compile(HS_DATE_NOTZ_PATT)
def hs_date_to_datetime(datestr):
"""
Parse HydroShare (HS) formatted date from a String to a datetime.datetime.
Note: We use a weird TZ format, that does not appear to be ISO 8601
compliant, e.g.: 2015-06-03T09:29:00T-00003
:param datestr: String representing the date in HS format
:return: datetime.datetime with timezone set to UTC
"""
m = HS_DATE_RE.match(datestr)
if m is None:
msg = "Unable to parse date {0}.".format(datestr)
raise HsDateException(msg)
try:
ret_date = datetime.datetime(year=int(m.group('year')),
month=int(m.group('month')),
day=int(m.group('day')),
hour=int(m.group('hour')),
minute=int(m.group('minute')),
second=int(m.group('second')),
tzinfo=pytz.utc)
except Exception as e:
msg = "Unable to parse date {0}, error {1}.".format(datestr,
str(e))
raise HsDateException(msg)
return ret_date
def hs_date_to_datetime_iso(datestr):
"""
Parse the ISO 8601-formatted HydroShare (HS) date from a String to a datetime.datetime.
:param datestr: String representing the date in HS format
:return: datetime.datetime with timezone set to UTC
"""
m = HS_DATE_ISO_RE.match(datestr)
if m is None:
msg = "Unable to parse date {0}.".format(datestr)
raise HsDateException(msg)
try:
# Handle microseconds (if present)
if m.group('microsecond'):
us = float(m.group('microsecond'))
# Convert from seconds to microseconds
microsecond = int(1000 * 1000 * us)
else:
microsecond = 0
ret_date = datetime.datetime(year=int(m.group('year')),
month=int(m.group('month')),
day=int(m.group('day')),
hour=int(m.group('hour')),
minute=int(m.group('minute')),
second=int(m.group('second')),
microsecond=microsecond,
tzinfo=pytz.utc)
except Exception as e:
msg = "Unable to parse date {0}, error {1}.".format(datestr,
str(e))
raise HsDateException(msg)
return ret_date
def hs_date_to_datetime_notz(datestr):
"""
Parse HydroShare (HS) formatted datetime (without timezone information) from a String
to a datetime.datetime.
:param datestr: String representing the date in HS format (without timezone information)
:return: datetime.datetime with timezone set to UTC
"""
m = HS_DATE_NOTZ_RE.match(datestr)
if m is None:
msg = "Unable to parse date {0}.".format(datestr)
raise HsDateException(msg)
try:
ret_date = datetime.datetime(year=int(m.group('year')),
month=int(m.group('month')),
day=int(m.group('day')),
hour=int(m.group('hour')),
minute=int(m.group('minute')),
second=int(m.group('second')),
tzinfo=pytz.utc)
except Exception as e:
msg = "Unable to parse date {0}, error {1}.".format(datestr,
str(e))
raise HsDateException(msg)
return ret_date
class HsDateException(Exception):
pass
| {
"content_hash": "f1d3ef8c90c1164fb189a367e56a8bc2",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 117,
"avg_line_length": 40.74107142857143,
"alnum_prop": 0.5031777339469647,
"repo_name": "FescueFungiShare/hydroshare",
"id": "8694f00cb090b5cf1c6c067aad9e812a74e7878e",
"size": "4563",
"binary": false,
"copies": "2",
"ref": "refs/heads/FescueFungiShare-develop",
"path": "hs_core/hydroshare/date_util.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "374952"
},
{
"name": "HTML",
"bytes": "1107800"
},
{
"name": "JavaScript",
"bytes": "1822132"
},
{
"name": "Python",
"bytes": "3599347"
},
{
"name": "R",
"bytes": "4475"
},
{
"name": "Shell",
"bytes": "49970"
},
{
"name": "XSLT",
"bytes": "790987"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Gdata_App_Extension_Category
*/
require_once 'Zend/Gdata/App/Extension/Category.php';
/**
* Describes a books category
*
* @category Zend
* @package Zend_Gdata
* @subpackage Books
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc.
* (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Books_Extension_BooksCategory extends
Zend_Gdata_App_Extension_Category
{
/**
* Constructor for Zend_Gdata_Books_Extension_BooksCategory which
* Describes a books category
*
* @param string|null $term An identifier representing the category within
* the categorization scheme.
* @param string|null $scheme A string containing a URI identifying the
* categorization scheme.
* @param string|null $label A human-readable label for display in
* end-user applications.
*/
public function __construct($term = null, $scheme = null, $label = null)
{
$this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
parent::__construct($term, $scheme, $label);
}
}
| {
"content_hash": "01e29d01973b450714a2a4ab6404d7be",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 29.48780487804878,
"alnum_prop": 0.6393713813068652,
"repo_name": "ankuradhey/dealtrip",
"id": "a4cff1d20bc45c31085f909e611b1d04adc0222d",
"size": "1923",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/Zend/Gdata/Books/Extension/BooksCategory.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "395"
},
{
"name": "CSS",
"bytes": "674987"
},
{
"name": "HTML",
"bytes": "2367754"
},
{
"name": "JavaScript",
"bytes": "2191952"
},
{
"name": "PHP",
"bytes": "16297944"
},
{
"name": "Python",
"bytes": "42582"
}
],
"symlink_target": ""
} |
/*
* (C) Copyright IBM Corp. 1999 All Rights Reserved.
* Copyright 1997 The Open Group Research Institute. All rights reserved.
*/
package sun.security.krb5;
import sun.security.krb5.internal.Krb5;
import sun.security.krb5.internal.KRBError;
public class KrbException extends Exception {
private static final long serialVersionUID = -4993302876451928596L;
private int returnCode;
private KRBError error;
public KrbException(String s) {
super(s);
}
public KrbException(int i) {
returnCode = i;
}
public KrbException(int i, String s) {
this(s);
returnCode = i;
}
public KrbException(KRBError e) {
returnCode = e.getErrorCode();
error = e;
}
public KrbException(KRBError e, String s) {
this(s);
returnCode = e.getErrorCode();
error = e;
}
public KRBError getError() {
return error;
}
public int returnCode() {
return returnCode;
}
public String returnCodeSymbol() {
return returnCodeSymbol(returnCode);
}
public static String returnCodeSymbol(int i) {
return "not yet implemented";
}
public String returnCodeMessage() {
return Krb5.getErrorMessage(returnCode);
}
public static String errorMessage(int i) {
return Krb5.getErrorMessage(i);
}
public String krbErrorMessage() {
StringBuffer strbuf = new StringBuffer("krb_error " + returnCode);
String msg = getMessage();
if (msg != null) {
strbuf.append(" ");
strbuf.append(msg);
}
return strbuf.toString();
}
/**
* Returns messages like:
* "Integrity check on decrypted field failed (31) - \
* Could not decrypt service ticket"
* If the error code is 0 then the first half is skipped.
*/
public String getMessage() {
StringBuffer message = new StringBuffer();
int returnCode = returnCode();
if (returnCode != 0) {
message.append(returnCodeMessage());
message.append(" (").append(returnCode()).append(')');
}
String consMessage = super.getMessage();
if (consMessage != null && consMessage.length() != 0) {
if (returnCode != 0)
message.append(" - ");
message.append(consMessage);
}
return message.toString();
}
public String toString() {
return ("KrbException: " + getMessage());
}
@Override public int hashCode() {
int result = 17;
result = 37 * result + returnCode;
if (error != null) {
result = 37 * result + error.hashCode();
}
return result;
}
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof KrbException)) {
return false;
}
KrbException other = (KrbException)obj;
if (returnCode != other.returnCode) {
return false;
}
return (error == null)?(other.error == null):
(error.equals(other.error));
}
}
| {
"content_hash": "3f009f804e931ac3c04dbe2321a3a99b",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 75,
"avg_line_length": 24.50381679389313,
"alnum_prop": 0.5663551401869159,
"repo_name": "andreagenso/java2scala",
"id": "efe2324fd26b5031cdda419898b0606f8a499240",
"size": "4422",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/security/krb5/KrbException.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8983"
},
{
"name": "Awk",
"bytes": "26041"
},
{
"name": "Batchfile",
"bytes": "1796"
},
{
"name": "C",
"bytes": "20159882"
},
{
"name": "C#",
"bytes": "7630"
},
{
"name": "C++",
"bytes": "4513460"
},
{
"name": "CSS",
"bytes": "5128"
},
{
"name": "DTrace",
"bytes": "68220"
},
{
"name": "HTML",
"bytes": "1302117"
},
{
"name": "Haskell",
"bytes": "244134"
},
{
"name": "Java",
"bytes": "129267130"
},
{
"name": "JavaScript",
"bytes": "182900"
},
{
"name": "Makefile",
"bytes": "711241"
},
{
"name": "Objective-C",
"bytes": "66163"
},
{
"name": "Python",
"bytes": "137817"
},
{
"name": "Roff",
"bytes": "2630160"
},
{
"name": "Scala",
"bytes": "25599"
},
{
"name": "Shell",
"bytes": "888136"
},
{
"name": "SourcePawn",
"bytes": "78"
}
],
"symlink_target": ""
} |
#ifndef GEOS_OP_BUFFER_OFFSETCURVESETBUILDER_H
#define GEOS_OP_BUFFER_OFFSETCURVESETBUILDER_H
#include <geos/export.h>
#include <vector>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4251) // warning C4251: needs to have dll-interface to be used by clients of class
#endif
// Forward declarations
namespace geos {
namespace geom {
class Geometry;
class CoordinateSequence;
class GeometryCollection;
class Point;
class LineString;
class LinearRing;
class Polygon;
}
namespace geomgraph {
class Label;
}
namespace noding {
class SegmentString;
}
namespace operation {
namespace buffer {
class OffsetCurveBuilder;
}
}
}
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
/**
* \class OffsetCurveSetBuilder opBuffer.h geos/opBuffer.h
*
* \brief
* Creates all the raw offset curves for a buffer of a Geometry.
*
* Raw curves need to be noded together and polygonized to form the
* final buffer area.
*
*/
class GEOS_DLL OffsetCurveSetBuilder {
private:
// To keep track of newly-created Labels.
// Labels will be relesed by object dtor
std::vector<geomgraph::Label*> newLabels;
const geom::Geometry& inputGeom;
double distance;
OffsetCurveBuilder& curveBuilder;
/// The raw offset curves computed.
/// This class holds ownership of std::vector elements.
///
std::vector<noding::SegmentString*> curveList;
/**
* Creates a noding::SegmentString for a coordinate list which is a raw
* offset curve, and adds it to the list of buffer curves.
* The noding::SegmentString is tagged with a geomgraph::Label
* giving the topology of the curve.
* The curve may be oriented in either direction.
* If the curve is oriented CW, the locations will be:
* - Left: Location.EXTERIOR
* - Right: Location.INTERIOR
*
* @param coord is raw offset curve, ownership transferred here
*/
void addCurve(geom::CoordinateSequence *coord, int leftLoc,
int rightLoc);
void add(const geom::Geometry& g);
void addCollection(const geom::GeometryCollection *gc);
/**
* Add a Point to the graph.
*/
void addPoint(const geom::Point *p);
void addLineString(const geom::LineString *line);
void addPolygon(const geom::Polygon *p);
/**
* Add an offset curve for a polygon ring.
* The side and left and right topological location arguments
* assume that the ring is oriented CW.
* If the ring is in the opposite orientation,
* the left and right locations must be interchanged and the side
* flipped.
*
* @param coord the coordinates of the ring (must not contain
* repeated points)
* @param offsetDistance the distance at which to create the buffer
* @param side the side of the ring on which to construct the buffer
* line
* @param cwLeftLoc the location on the L side of the ring
* (if it is CW)
* @param cwRightLoc the location on the R side of the ring
* (if it is CW)
*/
void addPolygonRing(const geom::CoordinateSequence *coord,
double offsetDistance, int side, int cwLeftLoc,
int cwRightLoc);
/**
* The ringCoord is assumed to contain no repeated points.
* It may be degenerate (i.e. contain only 1, 2, or 3 points).
* In this case it has no area, and hence has a minimum diameter of 0.
*
* @param ring
* @param offsetDistance
* @return
*/
bool isErodedCompletely(const geom::LinearRing* ringCoord,
double bufferDistance);
/**
* Tests whether a triangular ring would be eroded completely by
* the given buffer distance.
* This is a precise test. It uses the fact that the inner buffer
* of a triangle converges on the inCentre of the triangle (the
* point equidistant from all sides). If the buffer distance is
* greater than the distance of the inCentre from a side, the
* triangle will be eroded completely.
*
* This test is important, since it removes a problematic case where
* the buffer distance is slightly larger than the inCentre distance.
* In this case the triangle buffer curve "inverts" with incorrect
* topology, producing an incorrect hole in the buffer.
*
* @param triCoord
* @param bufferDistance
* @return
*/
bool isTriangleErodedCompletely(const geom::CoordinateSequence *triCoords,
double bufferDistance);
// Declare type as noncopyable
OffsetCurveSetBuilder(const OffsetCurveSetBuilder& other);
OffsetCurveSetBuilder& operator=(const OffsetCurveSetBuilder& rhs);
public:
/// Constructor
OffsetCurveSetBuilder(const geom::Geometry& newInputGeom,
double newDistance, OffsetCurveBuilder& newCurveBuilder);
/// Destructor
~OffsetCurveSetBuilder();
/** \brief
* Computes the set of raw offset curves for the buffer.
*
* Each offset curve has an attached {@link geomgraph::Label} indicating
* its left and right location.
*
* @return a Collection of SegmentStrings representing the raw
* buffer curves
*/
std::vector<noding::SegmentString*>& getCurves();
/// Add raw curves for a set of CoordinateSequences
//
/// @param lineList is a list of CoordinateSequence, ownership
/// of which is transferred here.
///
void addCurves(const std::vector<geom::CoordinateSequence*>& lineList,
int leftLoc, int rightLoc);
};
} // namespace geos::operation::buffer
} // namespace geos::operation
} // namespace geos
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // ndef GEOS_OP_BUFFER_OFFSETCURVESETBUILDER_H
/**********************************************************************
* $Log$
* Revision 1.2 2006/05/04 10:15:20 strk
* Doxygen comments
*
* Revision 1.1 2006/03/14 00:19:40 strk
* opBuffer.h split, streamlined headers in some (not all) files in operation/buffer/
*
**********************************************************************/
| {
"content_hash": "243eb7cce697966d2731388915fd6e49",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 107,
"avg_line_length": 28.014423076923077,
"alnum_prop": 0.6998455465934443,
"repo_name": "aaam/hellomap3d",
"id": "6cafa8cdc1b5387a24fff3ad40176b04f9f91f39",
"size": "6593",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "AdvancedMap3D/jni/geos-3.3.8/include/geos/operation/buffer/OffsetCurveSetBuilder.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "882"
},
{
"name": "C",
"bytes": "23313028"
},
{
"name": "C++",
"bytes": "9664559"
},
{
"name": "CMake",
"bytes": "77394"
},
{
"name": "Groff",
"bytes": "23064"
},
{
"name": "HTML",
"bytes": "204550"
},
{
"name": "Java",
"bytes": "396240"
},
{
"name": "Lex",
"bytes": "24907"
},
{
"name": "Makefile",
"bytes": "3847314"
},
{
"name": "Objective-C",
"bytes": "42202"
},
{
"name": "PHP",
"bytes": "133902"
},
{
"name": "Python",
"bytes": "41386"
},
{
"name": "Ruby",
"bytes": "124452"
},
{
"name": "Shell",
"bytes": "2447515"
},
{
"name": "Yacc",
"bytes": "125002"
}
],
"symlink_target": ""
} |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.css']
})
export class SidenavComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| {
"content_hash": "7d5cdb44badc2a3d78c2286ac06fa1cc",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 50,
"avg_line_length": 19.428571428571427,
"alnum_prop": 0.6764705882352942,
"repo_name": "Q2mber/la-hackaton-app",
"id": "30716b5277013b76d89be7302c9838fd0cca778c",
"size": "272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/app/layout/sidenav/sidenav.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5140"
},
{
"name": "HTML",
"bytes": "15018"
},
{
"name": "JavaScript",
"bytes": "7132"
},
{
"name": "TypeScript",
"bytes": "48240"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title></title>
<script data-controller="main"></script></head>
<body>
<script type="text/javascript"></script>
<div id="div-to-replace"></div>
</body>
</html> | {
"content_hash": "f06d40757e2478803ca9addfbb65e142",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 15.384615384615385,
"alnum_prop": 0.625,
"repo_name": "aurimas639/grunt-alter-dom",
"id": "c516ca418d3a7700de5587f5f5f3b7e41fe7069d",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/change-scripts.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6810"
}
],
"symlink_target": ""
} |
package net.xxtime.activity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.longtu.base.util.FileUtils;
import com.longtu.base.util.StringUtils;
import com.longtu.base.util.ToastUtils;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import net.xxtime.R;
import net.xxtime.adapter.PhotoRAdapter;
import net.xxtime.base.activity.BaseActivity;
import net.xxtime.base.activity.XxtimeApplication;
import net.xxtime.bean.CommonBean;
import net.xxtime.utils.ImageUtils;
import net.xxtime.utils.SharedUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
public class AuthenticationActivity extends BaseActivity {
private ImageView ivAddjust, ivAddback, ivAddstudent;
private EditText etName, etId ,etStudentId;
private TextView tvStatus;
private Button btnSubmit;
private PopupWindow choosePhotoWindow;
private ImageView ivDelstudent, ivDelback, ivDeljust;
private String isstudent;
private String cardobverse;
private String cardreverse;
private String studentcard;
private int certification;
private String name;
private String cardcode;
private String studentcardcode;
private RelativeLayout rlStudent;
private Message msg;
private CommonBean commonBean;
private int uploadint=0,up=0;
private LinearLayout llSutent;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
commonBean= JSONObject.parseObject(msg.obj.toString(),CommonBean.class);
if (commonBean!=null){
// ToastUtils.show(PerfectInfoActivity.this,commonBean.getMsg());
if (commonBean.getBflag().equals("1")){
if (!StringUtils.isEmpty(addjust)){
if (addjust.indexOf("http://")<0){
params=new RequestParams();
params.put("reqCode","uploadImages");
params.put("userid", SharedUtils.getUserId(AuthenticationActivity.this));
params.put("type",4);
File myFile = new File(addjust);
try {
params.put("file1", myFile);
} catch(FileNotFoundException e) {}
uploadint++;
pullpost("studentUser", params,"uploadImages");
}
}
if (!StringUtils.isEmpty(addback)){
if (addback.indexOf("http://")<0){
params=new RequestParams();
params.put("reqCode","uploadImages");
params.put("userid", SharedUtils.getUserId(AuthenticationActivity.this));
params.put("type",5);
File myFile = new File(addback);
try {
params.put("file1", myFile);
} catch(FileNotFoundException e) {}
uploadint++;
pullpost("studentUser", params,"uploadImages");
}
}
if (!StringUtils.isEmpty(addstudent)){
if (addstudent.indexOf("http://")<0){
params=new RequestParams();
params.put("reqCode","uploadImages");
params.put("userid", SharedUtils.getUserId(AuthenticationActivity.this));
params.put("type",6);
File myFile = new File(addstudent);
try {
params.put("file1", myFile);
} catch(FileNotFoundException e) {}
uploadint++;
pullpost("studentUser", params,"uploadImages");
}
}
if (uploadint==0){
disMiss();
ToastUtils.show(AuthenticationActivity.this,"修改完善个人信息成功!");
finish();
}
// ToastUtils.show(PerfectInfoActivity.this,"正在保存图片");
}
}
break;
case 2:
up++;
if (up==uploadint){
disMiss();
ToastUtils.show(AuthenticationActivity.this,"修改完善个人信息成功!");
finish();
}
break;
}
}
};
@Override
public void setContentView() {
setContentView(R.layout.activity_authentication);
}
@Override
public void initViews() {
ivAddjust =(ImageView)findViewById(R.id.ivAddjust) ;
ivAddback =(ImageView)findViewById(R.id.ivAddback) ;
ivAddstudent =(ImageView)findViewById(R.id.ivAddstudent) ;
ivDelstudent =(ImageView)findViewById(R.id.ivDelstudent) ;
ivDelback =(ImageView)findViewById(R.id.ivDelback) ;
ivDeljust =(ImageView)findViewById(R.id.ivDeljust) ;
etName =(EditText) findViewById(R.id.etName) ;
etId =(EditText) findViewById(R.id.etId) ;
etStudentId =(EditText) findViewById(R.id.etStudentId) ;
tvStatus =(TextView) findViewById(R.id.tvStatus) ;
btnSubmit =(Button) findViewById(R.id.btnSubmit) ;
ivDelstudent.setVisibility(View.GONE);
ivDelback.setVisibility(View.GONE);
ivDeljust.setVisibility(View.GONE);
rlStudent=(RelativeLayout)findViewById(R.id.rlStudent);
llSutent=(LinearLayout) findViewById(R.id.llSutent);
}
@Override
public void initDatas() {
/* FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
params.width= XxtimeApplication.width/5;
params.height=params.width;
ivAddjust.setLayoutParams(params);
ivAddback.setLayoutParams(params);
ivAddstudent.setLayoutParams(params);*/
isstudent=getIntent().getStringExtra("isstudent");
cardobverse=getIntent().getStringExtra("cardobverse");
cardreverse=getIntent().getStringExtra("cardreverse");
studentcard=getIntent().getStringExtra("studentcard");
certification=getIntent().getIntExtra("certification",0);
name=getIntent().getStringExtra("name");
cardcode=getIntent().getStringExtra("cardcode");
studentcardcode=getIntent().getStringExtra("studentcardcode");
if (!isstudent.equals("1")){
llSutent.setVisibility(View.INVISIBLE);
rlStudent.setVisibility(View.GONE);
}
initChooseWindow();
}
@Override
public void setDatas() {
if(!StringUtils.isEmpty(cardobverse)){
addjust=cardobverse;
if (certification==0||certification==3) {
btnSubmit.setText("修改");
ivDeljust.setVisibility(View.VISIBLE);
}
ivAddjust.setEnabled(false);
ImageLoader.getInstance().displayImage(cardobverse,ivAddjust);
}
if(!StringUtils.isEmpty(cardreverse)){
addback=cardreverse;
if (certification==0||certification==3) {
ivDelback.setVisibility(View.VISIBLE);
}
ivAddback.setEnabled(false);
ImageLoader.getInstance().displayImage(cardreverse,ivAddback);
}
if(!StringUtils.isEmpty(studentcard)){
addstudent=studentcard;
if (certification==0||certification==3) {
ivDelstudent.setVisibility(View.VISIBLE);
}
ivAddstudent.setEnabled(false);
ImageLoader.getInstance().displayImage(studentcard,ivAddstudent);
}
if (!StringUtils.isEmpty(name)){
etName.setText(name);
}
if (!StringUtils.isEmpty(cardcode)){
etId.setText(cardcode);
}
if (!StringUtils.isEmpty(studentcardcode)){
etStudentId.setText(studentcardcode);
}
if (certification==0){
tvStatus.setText("未认证");
}else if (certification==1){
setEnadle();
btnSubmit.setText("待认证");
tvStatus.setText("待认证");
}else if (certification==2){
setEnadle();
btnSubmit.setText("已认证");
tvStatus.setText("已认证");
}else if (certification==3){
tvStatus.setText("认证未通过");
}
}
private void setEnadle(){
ivAddstudent.setEnabled(false);
ivAddjust.setEnabled(false);
ivAddback.setEnabled(false);
etName.setEnabled(false);
etStudentId.setEnabled(false);
etId.setEnabled(false);
btnSubmit.setEnabled(false);
btnSubmit.setBackgroundResource(R.drawable.btn_garey);
}
@Override
public void setListener() {
ivAddstudent.setOnClickListener(this);
ivAddjust.setOnClickListener(this);
ivAddback.setOnClickListener(this);
btnCancel.setOnClickListener(this);
btnCam .setOnClickListener(this);
btnCh.setOnClickListener(this);
ivDelstudent.setOnClickListener(this);
ivDelback.setOnClickListener(this);
ivDeljust.setOnClickListener(this);
btnSubmit.setOnClickListener(this);
}
@Override
public void ResumeDatas() {
}
private int addtype=-1;
private String addstudent="",addback="",addjust="";
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ivAddstudent:
addtype=2;
choosePhotoWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
break;
case R.id.ivAddback:
addtype=1;
choosePhotoWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
break;
case R.id.ivAddjust:
addtype=0;
choosePhotoWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
break;
case R.id.btnCancel:
if (choosePhotoWindow!=null)
choosePhotoWindow.dismiss();
break;
case R.id.btnCam:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_C_IMAGE);
if (choosePhotoWindow!=null)
choosePhotoWindow.dismiss();
break;
case R.id.btnCh:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/* startActivityForResult(intent, IMAGE);
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image*//*");
intent.addCategory(Intent.CATEGORY_OPENABLE);*/
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
if (choosePhotoWindow!=null)
choosePhotoWindow.dismiss();
break;
case R.id.ivDeljust:
addjust="";
ivDeljust.setVisibility(View.GONE);
ivAddjust.setEnabled(true);
ivAddjust.setImageResource(R.drawable.btn_add_img_selecter);
break;
case R.id.ivDelback:
addback="";
ivDelback.setVisibility(View.GONE);
ivAddback.setEnabled(true);
ivAddback.setImageResource(R.drawable.btn_add_img_selecter);
break;
case R.id.ivDelstudent:
addstudent="";
ivDelstudent.setVisibility(View.GONE);
ivAddstudent.setEnabled(true);
ivAddstudent.setImageResource(R.drawable.btn_add_img_selecter);
break;
case R.id.btnSubmit:
if (StringUtils.isEmpty(etName.getText().toString())){
ToastUtils.show(this,"请输入真实姓名");
return;
}
if (StringUtils.isEmpty(etId.getText().toString())){
ToastUtils.show(this,"请输入身份证号");
return;
}
if(isstudent.equals("1")){
if (StringUtils.isEmpty(etStudentId.getText().toString())){
ToastUtils.show(this,"请输入学生证号");
return;
}
if (StringUtils.isEmpty(addstudent)){
ToastUtils.show(this,"请选择学生证");
return;
}
}
if (StringUtils.isEmpty(addjust)){
ToastUtils.show(this,"请选择身份证正面");
return;
}
if (StringUtils.isEmpty(addback)){
ToastUtils.show(this,"请选择身份证反面");
return;
}
params=new RequestParams();
params.put("reqCode","modifyStudentUserInfo");
params.put("userid", SharedUtils.getUserId(this));
params.put("name",etName.getText().toString());
params.put("cardcode",etId.getText().toString());
params.put("studentcardcode",etStudentId.getText().toString());
params.put("certification",1);
post("studentUser",params,"modifyStudentUserInfo");
break;
}
}
private Button btnCam, btnCh, btnCancel;
private void initChooseWindow() {
View moreView = getLayoutInflater().inflate(R.layout.choose_photo, null, false);
// 创建PopupWindow实例,200,150分别是宽度和高度
choosePhotoWindow = new PopupWindow(moreView);
choosePhotoWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
choosePhotoWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
choosePhotoWindow.setFocusable(true);
moreView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
choosePhotoWindow.dismiss();
return false;
}
});
btnCam = (Button) moreView.findViewById(R.id.btnCam);
btnCh = (Button) moreView.findViewById(R.id.btnCh);
btnCancel = (Button) moreView.findViewById(R.id.btnCancel);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_IMAGE&& resultCode == Activity.RESULT_OK) {
if (data == null)
return;
if (data != null) {
Uri uri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null,null);
if (cursor != null && cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
if (addtype==0){
addjust=path;
ivDeljust.setVisibility(View.VISIBLE);
ivAddjust.setEnabled(false);
ImageLoader.getInstance().displayImage("file://"+path,ivAddjust);
}else if (addtype==1){
addback=path;
ivDelback.setVisibility(View.VISIBLE);
ivAddback.setEnabled(false);
ImageLoader.getInstance().displayImage("file://"+path,ivAddback);
}else if (addtype==2){
addstudent=path;
ivDelstudent.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage("file://"+path,ivAddstudent);
ivAddstudent.setEnabled(false);
}
}
}
} else if (requestCode==REQUEST_C_IMAGE){
Log.e("requestCode==>",requestCode+"---");
if (data == null)
return;
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
String name = (new DateFormat()).format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".png";
FileUtils.writeFile(Environment.getExternalStorageDirectory() + "/chakeshe/" + name,bitmap);
if (addtype==0){
addjust=Environment.getExternalStorageDirectory() + "/chakeshe/" + name;
ivDeljust.setVisibility(View.VISIBLE);
ivAddjust.setImageBitmap(bitmap);
ivAddjust.setEnabled(false);
}else if (addtype==1){
addback=Environment.getExternalStorageDirectory() + "/chakeshe/" + name;
ivDelback.setVisibility(View.VISIBLE);
ivAddback.setImageBitmap(bitmap);
ivAddback.setEnabled(false);
}else if (addtype==2){
addstudent=Environment.getExternalStorageDirectory() + "/chakeshe/" + name;
ivDelstudent.setVisibility(View.VISIBLE);
ivAddstudent.setImageBitmap(bitmap);
ivAddstudent.setEnabled(false);
}
}
}
@Override
public void OnReceive(String requestname, String response) {
msg=new Message();
if (requestname.equals("modifyStudentUserInfo")){
msg.what=1;
}else if (requestname.equals("uploadImages")){
msg.what=2;
}
msg.obj=response;
handler.sendMessage(msg);
}
}
| {
"content_hash": "7f73a5d1d80da34845335b5f10057ab5",
"timestamp": "",
"source": "github",
"line_count": 501,
"max_line_length": 148,
"avg_line_length": 38.93413173652694,
"alnum_prop": 0.5478314364810828,
"repo_name": "vvvpic/xxtime",
"id": "8b9206cdd2c73dba37909ee9cb5e08502770976d",
"size": "19752",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/net/xxtime/activity/AuthenticationActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "354"
},
{
"name": "Java",
"bytes": "1534952"
}
],
"symlink_target": ""
} |
typedef struct sockaddr* LPSOCKADDR;
#define RcSocketLastError() errno
#endif
namespace Dogee
{
namespace Socket
{
extern SOCKET RcCreateListen(int port);
extern void RcSetTCPNoDelay(SOCKET fd);
extern SOCKET RcConnect(char* ip, int port);
extern SOCKET RcListen(int port);
extern SOCKET RcAccept(SOCKET slisten);
inline int RcSend(SOCKET s, void* data, size_t len)
{
return send((SOCKET)s, (char*)data, len, 0);
}
inline int RcRecv(SOCKET s, void* data, size_t len)
{
return recv((SOCKET)s, (char*)data, len, 0);
}
inline int RcCloseSocket(SOCKET s)
{
return closesocket((SOCKET)s);
}
extern void get_peer_ip_port(SOCKET fd, std::string& ip, int& port);
extern SOCKET RcTryConnect(char* ip, int port, int node_id);
}
}
#endif | {
"content_hash": "859f3019304b76216d4f2d9d2f8b9504",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 70,
"avg_line_length": 23.454545454545453,
"alnum_prop": 0.6976744186046512,
"repo_name": "Menooker/Dogee",
"id": "3ea25271eea4e989a60d54bd9c108ae107015bbb",
"size": "1128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/DogeeSocket.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3200"
},
{
"name": "C++",
"bytes": "235236"
},
{
"name": "Makefile",
"bytes": "3112"
},
{
"name": "Shell",
"bytes": "667"
}
],
"symlink_target": ""
} |
using Newtonsoft.Json;
using VkApi.Wrapper.Objects;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace VkApi.Wrapper.Responses
{
public class BoardGetTopicsExtendedResponse
{
///<summary>
/// Total number
///</summary>
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("items")]
public BoardTopic[] Items { get; set; }
[JsonProperty("default_order")]
public BoardDefaultOrder DefaultOrder { get; set; }
///<summary>
/// Information whether current user can add topic
///</summary>
[JsonProperty("can_add_topics")]
public int CanAddTopics { get; set; }
[JsonProperty("profiles")]
public UsersUserMin[] Profiles { get; set; }
}
} | {
"content_hash": "1f0152b42dd4fe26508541dc5371eab2",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 59,
"avg_line_length": 28.7,
"alnum_prop": 0.6248548199767712,
"repo_name": "Worldbeater/VkLibrary",
"id": "315e609cf3c41eb4aa73ecef999e0ca411612d5c",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VkApi.Wrapper/Responses/Board/BoardGetTopicsExtendedResponse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "919347"
},
{
"name": "F#",
"bytes": "20646"
},
{
"name": "Python",
"bytes": "23282"
}
],
"symlink_target": ""
} |
The Scala Forex library is maintained by the pipeline team at Snowplow Analytics and improved on by
external contributors for which we are extremely grateful.
## Getting in touch
### Community support requests
First and foremost, please do not log an issue if you are asking a general question, all of our community support requests
go through our Discourse forum: https://discourse.snowplowanalytics.com/.
Posting your problem there ensures more people will see it and you should get support faster than creating a new issue on
GitHub. Please do create a new issue on GitHub if you think you've found a bug or if you would like to submit a feature
request though!
### Gitter
If you want to discuss already created issues, potential bugs, new features you would like to work on or any kind of developer
chat, you can head over to our [Gitter room](https://gitter.im/snowplow/scala-forex).
## Issues
### Creating an issue
The project contains an issue template which should help guiding you through the process. However, please keep in mind
that support requests should go to our Discourse forum: https://discourse.snowplowanalytics.com/ and not GitHub issues.
It's also a good idea to log an issue before starting to work on a pull request to discuss it with the maintainers.
### Working on an issue
If you see an issue you would like to work on, please let us know in the issue! That will help us in terms of scheduling and
not doubling the amount of work.
If you don't know where to start contributing, you can look at
[the issues labeled `good first issue`](https://github.com/snowplow/scala-forex/labels/good%20first%20issue).
## Pull requests
These are a few guidelines to keep in mind when opening pull requests, there is a GitHub template that reiterates most of the
points described here.
### Commit hygiene
We keep a strict 1-to-1 correspondance between commits and issues, as such our commit messages are formatted in the following
fashion:
`Add issues description (closes #1234)`
for example:
`Introduce an error ADT (closes #1234)`
### Writing tests and running tests
Whenever necessary, it's good practice to add the corresponding unit tests to whichever feature you are working on.
Then you can run `sbt test` to check they are working properly.
### Feedback cycle
Reviews should happen fairly quickly during weekdays. If you feel your pull request has been forgotten, please ping one
or more maintainers in the pull request.
### Getting your pull request merged
If your pull request is fairly chunky, there might be a non-trivial delay between the moment the pull request is approved and
the moment it gets merged. This is because your pull request will have been scheduled for a specific milestone which might or
might not be actively worked on by a maintainer at the moment.
### Contributor license agreement
We require outside contributors to sign a Contributor license agreement (or CLA) before we can merge their pull requests.
You can find more information on the topic in [the dedicated wiki page](https://github.com/snowplow/snowplow/wiki/CLA).
The @snowplowcla bot will guide you through the process.
| {
"content_hash": "b3715508038ebd2831a908f0245cfb85",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 126,
"avg_line_length": 42.62162162162162,
"alnum_prop": 0.7863031071655041,
"repo_name": "snowplow/scala-forex",
"id": "6c920ba7ccdbedd51255156ef0698a0b7e75c256",
"size": "3175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CONTRIBUTING.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "60690"
},
{
"name": "Shell",
"bytes": "598"
}
],
"symlink_target": ""
} |
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.6.0';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return obj;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
return obj;
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
each(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, function(value, index, list) {
return !predicate.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate || (predicate = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
each(obj, function(value, index, list) {
if (!(result = result && predicate.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, predicate, context) {
predicate || (predicate = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
each(obj, function(value, index, list) {
if (result || (result = predicate.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
var result = -Infinity, lastComputed = -Infinity;
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed > lastComputed) {
result = value;
lastComputed = computed;
}
});
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
var result = Infinity, lastComputed = Infinity;
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
if (computed < lastComputed) {
result = value;
lastComputed = computed;
}
});
return result;
};
// Shuffle an array, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
if (value == null) return _.identity;
if (_.isFunction(value)) return value;
return _.property(value);
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
iterator = lookupIterator(iterator);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iterator, context) {
var result = {};
iterator = lookupIterator(iterator);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, key, value) {
_.has(result, key) ? result[key].push(value) : result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, key, value) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, key) {
_.has(result, key) ? result[key]++ : result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if ((n == null) || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n == null) || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
each(input, function(value) {
if (_.isArray(value) || _.isArguments(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Split an array into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(array, predicate) {
var pass = [], fail = [];
each(array, function(elem) {
(predicate(elem) ? pass : fail).push(elem);
});
return [pass, fail];
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.contains(other, item);
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var length = _.max(_.pluck(arguments, 'length').concat(0));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, '' + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(length);
while(idx < length) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) throw new Error('bindAll must be passed function names');
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = new Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = new Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function () {
return value;
};
};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
return function(obj) {
if (obj === attrs) return true; //avoid comparing an object to itself.
for (var key in attrs) {
if (attrs[key] !== obj[key])
return false;
}
return true;
}
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(Math.max(0, n));
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() { return new Date().getTime(); };
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}).call(this); | {
"content_hash": "df388d631dd9c1f040f56b865182bda3",
"timestamp": "",
"source": "github",
"line_count": 1338,
"max_line_length": 104,
"avg_line_length": 33.85276532137519,
"alnum_prop": 0.6035323987195055,
"repo_name": "sismics/home",
"id": "95913f9adeb00bb91409383a850c96c6fa63f789",
"size": "45513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "home-web/src/main/webapp/src/lib/underscore.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1255"
},
{
"name": "CSS",
"bytes": "7611"
},
{
"name": "HTML",
"bytes": "9713"
},
{
"name": "Java",
"bytes": "229652"
},
{
"name": "JavaScript",
"bytes": "861709"
},
{
"name": "Shell",
"bytes": "3533"
}
],
"symlink_target": ""
} |
const mathPayload = {
name: 'MathAPI',
description: 'This is a simple API for Pizza Shack online pizza delivery store.',
context: '/mathapi',
version: '1.0',
transport: ['http', 'https'],
tags: ['math'],
policies: ['Unlimited'],
securityScheme: ['oauth2'],
visibility: 'PUBLIC',
gatewayEnvironments: ['Production and Sandbox'],
businessInformation: {
businessOwner: 'Jane Roe',
businessOwnerEmail: 'marketing@math.com',
technicalOwner: 'John Doe',
technicalOwnerEmail: 'architecture@math.com',
},
endpointConfig: {
endpoint_type: 'http',
sandbox_endpoints: {
url: 'http://www.mocky.io/v2/5afe55d53200000f00222e02',
},
production_endpoints: {
url: 'http://www.mocky.io/v2/5afe55d53200000f00222e02',
},
},
operations: [
{
target: '/area',
verb: 'GET',
throttlingPolicy: 'Unlimited',
authType: 'Application & Application User',
},
{
target: '/volume',
verb: 'GET',
throttlingPolicy: 'Unlimited',
authType: 'Application & Application User',
},
{
target: '/multiply',
verb: 'POST',
throttlingPolicy: 'Unlimited',
authType: 'Application & Application User',
},
],
};
export default mathPayload;
| {
"content_hash": "37a4a2002e8f3dd1c086d7557b2d99b1",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 85,
"avg_line_length": 29.428571428571427,
"alnum_prop": 0.5436893203883495,
"repo_name": "harsha89/carbon-apimgt",
"id": "44df3ec019aa6e615be0f7a1ddec3d170a39e625",
"size": "1442",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Listing/SampleAPI/math.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11203"
},
{
"name": "CSS",
"bytes": "544771"
},
{
"name": "HTML",
"bytes": "1718063"
},
{
"name": "Java",
"bytes": "14331309"
},
{
"name": "JavaScript",
"bytes": "4861969"
},
{
"name": "PLSQL",
"bytes": "188122"
},
{
"name": "Shell",
"bytes": "29067"
},
{
"name": "TSQL",
"bytes": "545771"
}
],
"symlink_target": ""
} |
package hitwh.xyz.coolweatherbyxyz;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("hitwh.xyz.coolweatherbyxyz", appContext.getPackageName());
}
}
| {
"content_hash": "41694b866350f78ec097939a4af858e1",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 80,
"avg_line_length": 29.076923076923077,
"alnum_prop": 0.7513227513227513,
"repo_name": "Yingzheng1995/CoolWeather",
"id": "7d2596f230213204bc31cd15eb9926ad344b1f44",
"size": "756",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/hitwh/xyz/coolweatherbyxyz/ExampleInstrumentedTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "32266"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using EnvDTE;
using NuGet.VisualStudio;
namespace NuGet.PowerShell.Commands {
/// <summary>
/// This command creates new package file.
/// </summary>
[Cmdlet(VerbsCommon.New, "Package")]
public class NewPackageCommand : NuGetBaseCommand {
private static readonly HashSet<string> _exclude =
new HashSet<string>(new[] { Constants.PackageExtension, Constants.ManifestExtension }, StringComparer.OrdinalIgnoreCase);
public NewPackageCommand()
: this(ServiceLocator.GetInstance<ISolutionManager>(),
ServiceLocator.GetInstance<IVsPackageManagerFactory>(),
ServiceLocator.GetInstance<IHttpClientEvents>()) {
}
public NewPackageCommand(ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IHttpClientEvents httpClientEvents)
: base(solutionManager, packageManagerFactory, httpClientEvents) {
}
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string ProjectName { get; set; }
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty]
public string SpecFileName { get; set; }
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty]
public string TargetFile { get; set; }
/// <summary>
/// If present, New-Package will not overwrite TargetFile.
/// </summary>
[Parameter]
public SwitchParameter NoClobber { get; set; }
protected override void ProcessRecordCore() {
if (!SolutionManager.IsSolutionOpen) {
ErrorHandler.ThrowSolutionNotOpenTerminatingError();
}
string projectName = ProjectName;
// no project specified - choose default
if (String.IsNullOrEmpty(projectName)) {
projectName = SolutionManager.DefaultProjectName;
}
// no default project? empty solution or no compatible projects found
if (String.IsNullOrEmpty(projectName)) {
ErrorHandler.ThrowNoCompatibleProjectsTerminatingError();
}
var projectIns = SolutionManager.GetProject(projectName);
if (projectIns == null) {
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: true);
}
string specFilePath = GetSpecFilePath(projectIns);
var builder = new NuGet.PackageBuilder(specFilePath);
string outputFilePath = GetTargetFilePath(projectIns, builder);
// Remove .nuspec and .nupkg files from output package
RemoveExludedFiles(builder);
WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_CreatingPackage, outputFilePath));
using (Stream stream = File.Create(outputFilePath)) {
builder.Save(stream);
}
WriteLine(Resources.Cmdlet_PackageCreated);
}
private string GetSpecFilePath(Project projectIns) {
string specFilePath = null;
ProjectItem specFile = null;
try {
specFile = FindSpecFile(projectIns, SpecFileName).SingleOrDefault();
}
catch (InvalidOperationException) {
// SingleOrDefault will throw if more than one spec files were found
// terminating
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_TooManySpecFiles),
terminating: true,
errorId: NuGetErrorId.TooManySpecFiles,
category: ErrorCategory.InvalidOperation);
}
if (specFile == null) {
// terminating
ErrorHandler.HandleException(
new ItemNotFoundException(Resources.Cmdlet_NuspecFileNotFound),
terminating: true,
errorId: NuGetErrorId.NuspecFileNotFound,
category: ErrorCategory.ObjectNotFound,
target: SpecFileName);
}
else {
specFilePath = specFile.FileNames[0];
}
return specFilePath;
}
private string GetTargetFilePath(Project projectIns, PackageBuilder builder) {
// Get the output file path
string outputFilePath = GetPackageFilePath(TargetFile, projectIns.FullName, builder.Id, builder.Version);
bool fileExists = File.Exists(outputFilePath);
// prevent overwrite if -NoClobber specified
if (fileExists && NoClobber.IsPresent) {
// terminating
ErrorHandler.HandleException(
new UnauthorizedAccessException(String.Format(
CultureInfo.CurrentCulture,
Resources.Cmdlet_FileExistsNoClobber, TargetFile)),
terminating: true,
errorId: NuGetErrorId.FileExistsNoClobber,
category: ErrorCategory.PermissionDenied,
target: TargetFile);
}
return outputFilePath;
}
internal static string GetPackageFilePath(string outputFile, string projectPath, string id, Version version) {
if (String.IsNullOrEmpty(outputFile)) {
outputFile = String.Join(".", id, version, Constants.PackageExtension.TrimStart('.'));
}
if (!Path.IsPathRooted(outputFile)) {
// if the path is a relative, prepend the project path to it
string folder = Path.GetDirectoryName(projectPath);
outputFile = Path.Combine(folder, outputFile);
}
return outputFile;
}
internal static void RemoveExludedFiles(PackageBuilder builder) {
// Remove the output file or the package spec might try to include it (which is default behavior)
builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path)));
}
private static IEnumerable<ProjectItem> FindSpecFile(EnvDTE.Project projectIns, string specFile) {
if (!String.IsNullOrEmpty(specFile)) {
ProjectItem projectItem = null;
projectIns.ProjectItems.TryGetFile(specFile, out projectItem);
yield return projectItem;
}
else {
// Verify if the project has exactly one file with the .nuspec extension.
// If found, use it as the manifest file for package creation.
int count = 0;
ProjectItem foundItem = null;
foreach (ProjectItem item in projectIns.ProjectItems) {
if (item.Name.EndsWith(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)) {
foundItem = item;
yield return foundItem;
count++;
if (count > 1) {
yield break;
}
}
}
}
}
}
} | {
"content_hash": "cb3f6566c8ac7ecf74c684d29a1d872d",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 150,
"avg_line_length": 41.27173913043478,
"alnum_prop": 0.5772978667368975,
"repo_name": "grendello/nuget",
"id": "2a8cab4e8505b3208a5a08f0a48701bfde5426bb",
"size": "7594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/VsConsole/PowerShellCmdlets/NewPackageCommand.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "27288"
},
{
"name": "C#",
"bytes": "2679355"
},
{
"name": "F#",
"bytes": "359"
},
{
"name": "PowerShell",
"bytes": "118198"
},
{
"name": "Puppet",
"bytes": "835"
}
],
"symlink_target": ""
} |
package com.btmura.android.reddit.app;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.btmura.android.reddit.R;
import com.btmura.android.reddit.content.AccountPrefs;
class SearchThingMenuController implements MenuController, OnClickListener {
private final Context context;
private final ThingHolder thingHolder;
private final Refreshable refreshable;
private final Filterable filterable;
SearchThingMenuController(Context context,
ThingHolder thingHolder,
Refreshable refreshable,
Filterable filterable) {
this.context = context;
this.thingHolder = thingHolder;
this.refreshable = refreshable;
this.filterable = filterable;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_thing_menu, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean hasThing = thingHolder != null && thingHolder.isShowingThing();
menu.findItem(R.id.menu_refresh).setVisible(!hasThing);
menu.findItem(R.id.menu_sort_results).setVisible(!hasThing);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
handleRefresh();
return true;
case R.id.menu_sort_results:
handleSort();
return true;
default:
return false;
}
}
private void handleRefresh() {
refreshable.refresh();
}
private void handleSort() {
MenuHelper.showSortSearchThingsDialog(context, filterable);
}
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
filterable.setFilter(which);
AccountPrefs.setLastSearchFilter(context, which);
}
}
| {
"content_hash": "ca398698f038f67a0d063d7e4ef1f810",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 79,
"avg_line_length": 28.786666666666665,
"alnum_prop": 0.6521537748957851,
"repo_name": "btmura/rbb",
"id": "a2b81223eaae65cabedc600855573fa384e0cc69",
"size": "2762",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/btmura/android/reddit/app/SearchThingMenuController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1068840"
}
],
"symlink_target": ""
} |
using System;
public class Sign_Of_Integer_Number
{
public static void Main()
{
var number = int.Parse(Console.ReadLine());
PrintSign(number);
}
private static void PrintSign(int number)
{
if (number > 0)
Console.WriteLine($"The number {number} is positive.");
else if (number < 0)
Console.WriteLine($"The number {number} is negative.");
else
Console.WriteLine($"The number {number} is zero.");
}
} | {
"content_hash": "505ff5c23b892b9b6c0e85cc9073745b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 67,
"avg_line_length": 21.91304347826087,
"alnum_prop": 0.5714285714285714,
"repo_name": "bilyanahristova42/SoftUni",
"id": "8c8b271918bb08079bfd540ec1b02a8fe517daf0",
"size": "506",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programming Fundamentals/3. Methods. Debugging and Troubleshooting Code/09. Methods. Debugging and Troubleshooting Code - Lab/02. Sign of Integer Number/SignOfIntegerNumber.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "617732"
},
{
"name": "CSS",
"bytes": "306158"
},
{
"name": "HTML",
"bytes": "11742"
},
{
"name": "Java",
"bytes": "6920"
},
{
"name": "JavaScript",
"bytes": "232693"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A binder that places the members of a symbol in scope.
/// </summary>
internal class InContainerBinder : Binder
{
private readonly NamespaceOrTypeSymbol _container;
/// <summary>
/// Creates a binder for a container.
/// </summary>
internal InContainerBinder(NamespaceOrTypeSymbol container, Binder next)
: base(next)
{
Debug.Assert((object)container != null);
_container = container;
}
internal NamespaceOrTypeSymbol Container
{
get
{
return _container;
}
}
internal override Symbol ContainingMemberOrLambda
{
get
{
var merged = _container as MergedNamespaceSymbol;
return ((object)merged != null) ? merged.GetConstituentForCompilation(this.Compilation) : _container;
}
}
private bool IsScriptClass
{
get { return (_container.Kind == SymbolKind.NamedType) && ((NamedTypeSymbol)_container).IsScriptClass; }
}
internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved)
{
var type = _container as NamedTypeSymbol;
if ((object)type != null)
{
return this.IsSymbolAccessibleConditional(symbol, type, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
}
else
{
return Next.IsAccessibleHelper(symbol, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); // delegate to containing Binder, eventually checking assembly.
}
}
internal override bool SupportsExtensionMethods
{
get { return true; }
}
internal override void GetCandidateExtensionMethods(
ArrayBuilder<MethodSymbol> methods,
string name,
int arity,
LookupOptions options,
Binder originalBinder)
{
if (_container.Kind == SymbolKind.Namespace)
{
((NamespaceSymbol)_container).GetExtensionMethods(methods, name, arity, options);
}
}
internal override TypeWithAnnotations GetIteratorElementType()
{
if (IsScriptClass)
{
// This is the scenario where a `yield return` exists in the script file as a global statement.
// This method is to guard against hitting `BuckStopsHereBinder` and crash.
return TypeWithAnnotations.Create(this.Compilation.GetSpecialType(SpecialType.System_Object));
}
else
{
// This path would eventually throw, if we didn't have the case above.
return Next.GetIteratorElementType();
}
}
internal override void LookupSymbolsInSingleBinder(
LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(result.IsClear);
// first lookup members of the namespace
if ((options & LookupOptions.NamespaceAliasesOnly) == 0)
{
this.LookupMembersInternal(result, _container, name, arity, basesBeingResolved, options, originalBinder, diagnose, ref useSiteInfo);
if (result.IsMultiViable)
{
if (arity == 0)
{
// symbols cannot conflict with using alias names
if (Next is WithExternAndUsingAliasesBinder withUsingAliases && withUsingAliases.IsUsingAlias(name, originalBinder.IsSemanticModelBinder, basesBeingResolved))
{
CSDiagnosticInfo diagInfo = new CSDiagnosticInfo(ErrorCode.ERR_ConflictAliasAndMember, name, _container);
var error = new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol)null, name, arity, diagInfo, unreported: true);
result.SetFrom(LookupResult.Good(error)); // force lookup to be done w/ error symbol as result
}
}
return;
}
}
}
internal override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
{
this.AddMemberLookupSymbolsInfo(result, _container, options, originalBinder);
}
protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken)
{
return null;
}
protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken)
{
return null;
}
internal override uint LocalScopeDepth => Binder.ExternalScope;
}
}
| {
"content_hash": "e3fedf43752a89c505669083516af0a7",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 221,
"avg_line_length": 38.736486486486484,
"alnum_prop": 0.6145124716553289,
"repo_name": "weltkante/roslyn",
"id": "771bfb4afaa8b765a0f3c5dcc9cfdc54cf816a5d",
"size": "5735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Compilers/CSharp/Portable/Binder/InContainerBinder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "8186"
},
{
"name": "C#",
"bytes": "171389020"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "11076"
},
{
"name": "Dockerfile",
"bytes": "441"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "283194"
},
{
"name": "Shell",
"bytes": "124090"
},
{
"name": "Vim Snippet",
"bytes": "6353"
},
{
"name": "Visual Basic .NET",
"bytes": "74265514"
}
],
"symlink_target": ""
} |
#################################################################################
#
# Automatically finds all moved work items.
#
# SPACES IN ARGUMENTS MUST BE ENCLOSED BY SINGLE QUOTES
#
# Example 1: Find all work-items, which have been moved and are part of the given team.
# .\Find-Moved-Work-Items -$FilterByTeam 'Team.Phoenix' -SaveInFile 'results.csv'
#
# Example 2: Find all work-items, which have been moved (Without filter).
# .\Find-Moved-Work-Items -ProjectName '' -$FilterByTeam '' -SaveInFile 'results.csv'
#
# Example 3: Specify the server and the project
# .\Find-Moved-Work-Items -Url "https://example.visualstudio.com/DefaultCollection/" -ProjectName "MyProject" -$FilterByTeam 'MyTeam' -SaveInFile 'results.csv'
#################################################################################
param(
[string]$Url,
[string]$ProjectName,
[string]$FilterByTeam,
[string]$SaveInFile = "results.csv"
)
$assignedToFieldName = "Assigned To"
$iterationPathFieldName = "Iteration Path"
#Load TFS PowerShell Snap-in
if ((Get-PSSnapIn -Name Microsoft.TeamFoundation.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.TeamFoundation.PowerShell
}
#Set to German culture so we generate German month names later
[System.Threading.Thread]::CurrentThread.CurrentCulture = "de-DE"
#Load Reference Assemblies
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.WorkItemTracking.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.ProjectManagement")
#TFS Server Settings
$TeamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($Url)
# Service instances
$css4 = ($TeamProjectCollection.GetService([type]"Microsoft.TeamFoundation.Server.ICommonStructureService4")) -as [Microsoft.TeamFoundation.Server.ICommonStructureService4]
$teamService = ($TeamProjectCollection.GetService([type]"Microsoft.TeamFoundation.Client.TfsTeamService")) -as [Microsoft.TeamFoundation.Client.TfsTeamService]
$teamConfig = ($TeamProjectCollection.GetService([type]"Microsoft.TeamFoundation.ProcessConfiguration.Client.TeamSettingsConfigurationService")) -as [Microsoft.TeamFoundation.ProcessConfiguration.Client.TeamSettingsConfigurationService]
$store = ($TeamProjectCollection.GetService([type]"Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore")) -as [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore]
# Find the correct Team and construct a big area filter (for all the areas of that team)
$areaFilter = ""
if ($ProjectName)
{
$proj = $css4.GetProjectFromName($ProjectName)
$allTeams = $teamService.QueryTeams($proj.Uri)
$firstArea = $true
$areaFilter = "WHERE [System.AreaPath] = """
ForEach($team in $allTeams)
{
if (([System.String]::IsNullOrEmpty($FilterByTeam)) -Or $team.Name -eq $FilterByTeam)
{
$ids = [System.Linq.Enumerable]::Repeat($team.Identity.TeamFoundationId, 1)
$teamConfigs = [System.Linq.Enumerable]::ToArray($teamConfig.GetTeamConfigurations($ids))
$settings = $teamConfigs[0].TeamSettings
ForEach($tfv in $settings.TeamFieldValues)
{
if($firstArea)
{
$firstArea = $false
$areaFilter = $areaFilter + $tfv.Value
}
else
{
$areaFilter = $areaFilter + """ OR [System.AreaPath] = """ + $tfv.Value
}
}
}
}
$areaFilter = $areaFilter + """"
}
# Fetch all the workitem ids
$workItemIdQuery = $store.Query("Select Id From WorkItems " + $areaFilter)
[array]$taskItems = new-object System.Threading.Tasks.Task``1[Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem][] ($workItemIdQuery.Count)
Write-Host "Requesting workitems..."
$num = 0
# Start simple tasks via C# Tasks
# This is to fetch all the WorkItem information in parallel (drastic speed-up)
# This is NOT trivial/very hard to do in PowerShell.
function CreateTask {
param(
$workItemId
)
# is this type already defined?
if (-not ("TaskRunner" -as [type])) {
$refs = @(
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll",
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Build.Client.dll",
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Build.Common.dll",
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.WorkItemTracking.Client.dll",
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll",
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v4.5\Microsoft.TeamFoundation.ProjectManagement.dll"
)
Add-Type -ReferencedAssemblies $refs @"
using System;
public sealed class TaskRunner
{
public static System.Threading.Tasks.Task<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem> Create(Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore store, int workItemId)
{
return
System.Threading.Tasks.Task.Run<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem>(
() => store.GetWorkItem(workItemId));
}
}
"@
}
return [TaskRunner]::Create($store, $workItemId)
}
ForEach ($workItem in $workItemIdQuery)
{
Write-Host "Starting... $num / $($workItemIdQuery.Count)"
# This is an alternative solution which is not running in parallel (= slow)
# $task = {
# return $store.GetWorkItem($i.Id)
#}
#$callBack = New-ScriptBlockCallback $task
#$taskObj = [System.Threading.Tasks.Task]::Run([System.Func``1[Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem]]$callBack)
$taskObj = CreateTask($workItem.Id)
$taskItems[$num] = $taskObj
$num = $num + 1
}
# Get all the changes for the given WorkItem and the given fieldName.
function GetChanges ($workItem, $fieldName)
{
if (!$workItem -or !$fieldName)
{
throw "Given workItem is null"
}
[array]$changes = @()
$n = 0
ForEach($rev in $workItem.Revisions)
{
ForEach($field in $rev.Fields)
{
# write-Output "Field: $f.Name"
if (
$field.Name -eq $fieldName -and
$field.OriginalValue -ne $field.Value -and
!([System.String]::IsNullOrWhiteSpace($field.OriginalValue.ToString())))
{
[array]$array = new-object string[] 2
$array[0] = $field.OriginalValue.ToString()
$array[1] = $field.Value.ToString()
$changes += ,$array
$n = $n + 1
}
}
}
if ($n -eq 0)
{
return new-object string[][] (0)
}
else
{
[array]$ret = new-object string[][] ($n)
For ($i=0; $i -lt $n; $i++)
{
if (! $changes[$i])
{
throw "Found a null element. (n $n, i $i )"
}
$ret[$i] = $changes[$i]
}
return $ret
}
}
# (unspectacular) function to write out the .csv file.
function Write-Csv
{
Write-Output "ITEMTITLE;ITEMID;STATE;(Second-)USER;CREATED;FROM;TO;ITERATIONCHANGES;USERCHANGES;TAGS"
$num = 0
ForEach ($taskObj in $taskItems)
{
$workItem = $taskObj.Result
$num = $num + 1
Write-Host "$num / $($workItemIdQuery.Count)"
# @( to force PowerShell to not unwrap: http://stackoverflow.com/questions/11107428/how-can-i-force-powershell-to-return-an-array-when-a-call-only-returns-one-objec
$currentIterationChanges = @(GetChanges -workItem $workItem -fieldName $iterationPathFieldName)
$assignedToChange = @(GetChanges -workItem $workItem -fieldName $assignedToFieldName)
# Remove first if it was initially moved out of root, first check if GetChanges returned null (= empty array at this point)
if ($currentIterationChanges.Length -gt 0 -and ($currentIterationChanges[0][0] -eq $ProjectName -or !$currentIterationChanges[0]))
{
if ($currentIterationChanges.Length -gt 1)
{
[array]$currentIterationChanges = $currentIterationChanges[1..($currentIterationChanges.Length - 1)]
}
else
{
$currentIterationChanges = @()
}
}
$user = $workItem.CreatedBy
$assignedLength = $assignedToChange.Length
if ($assignedLength -gt 0 -and $assignedToChange[0])
{
$from = $assignedToChange[0][0]
$to_ = $assignedToChange[0][1]
$isEmpty = [System.String]::IsNullOrEmpty($assignedToChange[0][1])
if ($isEmpty)
{
$user = $from
}
else
{
$user = $to_
}
}
ForEach($change in $currentIterationChanges)
{
Write-Output """$($workItem.Title)"";$($workItem.Id);$($workItem.State);$user;$($workItem.CreatedDate);$($change[0]);$($change[1]);$($currentIterationChanges.Length);$($assignedToChange.Length);""$($workItem.Tags)"""
}
}
}
Write-Csv > $SaveInFile
| {
"content_hash": "7a4bf3f8ed6053953ec4a0c23ef51ab8",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 236,
"avg_line_length": 36.59836065573771,
"alnum_prop": 0.6977603583426651,
"repo_name": "AITGmbH/AIT.Scripts.WorkItems",
"id": "c7a68798ef3c5113e98554e7eab171fea34377c5",
"size": "8932",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "WorkItems/Find-Moved-Work-Items.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "22524"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Catherine's World</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Theme CSS -->
<link href="css/clean-blog.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand" href="index.html">Catherine's World</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="about.html">About</a>
</li>
<li>
<a href="post.html">Scholarship</a>
</li>
<li>
<a href="network-visualization.html">Networks</a>
</li>
<li>
<a href="people-files.html">People Files</a>
</li>
<li>
<a href="methodology.html">Methods</a>
</li>
<li>
<a href="bibliography.html">Sources</a>
</li>
<li>
<a href="map.html">Italian Map</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('img/IMG_0649.JPG')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Barduccio Canigiani</h1>
<hr class="small">
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<p align="center">
<img class="img-responsive" src="img/Catherine_Pope_Giovanni.jpg"
<p><small>Catherine visits Pope Gregory XI in Avignon, France while her scribes write down her words, possibly depicted Barduccio. <br />
Giovanni di Paolo [Public domain], <a href="https://commons.wikimedia.org/wiki/File%3AGiovanni_di_Paolo_012.jpg">via Wikimedia Commons</a></small></a><br /></p>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p> Barduccio Canigini joined Catherine’s traveling group in 1378 much later than most of her companions.
After she accepted him into her family, he became her scribe and held that position until she died.
He was associated with the Guelf Party in Florence and part of the upper class of Florence.<sup><a href="#fn1" id="ref1">1</a></sup>
Thomas Luongo describes one of his tasks in the companion group as, “professional notaries, at some point
evidently began keep a register of copies of her letters, from which other copies were made which
circulated among her network of followers, to be copied again as desired by new readers.”<sup><a href="#fn2" id="ref2">2</a></sup>
Part of why Catherine was so successful was due to these followers, who took it upon themselves to spread
her word and collect her letters for future readers.</p>
</div>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<ul style="list-style-type:none">
<li> <sup id="fn1">1. Luongo, F. Thomas, The Saintly Politics of Catherine of Siena, (Ithaca: Cornell University Press, 2006), 66. <a href="#ref1" title="Jump back to footnote 1 in the text.">↩</a></sup></li>
<li> <sup id="fn2">2. Luongo, 77. <a href="#ref2" title="Jump back to footnote 2 in the text.">↩</a></sup></li>
</ul>
<p><small>Banner Photo: Basilica Cateriniana di San Domenico in Siena, Italy. By Jessica Mills, 2014.</small></p>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Contact Form JavaScript -->
<script src="js/jqBootstrapValidation.js"></script>
<script src="js/contact_me.js"></script>
<!-- Theme JavaScript -->
<script src="js/clean-blog.min.js"></script>
</body>
</html>
| {
"content_hash": "d37c8aac64d45265a8e08ed6d3188445",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 216,
"avg_line_length": 45.138888888888886,
"alnum_prop": 0.5424615384615384,
"repo_name": "jessmills/jessmills.github.io",
"id": "efa7b2b2e26b2c2eca4de6d837223b38332ecdc1",
"size": "6510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "barduccio-canigiani.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40314"
},
{
"name": "HTML",
"bytes": "514639"
},
{
"name": "JavaScript",
"bytes": "270261"
},
{
"name": "PHP",
"bytes": "1242"
}
],
"symlink_target": ""
} |
/*
* apu.h is duplicated from apu.hw at build time -- do not edit apu.h
*/
/* @file apu.h
* @brief APR-Utility main file
*/
/**
* @defgroup APR_Util APR Utility Functions
* @{
*/
#ifndef APU_H
#define APU_H
/**
* APU_DECLARE_EXPORT is defined when building the APR-UTIL dynamic library,
* so that all public symbols are exported.
*
* APU_DECLARE_STATIC is defined when including the APR-UTIL public headers,
* to provide static linkage when the dynamic library may be unavailable.
*
* APU_DECLARE_STATIC and APU_DECLARE_EXPORT are left undefined when
* including the APR-UTIL public headers, to import and link the symbols from
* the dynamic APR-UTIL library and assure appropriate indirection and calling
* conventions at compile time.
*/
#if defined(DOXYGEN) || !defined(WIN32)
/**
* The public APR-UTIL functions are declared with APU_DECLARE(), so they may
* use the most appropriate calling convention. Public APR functions with
* variable arguments must use APU_DECLARE_NONSTD().
*
* @fn APU_DECLARE(rettype) apr_func(args);
*/
#define APU_DECLARE(type) type
/**
* The public APR-UTIL functions using variable arguments are declared with
* APU_DECLARE_NONSTD(), as they must use the C language calling convention.
*
* @fn APU_DECLARE_NONSTD(rettype) apr_func(args, ...);
*/
#define APU_DECLARE_NONSTD(type) type
/**
* The public APR-UTIL variables are declared with APU_DECLARE_DATA.
* This assures the appropriate indirection is invoked at compile time.
*
* @fn APU_DECLARE_DATA type apr_variable;
* @note extern APU_DECLARE_DATA type apr_variable; syntax is required for
* declarations within headers to properly import the variable.
*/
#define APU_DECLARE_DATA
#elif defined(APU_DECLARE_STATIC)
#define APU_DECLARE(type) type __stdcall
#define APU_DECLARE_NONSTD(type) type __cdecl
#define APU_DECLARE_DATA
#elif defined(APU_DECLARE_EXPORT)
#define APU_DECLARE(type) __declspec(dllexport) type __stdcall
#define APU_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl
#define APU_DECLARE_DATA __declspec(dllexport)
#else
#define APU_DECLARE(type) __declspec(dllimport) type __stdcall
#define APU_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl
#define APU_DECLARE_DATA __declspec(dllimport)
#endif
#if !defined(WIN32) || defined(APU_MODULE_DECLARE_STATIC)
/**
* Declare a dso module's exported module structure as APU_MODULE_DECLARE_DATA.
*
* Unless APU_MODULE_DECLARE_STATIC is defined at compile time, symbols
* declared with APU_MODULE_DECLARE_DATA are always exported.
* @code
* module APU_MODULE_DECLARE_DATA mod_tag
* @endcode
*/
#define APU_MODULE_DECLARE_DATA
#else
#define APU_MODULE_DECLARE_DATA __declspec(dllexport)
#endif
/*
* we always have SDBM (it's in our codebase)
*/
#define APU_HAVE_SDBM 1
#ifndef APU_DSO_MODULE_BUILD
#define APU_HAVE_GDBM 0
#define APU_HAVE_NDBM 0
#define APU_HAVE_DB 0
#if APU_HAVE_DB
#define APU_HAVE_DB_VERSION 0
#endif
#endif
/*
* we always enable dynamic driver loads within apr_dbd
* Win32 always has odbc (it's always installed)
*/
#ifndef APU_DSO_MODULE_BUILD
#define APU_HAVE_PGSQL 0
#define APU_HAVE_MYSQL 0
#define APU_HAVE_SQLITE3 0
#define APU_HAVE_SQLITE2 0
#define APU_HAVE_ORACLE 0
#define APU_HAVE_FREETDS 0
#define APU_HAVE_ODBC 1
#endif
#define APU_HAVE_CRYPTO 1
#ifndef APU_DSO_MODULE_BUILD
#define APU_HAVE_OPENSSL 0
#define APU_HAVE_NSS 0
#endif
#define APU_HAVE_APR_ICONV 1
#define APU_HAVE_ICONV 0
#define APR_HAS_XLATE (APU_HAVE_APR_ICONV || APU_HAVE_ICONV)
#endif /* APU_H */
/** @} */
| {
"content_hash": "2dcdb4e668fd55009d206579f3838ac8",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 79,
"avg_line_length": 30.07936507936508,
"alnum_prop": 0.6873350923482849,
"repo_name": "coder7084/webflix",
"id": "8e67f9e85211e468c0e44afc5ee97e9fe984f19f",
"size": "4588",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bin/apache/Apache2.4.4/include/apu.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "40947"
},
{
"name": "C",
"bytes": "2036149"
},
{
"name": "C++",
"bytes": "157381"
},
{
"name": "CSS",
"bytes": "106251"
},
{
"name": "Erlang",
"bytes": "638729"
},
{
"name": "Forth",
"bytes": "192207"
},
{
"name": "Frege",
"bytes": "1711355"
},
{
"name": "Groff",
"bytes": "29"
},
{
"name": "HTML",
"bytes": "864370"
},
{
"name": "JavaScript",
"bytes": "246743"
},
{
"name": "Makefile",
"bytes": "5575"
},
{
"name": "PHP",
"bytes": "6520086"
},
{
"name": "PLSQL",
"bytes": "699180"
},
{
"name": "PLpgSQL",
"bytes": "92882"
},
{
"name": "Pascal",
"bytes": "31377"
},
{
"name": "Perl",
"bytes": "135163"
},
{
"name": "Python",
"bytes": "15874"
},
{
"name": "Shell",
"bytes": "11129"
},
{
"name": "TeX",
"bytes": "2582"
}
],
"symlink_target": ""
} |
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
//
// Arjuna Technologies Ltd.,
// Newcastle upon Tyne,
// Tyne and Wear,
// UK.
//
package org.jboss.jbossts.qa.CrashRecovery02Clients1;
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Client05a.java,v 1.2 2003/06/26 11:43:18 rbegg Exp $
*/
/*
* Try to get around the differences between Ansi CPP and
* K&R cpp with concatenation.
*/
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Client05a.java,v 1.2 2003/06/26 11:43:18 rbegg Exp $
*/
import org.jboss.jbossts.qa.CrashRecovery02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.jboss.jbossts.qa.Utils.CrashRecoveryDelays;
public class Client05a
{
public static void main(String[] args)
{
try
{
ORBInterface.initORB(args, null);
OAInterface.initOA();
String serviceIOR = ServerIORStore.loadIOR(args[args.length - 1]);
AfterCrashService service = AfterCrashServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR));
CheckBehavior[] checkBehaviors = new CheckBehavior[1];
checkBehaviors[0] = new CheckBehavior();
checkBehaviors[0].allow_done = false;
checkBehaviors[0].allow_returned_prepared = false;
checkBehaviors[0].allow_returned_committing = false;
checkBehaviors[0].allow_returned_committed = false;
checkBehaviors[0].allow_returned_rolledback = true;
checkBehaviors[0].allow_raised_not_prepared = false;
boolean correct = true;
service.setup_oper(1);
correct = service.check_oper(checkBehaviors) && service.is_correct();
CrashRecoveryDelays.awaitReplayCompletionCR02();
ResourceTrace resourceTrace = service.get_resource_trace(0);
correct = correct && (resourceTrace == ResourceTrace.ResourceTraceRollback);
if (correct)
{
System.out.println("Passed");
}
else
{
System.out.println("Failed");
}
}
catch (Exception exception)
{
System.out.println("Failed");
System.err.println("Client05a.main: " + exception);
exception.printStackTrace(System.err);
}
try
{
OAInterface.shutdownOA();
ORBInterface.shutdownORB();
}
catch (Exception exception)
{
System.err.println("Client05a.main: " + exception);
exception.printStackTrace(System.err);
}
}
}
| {
"content_hash": "115781e87e1eb15530925ccc492bf397",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 111,
"avg_line_length": 23.897196261682243,
"alnum_prop": 0.7035588580367619,
"repo_name": "nmcl/scratch",
"id": "3a4f6c6e384658cb60c113251f5ead68ae58b75e",
"size": "3535",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "graalvm/transactions/fork/narayana/qa/tests/src/org/jboss/jbossts/qa/CrashRecovery02Clients1/Client05a.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "37106"
},
{
"name": "Batchfile",
"bytes": "70668"
},
{
"name": "C",
"bytes": "139579"
},
{
"name": "C++",
"bytes": "3001008"
},
{
"name": "CSS",
"bytes": "2238"
},
{
"name": "Clojure",
"bytes": "1535"
},
{
"name": "Dockerfile",
"bytes": "4325"
},
{
"name": "Erlang",
"bytes": "33048"
},
{
"name": "Go",
"bytes": "333"
},
{
"name": "HTML",
"bytes": "1423375"
},
{
"name": "Haskell",
"bytes": "3992"
},
{
"name": "Io",
"bytes": "11232"
},
{
"name": "Java",
"bytes": "22796079"
},
{
"name": "JavaScript",
"bytes": "10464"
},
{
"name": "Makefile",
"bytes": "78159"
},
{
"name": "PHP",
"bytes": "175"
},
{
"name": "PowerShell",
"bytes": "3549"
},
{
"name": "Prolog",
"bytes": "17925"
},
{
"name": "Python",
"bytes": "23464"
},
{
"name": "Roff",
"bytes": "3575"
},
{
"name": "Ruby",
"bytes": "12190"
},
{
"name": "Rust",
"bytes": "880"
},
{
"name": "Scala",
"bytes": "4608"
},
{
"name": "Shell",
"bytes": "165574"
},
{
"name": "Swift",
"bytes": "211"
},
{
"name": "XSLT",
"bytes": "16312"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2cb142990cd5c1133cbfd86cd412918d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "4a5094c3463612bbde74ea837868fb674b823b40",
"size": "196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Bryophyta/Bryopsida/Dicranales/Ditrichaceae/Distichium/Distichium asperrimum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
var ch1 = require('./ch1');
var ch3 = require('./ch3');
var ch4 = require('./ch4');
var ch5 = require('./ch5');
function hamming_dist(bytes1, bytes2) {
console.assert(bytes1.length === bytes2.length, "Hamming distance between 2 byte arrays can only be calculated if they are same length");
var distance = 0;
for (var i = 0; i < bytes1.length; i+=1) {
try {
distance += (bytes1[i] ^ bytes2[i]).toString(2).match(/1/g).length;
}
catch (e) {
continue;
}
}
return distance;
}
if (require.main === module) {
console.log(
hamming_dist(
ch1.string_to_bytes('this is a test'), ch1.string_to_bytes('wokka wokka!!!')
) === 37
);
}
module.exports = {
hamming_dist: hamming_dist
};
| {
"content_hash": "3b2a4fb3cc7fb0f1f83c4eea2e0d07e0",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 139,
"avg_line_length": 22.303030303030305,
"alnum_prop": 0.6019021739130435,
"repo_name": "oasisvali/matasanochallenge",
"id": "e5e18686dd11ea10e8803b2031b758f9f89b783e",
"size": "736",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "set1/ch6.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
goog.require('treesaver.layout.Column');
$(function() {
module('column');
test('Construction & stretching', function () {
var colNode = document.createElement('div'),
col;
document.body.appendChild(colNode);
colNode.style.height = "550px";
colNode.style.minHeight = "200px";
colNode.className = "column fixed col-1";
col = new treesaver.layout.Column(colNode, 800);
ok(col, 'Object constructed');
ok(!col.flexible, 'Fixed flag detected');
equals(col.h, 550, 'Height computed');
equals(col.w, 200, 'Width computed');
equals(col.minH, 200, 'Height computed');
equals(col.delta, 250, 'Computed delta');
col.stretch(1000);
equals(col.h, 550, 'Fixed column does not stretch');
col.flexible = true;
col.stretch(1000);
equals(col.h, 750, 'Flexible column stretches');
document.body.removeChild(colNode);
});
});
| {
"content_hash": "8573e1b74f443186923a5a8fe0efa3b0",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 56,
"avg_line_length": 26.470588235294116,
"alnum_prop": 0.6466666666666666,
"repo_name": "Treesaver/treesaver",
"id": "95fb5bf1a9e965e28b1372eb05aebd0748da6bdd",
"size": "900",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/column.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "10181"
},
{
"name": "JavaScript",
"bytes": "613152"
},
{
"name": "PHP",
"bytes": "5298"
},
{
"name": "Python",
"bytes": "17495"
}
],
"symlink_target": ""
} |
module AmazonProductLookup
class ProductFinder
def self.find(code)
ProductFinder.new(code).find
end
def initialize(code)
ProductCode.validate!(code)
@product_code = ProductCode.normalize(code)
end
end
end | {
"content_hash": "0af3f2010e51be4c25417222ca34c87d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 49,
"avg_line_length": 19.846153846153847,
"alnum_prop": 0.6550387596899225,
"repo_name": "halfbyte/amazon_product_lookup",
"id": "2c83a4fda7ee468e30bfcefc35a9289b7cf68ae9",
"size": "258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/amazon_product_lookup/product_finder.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "25082"
},
{
"name": "Ruby",
"bytes": "52964"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Bundle\FrameworkBundle\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Finder\Finder;
/**
* Command that places bundle web assets into a given directory.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AssetsInstallCommand extends ContainerAwareCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('assets:install')
->setDefinition(array(
new InputArgument('target', InputArgument::OPTIONAL, 'The target directory', 'web'),
))
->addOption('symlink', null, InputOption::VALUE_NONE, 'Symlinks the assets instead of copying it')
->addOption('relative', null, InputOption::VALUE_NONE, 'Make relative symlinks')
->setDescription('Installs bundles web assets under a public web directory')
->setHelp(<<<'EOT'
The <info>%command.name%</info> command installs bundle assets into a given
directory (e.g. the <comment>web</comment> directory).
<info>php %command.full_name% web</info>
A "bundles" directory will be created inside the target directory and the
"Resources/public" directory of each bundle will be copied into it.
To create a symlink to each bundle instead of copying its assets, use the
<info>--symlink</info> option (will fall back to hard copies when symbolic links aren't possible:
<info>php %command.full_name% web --symlink</info>
To make symlink relative, add the <info>--relative</info> option:
<info>php %command.full_name% web --symlink --relative</info>
EOT
)
;
}
/**
* {@inheritdoc}
*
* @throws \InvalidArgumentException When the target directory does not exist or symlink cannot be used
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$targetArg = rtrim($input->getArgument('target'), '/');
if (!is_dir($targetArg)) {
throw new \InvalidArgumentException(sprintf('The target directory "%s" does not exist.', $input->getArgument('target')));
}
$filesystem = $this->getContainer()->get('filesystem');
// Create the bundles directory otherwise symlink will fail.
$bundlesDir = $targetArg.'/bundles/';
$filesystem->mkdir($bundlesDir, 0777);
// relative implies symlink
$symlink = $input->getOption('symlink') || $input->getOption('relative');
if ($symlink) {
$output->writeln('Trying to install assets as <comment>symbolic links</comment>.');
} else {
$output->writeln('Installing assets as <comment>hard copies</comment>.');
}
$validAssetDirs = array();
foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
if (is_dir($originDir = $bundle->getPath().'/Resources/public')) {
$assetDir = preg_replace('/bundle$/', '', strtolower($bundle->getName()));
$targetDir = $bundlesDir.$assetDir;
$validAssetDirs[] = $assetDir;
$output->writeln(sprintf('Installing assets for <comment>%s</comment> into <comment>%s</comment>', $bundle->getNamespace(), $targetDir));
$filesystem->remove($targetDir);
if ($symlink) {
if ($input->getOption('relative')) {
$relativeOriginDir = $filesystem->makePathRelative($originDir, realpath($bundlesDir));
} else {
$relativeOriginDir = $originDir;
}
try {
$filesystem->symlink($relativeOriginDir, $targetDir);
if (!file_exists($targetDir)) {
throw new IOException('Symbolic link is broken');
}
$output->writeln('The assets were installed using symbolic links.');
} catch (IOException $e) {
if (!$input->getOption('relative')) {
$this->hardCopy($originDir, $targetDir);
$output->writeln('It looks like your system doesn\'t support symbolic links, so the assets were installed by copying them.');
}
// try again without the relative option
try {
$filesystem->symlink($originDir, $targetDir);
if (!file_exists($targetDir)) {
throw new IOException('Symbolic link is broken');
}
$output->writeln('It looks like your system doesn\'t support relative symbolic links, so the assets were installed by using absolute symbolic links.');
} catch (IOException $e) {
$this->hardCopy($originDir, $targetDir);
$output->writeln('It looks like your system doesn\'t support symbolic links, so the assets were installed by copying them.');
}
}
} else {
$this->hardCopy($originDir, $targetDir);
}
}
}
// remove the assets of the bundles that no longer exist
$dirsToRemove = Finder::create()->depth(0)->directories()->exclude($validAssetDirs)->in($bundlesDir);
$filesystem->remove($dirsToRemove);
}
/**
* @param string $originDir
* @param string $targetDir
*/
private function hardCopy($originDir, $targetDir)
{
$filesystem = $this->getContainer()->get('filesystem');
$filesystem->mkdir($targetDir, 0777);
// We use a custom iterator to ignore VCS files
$filesystem->mirror($originDir, $targetDir, Finder::create()->ignoreDotFiles(false)->in($originDir));
}
}
| {
"content_hash": "8a0995f0f83cf0748de95bfdd109bffa",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 179,
"avg_line_length": 41.11333333333334,
"alnum_prop": 0.5808334684611642,
"repo_name": "inso/symfony",
"id": "27cccd869e9a01e84a1fb81e878cbce5e9adef3a",
"size": "6396",
"binary": false,
"copies": "3",
"ref": "refs/heads/2.7",
"path": "src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8656"
},
{
"name": "CSS",
"bytes": "10278"
},
{
"name": "HTML",
"bytes": "262023"
},
{
"name": "JavaScript",
"bytes": "345"
},
{
"name": "M4",
"bytes": "2250"
},
{
"name": "PHP",
"bytes": "12306031"
},
{
"name": "PLSQL",
"bytes": "7498"
},
{
"name": "Shell",
"bytes": "643"
}
],
"symlink_target": ""
} |
require "test_helper"
# Single search controller test.
class ReaderSearchControllerNamesBaseAuthorIdListT < ActionController::TestCase
tests SearchController
test "reader can search for a name by base author id" do
author = authors(:cronquist_et_al)
get(:search,
{ query_target: "name", query_string: "base-author-id: #{author.id}" },
username: "fred",
user_full_name: "Fred Jones",
groups: [])
assert_response :success
assert_select "#search-results-summary",
/\b1 name\b/,
"Should find 1 record for base author ID: #{author.id}"
end
end
| {
"content_hash": "7e21634fa33b1002d325b27051b3b825",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 79,
"avg_line_length": 33.21052631578947,
"alnum_prop": 0.6434231378763867,
"repo_name": "bio-org-au/nsl-editor",
"id": "0bdf623681ec70ce702c1728ed0e891f51d8d36c",
"size": "1322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/controllers/search/names/for_reader/list/base_author_id_test.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "53964"
},
{
"name": "CoffeeScript",
"bytes": "32497"
},
{
"name": "Dockerfile",
"bytes": "658"
},
{
"name": "HTML",
"bytes": "724160"
},
{
"name": "JavaScript",
"bytes": "82408"
},
{
"name": "PLpgSQL",
"bytes": "181444"
},
{
"name": "Ruby",
"bytes": "2827413"
},
{
"name": "SQLPL",
"bytes": "169"
},
{
"name": "Shell",
"bytes": "1496"
},
{
"name": "TSQL",
"bytes": "16000"
}
],
"symlink_target": ""
} |
#ifndef AVL_TREE_H
#define AVL_TREE_H
typedef struct AVLTree_t AVLTree;
typedef struct AVLNode_t AVLNode;
/*
1 >
0 =
-1 <
*/
typedef int (*comp_func)(void *, void *);
typedef void (*map_func)(void *, void *);
AVLTree *avl_new(comp_func);
/*
Note avl_destroy will free data in nodes aswell
*/
void avl_destroy(AVLTree *);
void avl_add(AVLTree *, void *);
void avl_delete(AVLTree *, void *);
void avl_reroot(AVLTree *);
void avl_map(AVLTree *t, void *arg, map_func);
int avl_height(AVLTree *);
int avl_size(AVLTree *);
void *avl_find(AVLTree *, void *);
AVLNode *avl_new_node();
void avl_destroy_node(AVLNode *);
void avl_rotate_right(AVLNode *);
void avl_rotate_left(AVLNode *);
void avl_remeasure(AVLNode *);
void avl_rebalance(AVLNode *);
AVLNode *avl_node_find(AVLNode *, void *, comp_func fun);
#endif
| {
"content_hash": "bd0daab47c278b4e1ed2e17ccaf05f09",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 57,
"avg_line_length": 20.897435897435898,
"alnum_prop": 0.6834355828220859,
"repo_name": "iiag/iiag",
"id": "b89a365ac0253ef85b68024e73b506ad902895d4",
"size": "815",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/util/AVLTree.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "37191"
},
{
"name": "Makefile",
"bytes": "1906"
}
],
"symlink_target": ""
} |
layout: post
title: "Juiblex"
date: 2017-09-10
tags: [huge, fiend, cr23, out-of-the-abyss]
---
**Huge fiend (demon), chaotic evil**
**Armor Class** 18 (natural armor)
**Hit Points** 350 (28d12+168)
**Speed** 30 ft.
| STR | DEX | CON | INT | WIS | CHA |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 24 (+7) | 10 (0) | 23 (+6) | 20 (+5) | 20 (+5) | 16 (+3) |
**Saving Throws** Dex +7, Con +13, Wis +12
**Skills** Perception +12
**Damage Resistances** cold, fire, lightning
**Damage Immunities** poison; bludgeoning, piercing, and slashing that is nonmagical
**Condition Immunities** blinded, charmed, deafened, exhaustion, frightened, grappled, paralyzed, petrified, poisoned, prone, restrained, stunned, unconscious
**Senses** truesight 120 ft.
**Languages** all, telepathy 120 ft.
**Challenge** 23 (50,000 XP)
***Foul.*** Any creature, other than an ooze, that starts its turn within 10 feet of Juiblex must succeed on a DC 21 Constitution saving throw or be poisoned until the start of the creature's next turn.
***Innate Spellcasting.*** Juiblex's spellcasting ability is Charisma (spell save DC 18, +10 to hit with spell attacks). Juiblex can innately cast the following spells, requiring no material components:
At will: acid splash (17th level), detect magic
3/day each: blight, contagion, gaseous form
***Legendary Resistance (3/Day).*** If Juiblex fails a saving throw, it can choose to succeed instead.
***Magic Resistance.*** Juiblex has advantage on saving throws against spell and other magic effects.
***Magic Weapon.*** Juiblex's weapon attacks are magical.
***Regeneration.*** Juiblex regains 20 hit points at the start of its turn. If it takes fire or radiant damage, this trait doesn't function at the start of its next turn. Juiblex dies only if it starts its turn with 0 hit points and doesn't regenerate.
***Spider Climb.*** Juiblex can climb difficult surfaces, including upside down on ceilings, without needing to make an ability check.
**Actions**
***Multiattack.*** Juiblex makes three acid lash attacks.
***Acid Lash.*** Melee Weapon Attack: +14 to hit, reach 10 ft., one target. Hit: 21 (4d6 + 7) acid damage. Any creature killed by this attack is drawn into Juiblex's body, and the corpse is obliterated after 1 minute.
***Eject Slime (Recharge 5-6).*** Juiblex spews out a corrosive slime, targeting one creature that it can see within 60 feet of it. The target must make a DC 21 Dexterity saving throw. On a failure, the target takes 55 (10d10) acid damage. Unless the target avoids taking any of this damage, any metal armor worn by the target takes a permanent -1 penalty to the AC it offers, and any metal weapon it is carrying or wearing takes a permanent -1 penalty to damage rolls. The penalty worsens each time a target is subjected to this effect. If the penalty on an object drops to -5, the object is destroyed.
**Legendary Actions**
Juiblex can take 3 legendary actions, choosing from the options below, Only one legendary action option can be used at a time and only at the end of another creature's turn. Juiblex regains spent legendary actions at the start of its turn.
***Acid Splash.*** Juiblex casts acid splash.
***Attack.*** Juiblex makes one acid lash attack.
***Corrupting Touch (Costs 2 Actions).*** Melee Weapon Attack: +14 to hit, reach 10 ft., one creature. Hit: 21 (4d6+ 7) poison damage, and the target is slimed. Until the slime is scraped off with an action, the target is poisoned, and any creature, other than an ooze, is poisoned while Within 10 of the target.
| {
"content_hash": "f5ba1579852fa4cb9e531bb34f50919e",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 603,
"avg_line_length": 51.214285714285715,
"alnum_prop": 0.7210599721059973,
"repo_name": "whiplashomega/elthelas2",
"id": "1b0c43caf054f43a6996d5d5d149e30de5f9d479",
"size": "3589",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.x-dev",
"path": "data/creaturebackup/juiblex.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2037"
},
{
"name": "HTML",
"bytes": "354"
},
{
"name": "JavaScript",
"bytes": "761819"
},
{
"name": "PHP",
"bytes": "6911"
},
{
"name": "Procfile",
"bytes": "19"
},
{
"name": "SCSS",
"bytes": "29752"
},
{
"name": "Vue",
"bytes": "727797"
}
],
"symlink_target": ""
} |
package com.forestry.service.sys.impl;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.forestry.dao.sys.AuthorityDao;
import com.forestry.model.sys.Authority;
import com.forestry.model.sys.RoleAuthority;
import com.forestry.service.sys.AuthorityService;
import core.service.BaseService;
/**
* @author Yang Tian
* @email 1298588579@qq.com
*/
@Service
public class AuthorityServiceImpl extends BaseService<Authority> implements AuthorityService {
private AuthorityDao authorityDao;
@Resource
public void setAuthorityDao(AuthorityDao authorityDao) {
this.authorityDao = authorityDao;
this.dao = authorityDao;
}
@Override
public List<Authority> queryByParentIdAndRole(Short role) {
return authorityDao.queryByParentIdAndRole(role);
}
@Override
public List<Authority> queryChildrenByParentIdAndRole(Long parentId, Short role) {
return authorityDao.queryChildrenByParentIdAndRole(parentId, role);
}
@Override
public String querySurfaceAuthorityList(List<RoleAuthority> queryByProerties, Long id, String buttons) {
StringBuilder sb = new StringBuilder();
String[] buttonsArray = buttons.split(",");
for (RoleAuthority roleAuthority : queryByProerties) {
if (!isNumeric(roleAuthority.getAuthorityId())) {
for (int z = 0; z < buttonsArray.length; z++) {
if ((id + buttonsArray[z]).equalsIgnoreCase(roleAuthority.getAuthorityId())) {
sb.append(buttonsArray[z] + ",");
}
}
}
}
return sb.toString();
}
private static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
}
| {
"content_hash": "0d9e7fe9aeadd803f02af0d9e6dc0d33",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 105,
"avg_line_length": 27.095238095238095,
"alnum_prop": 0.7545401288810779,
"repo_name": "youimages/community",
"id": "cdba7ff1bed2ed6ec5f7075b105fb8465cd351cc",
"size": "1707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "forestry/src/com/forestry/service/sys/impl/AuthorityServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "449903"
},
{
"name": "HTML",
"bytes": "9803"
},
{
"name": "Java",
"bytes": "651983"
},
{
"name": "JavaScript",
"bytes": "1188"
}
],
"symlink_target": ""
} |
package org.kie.workbench.drools.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.guvnor.common.services.shared.config.AppConfigService;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.screens.social.hp.config.SocialConfigurationService;
import org.kie.workbench.common.services.shared.service.PlaceManagerActivityService;
import org.kie.workbench.common.workbench.client.authz.PermissionTreeSetup;
import org.kie.workbench.common.workbench.client.menu.DefaultWorkbenchFeaturesMenusHelper;
import org.kie.workbench.common.workbench.client.admin.DefaultAdminPageHelper;
import org.kie.workbench.drools.client.home.HomeProducer;
import org.kie.workbench.drools.client.resources.i18n.AppConstants;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.uberfire.client.mvp.ActivityBeansCache;
import org.uberfire.client.workbench.Workbench;
import org.uberfire.client.workbench.widgets.menu.WorkbenchMenuBarPresenter;
import org.uberfire.ext.security.management.client.ClientUserSystemManager;
import org.uberfire.mocks.CallerMock;
import org.uberfire.mocks.ConstantsAnswerMock;
import org.uberfire.mocks.IocTestingUtils;
import org.uberfire.mvp.Command;
import org.uberfire.workbench.model.menu.MenuItem;
import org.uberfire.workbench.model.menu.Menus;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(GwtMockitoTestRunner.class)
public class KieDroolsWorkbenchEntryPointTest {
@Mock
private AppConfigService appConfigService;
private CallerMock<AppConfigService> appConfigServiceCallerMock;
@Mock
private PlaceManagerActivityService pmas;
private CallerMock<PlaceManagerActivityService> pmasCallerMock;
@Mock
private ActivityBeansCache activityBeansCache;
@Mock
private HomeProducer homeProducer;
@Mock
private SocialConfigurationService socialConfigurationService;
private CallerMock<SocialConfigurationService> socialConfigurationServiceCallerMock;
@Mock
private DefaultWorkbenchFeaturesMenusHelper menusHelper;
@Mock
protected ClientUserSystemManager userSystemManager;
@Mock
protected WorkbenchMenuBarPresenter menuBar;
@Mock
protected SyncBeanManager iocManager;
@Mock
protected Workbench workbench;
@Mock
protected PermissionTreeSetup permissionTreeSetup;
@Mock
protected DefaultAdminPageHelper adminPageHelper;
private KieDroolsWorkbenchEntryPoint kieDroolsWorkbenchEntryPoint;
@Before
public void setup() {
doNothing().when( pmas ).initActivities( anyList() );
doReturn( Boolean.TRUE ).when( socialConfigurationService ).isSocialEnable();
doAnswer( invocationOnMock -> {
( ( Command ) invocationOnMock.getArguments()[0] ).execute();
return null;
} ).when( userSystemManager ).waitForInitialization( any( Command.class ) );
appConfigServiceCallerMock = new CallerMock<>( appConfigService );
socialConfigurationServiceCallerMock = new CallerMock<>( socialConfigurationService );
pmasCallerMock = new CallerMock<>( pmas );
kieDroolsWorkbenchEntryPoint = spy( new KieDroolsWorkbenchEntryPoint( appConfigServiceCallerMock,
pmasCallerMock,
activityBeansCache,
homeProducer,
socialConfigurationServiceCallerMock,
menusHelper,
userSystemManager,
menuBar,
iocManager,
workbench,
permissionTreeSetup,
adminPageHelper ) );
mockMenuHelper();
mockConstants();
IocTestingUtils.mockIocManager( iocManager );
doNothing().when( kieDroolsWorkbenchEntryPoint ).hideLoadingPopup();
}
@Test
public void initTest() {
kieDroolsWorkbenchEntryPoint.init();
verify( workbench ).addStartupBlocker( KieDroolsWorkbenchEntryPoint.class );
verify( homeProducer ).init();
}
@Test
public void setupMenuTest() {
kieDroolsWorkbenchEntryPoint.setupMenu();
ArgumentCaptor<Menus> menusCaptor = ArgumentCaptor.forClass( Menus.class );
verify( menuBar ).addMenus( menusCaptor.capture() );
Menus menus = menusCaptor.getValue();
assertEquals( 5, menus.getItems().size() );
assertEquals( kieDroolsWorkbenchEntryPoint.constants.home(), menus.getItems().get( 0 ).getCaption() );
assertEquals( kieDroolsWorkbenchEntryPoint.constants.authoring(), menus.getItems().get( 1 ).getCaption() );
assertEquals( kieDroolsWorkbenchEntryPoint.constants.deploy(), menus.getItems().get( 2 ).getCaption() );
assertEquals( kieDroolsWorkbenchEntryPoint.constants.extensions(), menus.getItems().get( 3 ).getCaption() );
verify( menusHelper ).addRolesMenuItems();
verify( menusHelper ).addWorkbenchViewModeSwitcherMenuItem();
verify( menusHelper ).addWorkbenchConfigurationMenuItem();
verify( menusHelper ).addUtilitiesMenuItems();
verify( workbench ).removeStartupBlocker( KieDroolsWorkbenchEntryPoint.class );
}
@Test
public void getDeploymentViewsTest() {
List<? extends MenuItem> deploymentMenuItems = kieDroolsWorkbenchEntryPoint.getDeploymentViews();
assertEquals( 1, deploymentMenuItems.size() );
assertEquals( kieDroolsWorkbenchEntryPoint.constants.ExecutionServers(), deploymentMenuItems.get( 0 ).getCaption() );
}
private void mockMenuHelper() {
final ArrayList<MenuItem> menuItems = new ArrayList<>();
menuItems.add( mock( MenuItem.class ) );
doReturn( menuItems ).when( menusHelper ).getHomeViews( anyBoolean() );
doReturn( menuItems ).when( menusHelper ).getAuthoringViews();
doReturn( menuItems ).when( menusHelper ).getExtensionsViews();
}
private void mockConstants() {
kieDroolsWorkbenchEntryPoint.constants = mock( AppConstants.class, new ConstantsAnswerMock() );
}
}
| {
"content_hash": "fdb12cca8c24793db066862b35674b3f",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 125,
"avg_line_length": 41.64848484848485,
"alnum_prop": 0.6613795110593713,
"repo_name": "psiroky/kie-wb-distributions",
"id": "90c86b44ef9698f3c4b0340cd80536be42ce7069",
"size": "7493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kie-drools-wb/kie-drools-wb-webapp/src/test/java/org/kie/workbench/drools/client/KieDroolsWorkbenchEntryPointTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "42366"
},
{
"name": "HTML",
"bytes": "28266"
},
{
"name": "Java",
"bytes": "421518"
},
{
"name": "JavaScript",
"bytes": "14753"
}
],
"symlink_target": ""
} |
package lila.app
import akka.actor._
import com.typesafe.config.Config
final class Env(
config: Config,
system: ActorSystem,
appPath: String) {
val CliUsername = config getString "cli.username"
private val RendererName = config getString "app.renderer.name"
private val RouterName = config getString "app.router.name"
private val WebPath = config getString "app.web_path"
lazy val bus = lila.common.Bus(system)
lazy val preloader = new mashup.Preload(
tv = Env.tv.tv,
leaderboard = Env.user.cached.topToday,
tourneyWinners = Env.tournament.winners.scheduled,
timelineEntries = Env.timeline.entryRepo.userEntries _,
dailyPuzzle = Env.puzzle.daily,
streamsOnAir = () => Env.tv.streamsOnAir,
ongoingRelays = () => Env.relay.cached.miniStarted,
countRounds = Env.round.count,
lobbyApi = Env.api.lobbyApi,
getPlayban = Env.playban.api.currentBan _)
lazy val userInfo = mashup.UserInfo(
countUsers = () => Env.user.countEnabled,
bookmarkApi = Env.bookmark.api,
relationApi = Env.relation.api,
trophyApi = Env.user.trophyApi,
gameCached = Env.game.cached,
crosstableApi = Env.game.crosstableApi,
postApi = Env.forum.postApi,
getRatingChart = Env.history.ratingChartApi.apply,
getRanks = Env.user.cached.ranking.getAll,
isDonor = Env.donation.isDonor,
isHostingSimul = Env.simul.isHosting) _
system.actorOf(Props(new actor.Renderer), name = RendererName)
system.actorOf(Props(new actor.Router(
baseUrl = Env.api.Net.BaseUrl,
protocol = Env.api.Net.Protocol,
domain = Env.api.Net.Domain
)), name = RouterName)
if (!Env.ai.ServerOnly) {
loginfo("[boot] Preloading modules")
List(Env.socket,
Env.site,
Env.tournament,
Env.lobby,
Env.game,
Env.setup,
Env.round,
Env.team,
Env.message,
Env.timeline,
Env.gameSearch,
Env.teamSearch,
Env.forumSearch,
Env.relation,
Env.report,
Env.notification,
Env.bookmark,
Env.pref,
Env.chat,
Env.puzzle,
Env.tv,
Env.blog,
Env.video,
Env.shutup, // required to load the actor
Env.relay
)
loginfo("[boot] Preloading complete")
}
if (Env.ai.ServerOnly) println("Running as AI server")
// if (config getBoolean "simulation.enabled") {
// lila.simulation.Env.current.start
// }
}
object Env {
lazy val current = "[boot] app" describes new Env(
config = lila.common.PlayApp.loadConfig,
system = lila.common.PlayApp.system,
appPath = lila.common.PlayApp withApp (_.path.getCanonicalPath))
def api = lila.api.Env.current
def db = lila.db.Env.current
def user = lila.user.Env.current
def security = lila.security.Env.current
def wiki = lila.wiki.Env.current
def hub = lila.hub.Env.current
def socket = lila.socket.Env.current
def message = lila.message.Env.current
def notification = lila.notification.Env.current
def i18n = lila.i18n.Env.current
def game = lila.game.Env.current
def bookmark = lila.bookmark.Env.current
def search = lila.search.Env.current
def gameSearch = lila.gameSearch.Env.current
def timeline = lila.timeline.Env.current
def forum = lila.forum.Env.current
def forumSearch = lila.forumSearch.Env.current
def team = lila.team.Env.current
def teamSearch = lila.teamSearch.Env.current
def ai = lila.ai.Env.current
def analyse = lila.analyse.Env.current
def mod = lila.mod.Env.current
def monitor = lila.monitor.Env.current
def site = lila.site.Env.current
def round = lila.round.Env.current
def lobby = lila.lobby.Env.current
def setup = lila.setup.Env.current
def importer = lila.importer.Env.current
def tournament = lila.tournament.Env.current
def simul = lila.simul.Env.current
def relation = lila.relation.Env.current
def report = lila.report.Env.current
def pref = lila.pref.Env.current
def chat = lila.chat.Env.current
def puzzle = lila.puzzle.Env.current
def coordinate = lila.coordinate.Env.current
def tv = lila.tv.Env.current
def blog = lila.blog.Env.current
def donation = lila.donation.Env.current
def qa = lila.qa.Env.current
def history = lila.history.Env.current
def worldMap = lila.worldMap.Env.current
def opening = lila.opening.Env.current
def video = lila.video.Env.current
def playban = lila.playban.Env.current
def shutup = lila.shutup.Env.current
def relay = lila.relay.Env.current
}
| {
"content_hash": "55e0fa8938e765960f090204a1b82ad5",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 68,
"avg_line_length": 31,
"alnum_prop": 0.6989247311827957,
"repo_name": "systemovich/lila",
"id": "a0bc4346481835560d27646d9a3962bb40749629",
"size": "4464",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/Env.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "849"
},
{
"name": "CSS",
"bytes": "217388"
},
{
"name": "Cycript",
"bytes": "3701"
},
{
"name": "Emacs Lisp",
"bytes": "30520"
},
{
"name": "Erlang",
"bytes": "19825"
},
{
"name": "Fancy",
"bytes": "119"
},
{
"name": "GAP",
"bytes": "11334"
},
{
"name": "GLSL",
"bytes": "2434"
},
{
"name": "HTML",
"bytes": "324564"
},
{
"name": "Hy",
"bytes": "20591"
},
{
"name": "Io",
"bytes": "4943"
},
{
"name": "Java",
"bytes": "21183"
},
{
"name": "JavaScript",
"bytes": "386363"
},
{
"name": "Makefile",
"bytes": "15207"
},
{
"name": "Mathematica",
"bytes": "18453"
},
{
"name": "NewLisp",
"bytes": "19130"
},
{
"name": "OCaml",
"bytes": "1709"
},
{
"name": "Perl6",
"bytes": "19664"
},
{
"name": "PostScript",
"bytes": "2604"
},
{
"name": "Python",
"bytes": "1959"
},
{
"name": "Ruby",
"bytes": "31034"
},
{
"name": "Scala",
"bytes": "1562558"
},
{
"name": "Shell",
"bytes": "9923"
},
{
"name": "Slash",
"bytes": "18065"
},
{
"name": "Smalltalk",
"bytes": "18975"
},
{
"name": "SystemVerilog",
"bytes": "17783"
}
],
"symlink_target": ""
} |
@include("admin.layout.header")
<!-- iCheck -->
{!! Html::style('plugins/iCheck/square/blue.css'); !!}
<title>Панель приборов</title>
</head>
<body class="hold-transition sidebar-mini skin-red-light">
<div class="wrapper">
@include("admin.layout.topmenu")
@include("admin.layout.navbar")
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Создание продукта
</h1>
<ol class="breadcrumb">
<li><a href="{{URL::to('/')}}">{{Setting::get('config.sitename')}}</a></li>
<li>Список продуктов</li>
<li class="active">Создание продукта</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-9">
<div class="box">
<div class="box-header">
<h3 class="box-title">Информация о продукте</h3>
</div>
<div class="box-body">
{!! Form::model($product, array('action' => array('ContentController@updateProduct', $product->id), 'method'=> 'PATCH', 'files'=>true, 'class'=>'form-horizontal')) !!}
<div class="form-group @if ($errors->has('name')) has-error @endif">
{!! Form::label('name', 'Название', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-4">
{!! Form::text('name', null, array('class'=>'form-control')) !!}
@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif
</div>
{!! Form::label('price', 'Цена', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-2">{!! Form::text('price', null, array('class'=>'form-control')) !!}
</div>
</div>
<div class="form-group">
<label for="inputPassword4" class="col-sm-3 control-label">Категория</label>
<div class="col-md-4">
{!! Form::select('categories_id', $CatList, Null, array('class'=>'form-control input-sm select2', 'style'=>'width: 100%')) !!}
</div>
{!! Form::label('price_old', 'Старая цена', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-2">{!! Form::text('price_old', null, array('class'=>'form-control')) !!}
</div>
</div>
<div class="form-group">
<label for="inputPassword4" class="col-sm-3 control-label">Опции цен</label>
<div class="col-md-9">
{!! Form::select('opts[]', $opt_arr, $myopt_arr, array('class'=>'form-control input-sm select2', 'style'=>'width: 100%', 'multiple'=>'multiple')) !!}
</div>
</div>
<div class="form-group @if ($errors->has('urlhash')) has-error @endif">
{!! Form::label('urlhash', 'URL-имя', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">{!! URL::to('/') !!}/</span>
{!! Form::text('urlhash', null, array('class'=>'form-control')) !!}
<span class="input-group-addon">.html</span>
</div>
@if ($errors->has('urlhash')) <p class="help-block">{{ $errors->first('urlhash') }}</p> @endif
</div>
</div>
<div class="form-group @if ($errors->has('cover')) has-error @endif">
{!! Form::label('cover', 'Изображение', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-2"><img style="max-height: 50px;" class="img responsive"
@if ($product->cover)
src="{{ asset('files/products/img/small/'.$product->cover) }}"
@else
src="{{ asset('dist/img/boxed-bg.png') }}"
@endif
>
</div>
<div class="col-sm-3">
{!! Form::file('cover', null, array('class'=>'form-control')) !!}
@if ($errors->has('cover')) <p class="help-block">{{ $errors->first('cover') }}</p> @endif
</div>
{!! Form::label('label', 'Label', array('class'=>'col-sm-2 control-label')) !!}
<div class="col-sm-2">
{!! Form::text('label', null, array('class'=>'form-control')) !!}
@if ($errors->has('label')) <p class="help-block">{{ $errors->first('label') }}</p> @endif
</div>
</div>
<div class="form-group @if ($errors->has('description')) has-error @endif">
{!! Form::label('description', 'Описание', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::textarea('description', null, array('class'=>'form-control', 'rows'=>'2')) !!}
@if ($errors->has('description')) <p class="help-block">{{ $errors->first('description') }}</p> @endif
</div>
</div>
<div class="form-group @if ($errors->has('description_full')) has-error @endif">
{!! Form::label('description_full', 'Детальное описание', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::textarea('description_full', null, array('class'=>'form-control', 'rows'=>'2')) !!}
@if ($errors->has('description_full')) <p class="help-block">{{ $errors->first('description_full') }}</p> @endif
</div>
</div>
<div class="form-group @if ($errors->has('values')) has-error @endif">
{!! Form::label('values', 'Свойства', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::textarea('values', null, array('class'=>'form-control', 'rows'=>'2')) !!}
@if ($errors->has('values')) <p class="help-block">{{ $errors->first('values') }}</p> @endif
</div>
</div>
<hr>
<div class="form-group @if ($errors->has('title')) has-error @endif">
{!! Form::label('title', 'Title', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::text('title', null, array('class'=>'form-control')) !!}
@if ($errors->has('title')) <p class="help-block">{{ $errors->first('title') }}</p> @endif
</div>
</div>
<div class="form-group @if ($errors->has('keywords')) has-error @endif">
{!! Form::label('keywords', 'Keywords', array('class'=>'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::text('keywords', null, array('class'=>'form-control')) !!}
@if ($errors->has('keywords')) <p class="help-block">{{ $errors->first('keywords') }}</p> @endif
</div>
</div>
<hr>
<div class="form-group">
<label for="inputPassword4" class="col-sm-3 control-label">Сопутствующие товары</label>
<div class="col-md-9">
{!! Form::select('related[]', $Prods, $myProds, array('class'=>'form-control input-sm select2', 'style'=>'width: 100%', 'multiple'=>'multiple')) !!}
</div>
</div>
<div class="form-group">
<label for="inputPassword4" class="col-sm-3 control-label">В наличии</label>
<div class="col-md-9">
<label class="col-md-12">
{!! Form::checkbox('isset', 'true', null, array('class' => 'minimal')); !!}
есть
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-8">
{!! HTML::decode(Form::button('Сохранить', array('type' => 'submit', 'class'=>'btn btn-success'))) !!}
</div>
</div>
{!! Form::close(); !!}
</div>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</section>
<!-- /.content -->
</div>
@include("admin.layout.footer")
<!-- iCheck -->
{!! Html::script('plugins/iCheck/icheck.min.js'); !!}
<!-- page script -->
<script type="text/javascript">
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
$(".select2").select2({
maximumSelectionSize: 4
});
</script>
</body>
</html> | {
"content_hash": "fbe9882416a69702b09b923f9b420ea0",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 195,
"avg_line_length": 59.5945945945946,
"alnum_prop": 0.38249433106575964,
"repo_name": "ZENLIX/LaraShop",
"id": "503d84ef9f35b1de1c4a35b7bf594fb5517fcdbb",
"size": "11231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "laravel/resources/views/admin/content/productEdit.blade.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "203570"
},
{
"name": "HTML",
"bytes": "3005017"
},
{
"name": "JavaScript",
"bytes": "4090890"
},
{
"name": "PHP",
"bytes": "1389300"
},
{
"name": "Python",
"bytes": "32324"
}
],
"symlink_target": ""
} |
package all
import _ "github.com/influxdata/telegraf/plugins/inputs/nomad" // register plugin
| {
"content_hash": "eb913b5ecc32e743705f122b37e1d0aa",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 81,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.7894736842105263,
"repo_name": "influxdata/telegraf",
"id": "769c18df40f898105206fac043c9d36248e99c20",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/inputs/all/nomad.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1067"
},
{
"name": "Go",
"bytes": "9722072"
},
{
"name": "Makefile",
"bytes": "15617"
},
{
"name": "PowerShell",
"bytes": "1385"
},
{
"name": "Ragel",
"bytes": "10377"
},
{
"name": "Ruby",
"bytes": "1981"
},
{
"name": "Shell",
"bytes": "32388"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>isMaxLength</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../../../";</script> <script>const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<link href="../../../../styles/prism.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async></script>
<script type="text/javascript" src="../../../../scripts/main.js" defer></script>
<script type="text/javascript" src="../../../../scripts/prism.js" async></script>
<script type="text/javascript" src="../../../../scripts/symbol-parameters-wrapper_deferred.js" defer></script></head>
<body>
<div class="navigation-wrapper" id="navigation-wrapper">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<div class="library-name">
<a href="../../../../index.html">
<span>stripe-android</span> </a> </div>
<div>
</div>
<div class="pull-right d-flex">
<button id="theme-toggle-button"><span id="theme-toggle"></span></button>
<div id="searchBar"></div>
</div>
</div>
<div id="container">
<div id="leftColumn">
<div id="sideMenu"></div>
</div>
<div id="main">
<div class="main-content" id="content" pageids="payments-model::com.stripe.android.cards/CardNumber.Unvalidated/isMaxLength/#/PointingToDeclaration//617549930">
<div class="breadcrumbs"><a href="../../../index.html">payments-model</a><span class="delimiter">/</span><a href="../../index.html">com.stripe.android.cards</a><span class="delimiter">/</span><a href="../index.html">CardNumber</a><span class="delimiter">/</span><a href="index.html">Unvalidated</a><span class="delimiter">/</span><span class="current">isMaxLength</span></div>
<div class="cover ">
<h1 class="cover"><span>is</span><wbr><span>Max</span><wbr><span><span>Length</span></span></h1>
</div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-dependent-content" data-active="" data-togglable=":payments-model:dokkaHtmlPartial/release"><div class="symbol monospace"><span class="token keyword"></span><span class="token keyword">val </span><a href="is-max-length.html">isMaxLength</a><span class="token operator">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html">Boolean</a></div></div></div>
</div>
<div class="footer">
<span class="go-to-top-icon"><a href="#content" id="go-to-top-link"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span>
</div>
</div>
</div>
</body></html>
| {
"content_hash": "c78da918a57787765d0d62d5ca9d2e39",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 495,
"avg_line_length": 61.666666666666664,
"alnum_prop": 0.6453024453024453,
"repo_name": "stripe/stripe-android",
"id": "3daee6e18bef1e90c967dea11fb8180515d4d383",
"size": "3886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/payments-model/com.stripe.android.cards/-card-number/-unvalidated/is-max-length.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "67407"
},
{
"name": "Kotlin",
"bytes": "7720826"
},
{
"name": "Python",
"bytes": "13146"
},
{
"name": "Ruby",
"bytes": "5171"
},
{
"name": "Shell",
"bytes": "18256"
}
],
"symlink_target": ""
} |
<?php
/**
* Basic Template
*
* Template used for Special Groups. Will now be auto-created
* when admin switches group from type HUB to type Special.
*/
// define base path (without doc root)
$base = rtrim(str_replace(PATH_ROOT, '', __DIR__), DS);
// define base url for links
$baseLink = 'index.php?option=com_groups&cn=' . $this->group->get('cn');
// check to see if were supposed to no display html (template frame)
$no_html = Request::getInt('no_html', 0);
// add stylesheets and scripts
Document::addStyleSheet($base . DS . 'assets/css/main.css');
Document::addScript($base . DS . 'assets/js/main.js');
?>
<?php if (!$no_html) : ?>
<group:include type="content" scope="before" />
<div class="super-group-body-wrap group-<?php echo $this->group->get('cn'); ?>">
<div class="super-group-body">
<?php include_once 'includes/header.php'; ?>
<div class="super-group-content-wrap">
<div class="super-group-content group_<?php echo $this->tab; ?>">
<?php
$title = (isset($this->page) && $this->page->get('title')) ? $this->page->get('title') : Lang::txt('PLG_GROUPS_' . strtoupper($this->tab));
$title = ($title == 'PLG_GROUPS_' . strtoupper($this->tab) ? ucfirst($this->tab) : $title);
if ($title != '') :
?>
<h2><?php echo $title; ?></h2>
<?php endif; ?>
<?php endif; ?>
<!-- ### Start Content Include ### -->
<group:include type="content" />
<!-- ### End Content Include ### -->
<?php if (!$no_html) : ?>
</div>
</div>
<?php include_once 'includes/footer.php'; ?>
</div>
</div>
<group:include type="googleanalytics" account="" />
<?php endif; | {
"content_hash": "3c4c49783b6df9a468d8243e37368610",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 144,
"avg_line_length": 31.192307692307693,
"alnum_prop": 0.6054254007398274,
"repo_name": "zooley/hubzero-cms",
"id": "d0faebc17e1a3340ff906652dba67a57957ae0a4",
"size": "1622",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "core/components/com_groups/super/default/template/index.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "171251"
},
{
"name": "AngelScript",
"bytes": "1638"
},
{
"name": "CSS",
"bytes": "2719736"
},
{
"name": "HTML",
"bytes": "1289374"
},
{
"name": "JavaScript",
"bytes": "12613354"
},
{
"name": "PHP",
"bytes": "24941743"
},
{
"name": "Shell",
"bytes": "10678"
},
{
"name": "TSQL",
"bytes": "572"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Add a new virtual domain</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.vpopmail-add-alias-domain.html">vpopmail_add_alias_domain</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.vpopmail-add-domain.html">vpopmail_add_domain</a></div>
<div class="up"><a href="ref.vpopmail.html">vpopmail Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.vpopmail-add-domain-ex" class="refentry">
<div class="refnamediv">
<h1 class="refname">vpopmail_add_domain_ex</h1>
<p class="verinfo">(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)</p><p class="refpurpose"><span class="refname">vpopmail_add_domain_ex</span> — <span class="dc-title">Add a new virtual domain</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.vpopmail-add-domain-ex-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">bool</span> <span class="methodname"><strong>vpopmail_add_domain_ex</strong></span>
( <span class="methodparam"><span class="type">string</span> <code class="parameter">$domain</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$passwd</code></span>
[, <span class="methodparam"><span class="type">string</span> <code class="parameter">$quota</code></span>
[, <span class="methodparam"><span class="type">string</span> <code class="parameter">$bounce</code></span>
[, <span class="methodparam"><span class="type">bool</span> <code class="parameter">$apop</code></span>
]]] )</div>
<div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is
<em class="emphasis">EXPERIMENTAL</em>. The behaviour of this function, its name, and
surrounding documentation may change without notice in a future release of PHP.
This function should be used at your own risk.
</p></div>
<div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is
currently not documented; only its argument list is available.
</p></div>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.vpopmail-add-alias-domain.html">vpopmail_add_alias_domain</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.vpopmail-add-domain.html">vpopmail_add_domain</a></div>
<div class="up"><a href="ref.vpopmail.html">vpopmail Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| {
"content_hash": "1f4de1ef967d5908c4382535135964bf",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 209,
"avg_line_length": 65.22222222222223,
"alnum_prop": 0.6984667802385008,
"repo_name": "dpkshrma/phpdox",
"id": "95c9888af8793ebb5ce395065955b1e73de447ac",
"size": "2935",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "functions/function.vpopmail-add-domain-ex.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "26553092"
},
{
"name": "PHP",
"bytes": "8567"
},
{
"name": "Shell",
"bytes": "286"
}
],
"symlink_target": ""
} |
package API.amazon.mws.products.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://mws.amazonservices.com/schema/Products/2011-10-01}GetLowestOfferListingsForSKUResult" maxOccurs="unbounded"/>
* <element ref="{http://mws.amazonservices.com/schema/Products/2011-10-01}ResponseMetadata"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"getLowestOfferListingsForSKUResult",
"responseMetadata"
})
@XmlRootElement(name = "GetLowestOfferListingsForSKUResponse")
public class GetLowestOfferListingsForSKUResponse {
@XmlElement(name = "GetLowestOfferListingsForSKUResult", required = true)
protected List<GetLowestOfferListingsForSKUResult> getLowestOfferListingsForSKUResult;
@XmlElement(name = "ResponseMetadata", required = true)
protected ResponseMetadata responseMetadata;
/**
* Default constructor
*
*/
public GetLowestOfferListingsForSKUResponse() {
super();
}
/**
* Value constructor
*
*/
public GetLowestOfferListingsForSKUResponse(final List<GetLowestOfferListingsForSKUResult> getLowestOfferListingsForSKUResult, final ResponseMetadata responseMetadata) {
this.getLowestOfferListingsForSKUResult = getLowestOfferListingsForSKUResult;
this.responseMetadata = responseMetadata;
}
/**
* Gets the value of the getLowestOfferListingsForSKUResult property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the getLowestOfferListingsForSKUResult property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGetLowestOfferListingsForSKUResult().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link GetLowestOfferListingsForSKUResult }
*
*
*/
public List<GetLowestOfferListingsForSKUResult> getGetLowestOfferListingsForSKUResult() {
if (getLowestOfferListingsForSKUResult == null) {
getLowestOfferListingsForSKUResult = new ArrayList<GetLowestOfferListingsForSKUResult>();
}
return this.getLowestOfferListingsForSKUResult;
}
public boolean isSetGetLowestOfferListingsForSKUResult() {
return ((this.getLowestOfferListingsForSKUResult!= null)&&(!this.getLowestOfferListingsForSKUResult.isEmpty()));
}
public void unsetGetLowestOfferListingsForSKUResult() {
this.getLowestOfferListingsForSKUResult = null;
}
/**
* Gets the value of the responseMetadata property.
*
* @return
* possible object is
* {@link ResponseMetadata }
*
*/
public ResponseMetadata getResponseMetadata() {
return responseMetadata;
}
/**
* Sets the value of the responseMetadata property.
*
* @param value
* allowed object is
* {@link ResponseMetadata }
*
*/
public void setResponseMetadata(ResponseMetadata value) {
this.responseMetadata = value;
}
public boolean isSetResponseMetadata() {
return (this.responseMetadata!= null);
}
/**
* Sets the value of the GetLowestOfferListingsForSKUResult property.
*
* @param values
* @return
* this instance
*/
public GetLowestOfferListingsForSKUResponse withGetLowestOfferListingsForSKUResult(GetLowestOfferListingsForSKUResult... values) {
for (GetLowestOfferListingsForSKUResult value: values) {
getGetLowestOfferListingsForSKUResult().add(value);
}
return this;
}
/**
* Sets the value of the ResponseMetadata property.
*
* @param value
* @return
* this instance
*/
public GetLowestOfferListingsForSKUResponse withResponseMetadata(ResponseMetadata value) {
setResponseMetadata(value);
return this;
}
/**
* Sets the value of the getLowestOfferListingsForSKUResult property.
*
* @param getLowestOfferListingsForSKUResult
* allowed object is
* {@link GetLowestOfferListingsForSKUResult }
*
*/
public void setGetLowestOfferListingsForSKUResult(List<GetLowestOfferListingsForSKUResult> getLowestOfferListingsForSKUResult) {
this.getLowestOfferListingsForSKUResult = getLowestOfferListingsForSKUResult;
}
@javax.xml.bind.annotation.XmlTransient
private ResponseHeaderMetadata responseHeaderMetadata;
/**
* Checks whether the ResponseHeaderMetadata field has been set.
*/
public boolean isSetResponseHeaderMetadata() {
return this.responseHeaderMetadata != null;
}
/**
* Sets the ResponseHeaderMetadata field.
*/
public void setResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
this.responseHeaderMetadata = responseHeaderMetadata;
}
/**
* Gets the ResponseHeaderMetadata field.
*/
public ResponseHeaderMetadata getResponseHeaderMetadata() {
return responseHeaderMetadata;
}
/**
*
* XML string representation of this object
*
* @return XML String
*/
public String toXML() {
StringBuffer xml = new StringBuffer();
xml.append("<GetLowestOfferListingsForSKUResponse xmlns=\"http://mws.amazonservices.com/schema/Products/2011-10-01\">");
java.util.List<GetLowestOfferListingsForSKUResult> getLowestOfferListingsForSKUResultList = getGetLowestOfferListingsForSKUResult();
for (GetLowestOfferListingsForSKUResult getLowestOfferListingsForSKUResult : getLowestOfferListingsForSKUResultList) {
xml.append("<GetLowestOfferListingsForSKUResult " + (getLowestOfferListingsForSKUResult.isSetSellerSKU() ? " SellerSKU=" + "\"" + escapeXML(getLowestOfferListingsForSKUResult.getSellerSKU()) + "\"" : "") + " " + (getLowestOfferListingsForSKUResult.isSetStatus() ? " status=" + "\"" + escapeXML(getLowestOfferListingsForSKUResult.getStatus()) + "\"" : "") + ">");
xml.append(getLowestOfferListingsForSKUResult.toXMLFragment());
xml.append("</GetLowestOfferListingsForSKUResult>");
}
if (isSetResponseMetadata()) {
ResponseMetadata responseMetadata = getResponseMetadata();
xml.append("<ResponseMetadata>");
xml.append(responseMetadata.toXMLFragment());
xml.append("</ResponseMetadata>");
}
xml.append("</GetLowestOfferListingsForSKUResponse>");
return xml.toString();
}
/**
*
* Escape XML special characters
*/
private String escapeXML(String string) {
if (string == null)
return "null";
StringBuffer sb = new StringBuffer();
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
*
* JSON string representation of this object
*
* @return JSON String
*/
public String toJSON() {
StringBuffer json = new StringBuffer();
json.append("{\"GetLowestOfferListingsForSKUResponse\" : {");
json.append(quoteJSON("@xmlns"));
json.append(" : ");
json.append(quoteJSON("http://mws.amazonservices.com/schema/Products/2011-10-01"));
boolean first = true;
json.append(", ");
if (isSetGetLowestOfferListingsForSKUResult()) {
if (!first) json.append(", ");
json.append("\"GetLowestOfferListingsForSKUResult\" : [");
java.util.List<GetLowestOfferListingsForSKUResult> getLowestOfferListingsForSKUResultList = getGetLowestOfferListingsForSKUResult();
int getLowestOfferListingsForSKUResultListIndex = 0;
for (GetLowestOfferListingsForSKUResult getLowestOfferListingsForSKUResult : getLowestOfferListingsForSKUResultList) {
if (getLowestOfferListingsForSKUResultListIndex > 0) json.append(", ");
json.append("{");
json.append("");
json.append(getLowestOfferListingsForSKUResult.toJSONFragment());
json.append("}");
first = false;
++getLowestOfferListingsForSKUResultListIndex;
}
json.append("]");
}
if (isSetResponseMetadata()) {
if (!first) json.append(", ");
json.append("\"ResponseMetadata\" : {");
ResponseMetadata responseMetadata = getResponseMetadata();
json.append(responseMetadata.toJSONFragment());
json.append("}");
first = false;
}
json.append("}");
json.append("}");
return json.toString();
}
/**
*
* Quote JSON string
*/
private String quoteJSON(String string) {
if (string == null)
return "null";
StringBuffer sb = new StringBuffer();
sb.append("\"");
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < ' ') {
sb.append("\\u" + String.format("%03x", Integer.valueOf(c)));
} else {
sb.append(c);
}
}
}
sb.append("\"");
return sb.toString();
}
}
| {
"content_hash": "416a9643125744d62c1e3b8aacb15622",
"timestamp": "",
"source": "github",
"line_count": 351,
"max_line_length": 374,
"avg_line_length": 32.717948717948715,
"alnum_prop": 0.6014454893765239,
"repo_name": "VDuda/SyncRunner-Pub",
"id": "42f7356e4cf5224fa840f76e8c6b12eaa8adaf7c",
"size": "11484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/API/amazon/mws/products/model/GetLowestOfferListingsForSKUResponse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "11076554"
}
],
"symlink_target": ""
} |
casper.options.viewportSize = {
width : 1280,
height : 800
};
casper.on('page.initialized', function( page ) {
this.evaluate(function() {
var isFunction = function(o) {
return typeof o == 'function';
},
bind,
slice = [].slice,
proto = Function.prototype,
featureMap = {
'function-bind': 'bind'
};
function has(feature) {
var prop = featureMap[feature];
return isFunction(proto[prop]);
}
// check for missing features
if (!has('function-bind')) {
// adapted from Mozilla Developer Network example at
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
bind = function bind(obj) {
var args = slice.call(arguments, 1),
self = this,
nop = function() {},
bound = function() {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
};
nop.prototype = this.prototype || {}; // Firefox cries sometimes if prototype is undefined
bound.prototype = new nop();
return bound;
};
proto.bind = bind;
}
});
});
var stamp = (function () {
var i = 0;
return function () {
return ++i;
};
})();
var template = function (input, variables) {
for (var i = 0, len = variables.length; i < len; i++) {
var item = variables[i];
input = input.replace(/%[sd]/, item);
}
return input;
};
var newImageFilename = function ( alt ) {
return template('tests/screenshots/casper-%d.png', [alt || stamp()]);
};
var capture = function (alt) {
var filename = newImageFilename( alt );
casper.capture( filename );
casper.test.comment( filename.replace('tests/screenshots/', '') );
};
casper.on("page.error", function(msg, trace) {
if (msg === 'WebGL not supported' ||
msg.match(/^ReferenceError.*?Uint8ClampedArray$/)) {
// we know
return;
}
this.echo("Error: " + msg, "ERROR");
});
casper.test.on("fail", function(failure) {
failure.message = "Message : " + failure.message + "\nLine : " + failure.line + "\nCode : " + failure.lineContents;
}); | {
"content_hash": "e109766b65bd1f0afc0448ae1bf4e386",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 120,
"avg_line_length": 30.531645569620252,
"alnum_prop": 0.525290215588723,
"repo_name": "ursudio/leaflet-webgl-heatmap",
"id": "520380339ddabb5fdf1dac01fcbe582d84d6fbd2",
"size": "2412",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "casper-helpers.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11546"
},
{
"name": "HTML",
"bytes": "5915"
},
{
"name": "JavaScript",
"bytes": "14471"
},
{
"name": "Shell",
"bytes": "432"
}
],
"symlink_target": ""
} |
This directory is used to store the generated model-related files:
* `*hparams.json` -- hyper parameters for models.
* `*.pkl` -- model files as python pickles. | {
"content_hash": "c26c68a5b2c30212595ff098e5dbabf5",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 66,
"avg_line_length": 54.666666666666664,
"alnum_prop": 0.7195121951219512,
"repo_name": "conversationai/unintended-ml-bias-analysis",
"id": "a11f970c98b998b7cf6c7f8556fb2476c306f751",
"size": "164",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "archive/models/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "6075275"
},
{
"name": "Python",
"bytes": "66594"
},
{
"name": "Shell",
"bytes": "860"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/home/jasper/Development/EdhrouterRedux/android/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-sq-rAL/values-sq-rAL.xml -->
<eat-comment/>
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"Orientohu për në shtëpi"</string>
<string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string>
<string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"Ngjitu lart"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Opsione të tjera"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"U krye!"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Shikoji të gjitha"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Zgjidh një aplikacion"</string>
<string msgid="7723749260725869598" name="abc_search_hint">"Kërko..."</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"Pastro pyetjen"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"Kërko pyetjen"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"Kërko"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"Dërgo pyetjen"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"Kërkim me zë"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Shpërnda publikisht me"</string>
<string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Shpërnda publikisht me %s"</string>
<string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Shpalos"</string>
<string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string>
</resources> | {
"content_hash": "2d64a884fae69bb5f112185acd2edd01",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 184,
"avg_line_length": 95.30434782608695,
"alnum_prop": 0.7531934306569343,
"repo_name": "cablegunmaster/Simple-Redux-Boilerplate",
"id": "bc7da99de80a3993b62b81e1bf661d2f2c2f0fd8",
"size": "2206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/app/build/intermediates/res/merged/debug/values-sq-rAL/values-sq-rAL.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "578924"
},
{
"name": "JavaScript",
"bytes": "31313"
},
{
"name": "Objective-C",
"bytes": "4975"
}
],
"symlink_target": ""
} |
/* Database.js
KC3改 Indexed Database
Used to log player information for later use on Strategy Room
Uses Dexie.js third-party plugin on the assets directory
*/
(function(){
"use strict";
window.KC3Database = {
index: 0,
con:{},
init :function( defaultUser ){
this.con = new Dexie("KC3");
if(typeof defaultUser !== "undefined"){
this.index = defaultUser;
}
this.con.version(1).stores({
account: "++id,&hq,server,mid,name",
build: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
lsc: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,devmat,result,time",
sortie: "++id,hq,world,mapnum,fleetnum,combined,fleet1,fleet2,time",
battle: "++id,hq,sortie_id,node,data,yasen,rating,drop,time",
resource: "++id,hq,rsc1,rsc2,rsc3,rsc4,hour",
useitem: "++id,hq,torch,screw,bucket,devmat,hour"
});
this.con.version(2).stores({
account: "++id,&hq,server,mid,name",
build: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
lsc: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,devmat,result,time",
sortie: "++id,hq,world,mapnum,fleetnum,combined,fleet1,fleet2,fleet3,fleet4,support1,support2,time",
battle: "++id,hq,sortie_id,node,data,yasen,rating,drop,time",
resource: "++id,hq,rsc1,rsc2,rsc3,rsc4,hour",
useitem: "++id,hq,torch,screw,bucket,devmat,hour",
screenshots: "++id,hq,imgur,ltime"
}).upgrade(function(t){});
this.con.version(3).stores({
account: "++id,&hq,server,mid,name",
build: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
lsc: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,devmat,result,time",
sortie: "++id,hq,world,mapnum,fleetnum,combined,fleet1,fleet2,fleet3,fleet4,support1,support2,time",
battle: "++id,hq,sortie_id,node,data,yasen,rating,drop,time",
resource: "++id,hq,rsc1,rsc2,rsc3,rsc4,hour",
useitem: "++id,hq,torch,screw,bucket,devmat,hour",
screenshots: "++id,hq,imgur,ltime",
develop: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time"
}).upgrade(function(t){});
this.con.version(4).stores({
account: "++id,&hq,server,mid,name",
build: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
lsc: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,devmat,result,time",
sortie: "++id,hq,world,mapnum,fleetnum,combined,fleet1,fleet2,fleet3,fleet4,support1,support2,time",
battle: "++id,hq,sortie_id,node,enemyId,data,yasen,rating,drop,time",
resource: "++id,hq,rsc1,rsc2,rsc3,rsc4,hour",
useitem: "++id,hq,torch,screw,bucket,devmat,hour",
screenshots: "++id,hq,imgur,ltime",
develop: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time"
}).upgrade(function(t){});
this.con.version(5).stores({
account: "++id,&hq,server,mid,name",
build: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
lsc: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,devmat,result,time",
sortie: "++id,hq,world,mapnum,fleetnum,combined,fleet1,fleet2,fleet3,fleet4,support1,support2,time",
battle: "++id,hq,sortie_id,node,enemyId,data,yasen,rating,drop,time",
resource: "++id,hq,rsc1,rsc2,rsc3,rsc4,hour",
useitem: "++id,hq,torch,screw,bucket,devmat,hour",
screenshots: "++id,hq,imgur,ltime",
develop: "++id,hq,flag,rsc1,rsc2,rsc3,rsc4,result,time",
newsfeed: "++id,hq,type,message,time",
}).upgrade(function(t){});
this.con.open();
},
Newsfeed: function(data){
this.con.newsfeed.add({
hq: this.index,
type: data.type,
message: data.message,
time: data.time
});
},
Player :function(data){
var self = this;
// check if account exists
this.con.account
.where("hq")
.equals(this.index)
.count(function(NumRecords){
if(NumRecords == 0){
// insert if not yet on db
self.con.account.add({
hq: self.index,
server: data.server,
mid: parseInt(data.mid, 10),
name: data.name
});
}
});
},
Build :function(data){
data.hq = this.index;
this.con.build.add(data);
},
LSC :function(data){
data.hq = this.index;
this.con.lsc.add(data);
},
Sortie :function(data, callback){
data.hq = this.index;
this.con.sortie.add(data).then(callback);
},
Battle :function(data){
data.hq = this.index;
this.con.battle.add(data);
},
Resource :function(data){
data.hq = this.index;
this.con.resource.add(data);
},
Useitem :function(data, stime){
data.hq = this.index;
this.con.useitem.add(data);
},
Screenshot :function(imgur){
this.con.screenshots.add({
hq : this.index,
imgur : imgur,
ltime : Math.floor((new Date()).getTime()/1000),
});
},
Develop :function(data){
data.hq = this.index;
this.con.develop.add(data);
},
/* [GET] Retrive logs from Local DB
--------------------------------------------*/
get_build :function(pageNumber, callback){
var itemsPerPage = 30;
this.con.build
.where("hq").equals(this.index)
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(callback);
},
count_build: function(callback){
this.con.build
.where("hq").equals(this.index)
.count(callback);
},
get_lscs :function(pageNumber, callback){
var itemsPerPage = 30;
this.con.lsc
.where("hq").equals(this.index)
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(callback);
},
count_lscs: function(callback){
this.con.lsc
.where("hq").equals(this.index)
.count(callback);
},
count_normal_sorties: function(callback){
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world < 10 && sortie.mapnum<5; })
.count(callback);
},
get_normal_sorties :function(pageNumber, callback){
var itemsPerPage = 10;
var self = this;
var sortieIds = [], bctr, sortieIndexed = {};
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world < 10 && sortie.mapnum<5; })
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(function(sortieList){
// Compile all sortieIDs and indexify
for(bctr in sortieList){
sortieIds.push(sortieList[bctr].id);
sortieIndexed["s"+sortieList[bctr].id] = sortieList[bctr];
sortieIndexed["s"+sortieList[bctr].id].battles = [];
}
// Get all battles on those sorties
self.con.battle
.where("sortie_id").anyOf(sortieIds)
.toArray(function(battleList){
for(bctr in battleList){
if(typeof sortieIndexed["s"+battleList[bctr].sortie_id] != "undefined"){
sortieIndexed["s"+battleList[bctr].sortie_id].battles.push(battleList[bctr]);
}else{
console.error("orphan battle", battleList[bctr]);
}
}
callback(sortieIndexed);
});
});
},
count_world :function(world, callback){
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world == world; })
.count(callback);
},
get_world :function(world, pageNumber, callback){
var itemsPerPage = 10;
var self = this;
var sortieIds = [], bctr, sortieIndexed = {};
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world==world; })
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(function(sortieList){
// Compile all sortieIDs and indexify
for(bctr in sortieList){
sortieIds.push(sortieList[bctr].id);
sortieIndexed["s"+sortieList[bctr].id] = sortieList[bctr];
sortieIndexed["s"+sortieList[bctr].id].battles = [];
}
// Get all battles on those sorties
self.con.battle
.where("sortie_id").anyOf(sortieIds)
.toArray(function(battleList){
for(bctr in battleList){
if(typeof sortieIndexed["s"+battleList[bctr].sortie_id] != "undefined"){
sortieIndexed["s"+battleList[bctr].sortie_id].battles.push(battleList[bctr]);
}else{
console.error("orphan battle", battleList[bctr]);
}
}
callback(sortieIndexed);
});
});
},
count_map :function(world, map, callback){
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world == world && sortie.mapnum==map; })
.count(callback);
},
get_map :function(world, map, pageNumber, callback){
var itemsPerPage = 10;
var self = this;
var sortieIds = [], bctr, sortieIndexed = {};
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world==world && sortie.mapnum==map; })
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(function(sortieList){
// Compile all sortieIDs and indexify
for(bctr in sortieList){
sortieIds.push(sortieList[bctr].id);
sortieIndexed["s"+sortieList[bctr].id] = sortieList[bctr];
sortieIndexed["s"+sortieList[bctr].id].battles = [];
}
// Get all battles on those sorties
self.con.battle
.where("sortie_id").anyOf(sortieIds)
.toArray(function(battleList){
for(bctr in battleList){
if(typeof sortieIndexed["s"+battleList[bctr].sortie_id] != "undefined"){
sortieIndexed["s"+battleList[bctr].sortie_id].battles.push(battleList[bctr]);
}else{
console.error("orphan battle", battleList[bctr]);
}
}
callback(sortieIndexed);
});
});
},
get_sortie :function( sortie_id, callback ){
var self = this;
this.con.sortie
.where("id").equals(sortie_id)
.toArray(function(response){
if(response.length > 0){
// Get all battles on this sortie
self.con.battle
.where("sortie_id").equals(sortie_id)
.toArray(function(battleList){
response[0].battles = battleList;
callback(response[0]);
});
}else{
callback(false);
}
});
},
get_battle : function(mapArea, mapNo, battleNode, enemyId, callback) {
var sortieIds = [];
var bctr;
var self = this;
this.con.sortie
.where("hq").equals(this.index)
.and(function(sortie){ return sortie.world == mapArea && sortie.mapnum == mapNo; })
.toArray(function(sortieList){
// Compile all sortieIDs and indexify
for( bctr in sortieList){
sortieIds.push(sortieList[bctr].id);
}
var foundBattle;
var callback2 = callback;
// Get all battles on those sorties
self.con.battle
.where("sortie_id").anyOf(sortieIds)
.toArray(function(battleList){
for(bctr in battleList){
if (battleList[bctr].enemyId == enemyId) {
foundBattle = battleList[bctr];
break;
}
}
callback2(foundBattle);
});
});
},
get_enemy : function(enemyId, callback) {
var self = this;
this.con.battle
.where("enemyId").equals(enemyId)
.toArray(function(battleList){
if(battleList.length > 0){
battleList[0].data.api_ship_ke.splice(0, 1);
callback({
ids: battleList[0].data.api_ship_ke,
formation: battleList[0].data.api_formation[1]
});
}else{
callback(false);
}
});
},
get_resource :function(HourNow, callback){
var self = this;
this.con.resource
.where("hour").above(HourNow-720)
.toArray(function(response){
var callbackResponse = [];
var ctr;
for(ctr in response){
if(response[ctr].hq == self.index){
callbackResponse.push(response[ctr]);
}
}
callback(callbackResponse);
});
},
get_useitem :function(HourNow, callback){
var self = this;
this.con.useitem
.where("hour").above(HourNow-720)
.toArray(function(response){
var callbackResponse = [];
var ctr;
for(ctr in response){
if(response[ctr].hq == self.index){
callbackResponse.push(response[ctr]);
}
}
callback(callbackResponse);
});
},
get_devmt :function(pageNumber, callback){
var itemsPerPage = 25;
this.con.develop
.where("hq").equals(this.index)
.reverse()
.offset( (pageNumber-1)*itemsPerPage ).limit( itemsPerPage )
.toArray(callback);
},
count_devmt: function(callback){
this.con.develop
.where("hq").equals(this.index)
.count(callback);
},
get_sortie_page :function( world, map, page, callback ){
}
};
})(); | {
"content_hash": "28542fdffcb9350aa2c3c31183ffe25a",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 104,
"avg_line_length": 29.639908256880734,
"alnum_prop": 0.5949083030256133,
"repo_name": "VRarara/KC3Kai",
"id": "c3410200bdace7b60b8e65e578585561f2cfc5aa",
"size": "12925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/library/modules/Database.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "147564"
},
{
"name": "HTML",
"bytes": "114802"
},
{
"name": "JavaScript",
"bytes": "339887"
}
],
"symlink_target": ""
} |
This readme describes how the files in this testdata folder was created.
* bach-one_phrase-4_voices.xml: Consists of the first phrase of Aus meines
Herzens Grunde manually encoded in MuseScore and then exported as MusicXML.
* bach-one_phrase-note_sequence.tfrecord: This TFRecord was created by first
parsing the MusicXML file bach-one_phrase-4_voices.xml using music21, and
then using magenta.music.pretty_music21 to convert the music21 score object
into a NoteSequence proto, and then it was written to disk as a TFRecord.
| {
"content_hash": "fc72989ca1369d7d8b14e31edf56a7f3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 79,
"avg_line_length": 60.333333333333336,
"alnum_prop": 0.7845303867403315,
"repo_name": "hanzorama/magenta",
"id": "4d2dd14d6bf80683ebec83f9940ffb7b21e17c59",
"size": "543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "magenta/music/testdata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Protocol Buffer",
"bytes": "9918"
},
{
"name": "Python",
"bytes": "628506"
},
{
"name": "Shell",
"bytes": "6299"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>WireFrame UI</title>
<link rel="stylesheet" type="text/css" href="css/style1.css">
<meta charset="utf-8">
</head>
<header>
<ul>
<li><a href="#home">Shopping list</a></li>
<ul style="float:right;list-style-type:none;">
<li><a class="active" href="#about">Our services</a></li>
<li><a href="./LoginPage.html">Login</a></li>
<li><a href="#Contact">Contact Us</a></li>
</ul>
</ul>
</header> | {
"content_hash": "65b97e0ee7a0bfffb98512dfbe2c1c76",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 62,
"avg_line_length": 25.166666666666668,
"alnum_prop": 0.6004415011037527,
"repo_name": "PeterclaverKimuli/andellachallenges1",
"id": "ec63c42ab50169d5fc08c81b71780afe900e64cd",
"size": "453",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/templates/homepage.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7716"
},
{
"name": "HTML",
"bytes": "7845"
},
{
"name": "Python",
"bytes": "18987"
}
],
"symlink_target": ""
} |
package io.gravitee.am.repository.management.api;
import io.gravitee.am.model.LoginAttempt;
import io.gravitee.am.repository.common.CrudRepository;
import io.gravitee.am.repository.management.api.search.LoginAttemptCriteria;
import io.reactivex.Completable;
import io.reactivex.Maybe;
/**
* @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public interface LoginAttemptRepository extends CrudRepository<LoginAttempt, String> {
Maybe<LoginAttempt> findByCriteria(LoginAttemptCriteria criteria);
Completable delete(LoginAttemptCriteria criteria);
default Completable purgeExpiredData() {
return Completable.complete();
}
}
| {
"content_hash": "203adb692f18a17af93e030879276a26",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 86,
"avg_line_length": 30.695652173913043,
"alnum_prop": 0.7960339943342776,
"repo_name": "gravitee-io/graviteeio-access-management",
"id": "2bc70f3c2b477b3eac0665fc5651b96019e596f2",
"size": "1336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gravitee-am-repository/gravitee-am-repository-api/src/main/java/io/gravitee/am/repository/management/api/LoginAttemptRepository.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4027"
},
{
"name": "CSS",
"bytes": "68813"
},
{
"name": "Dockerfile",
"bytes": "4681"
},
{
"name": "HTML",
"bytes": "419979"
},
{
"name": "Java",
"bytes": "5954609"
},
{
"name": "JavaScript",
"bytes": "4135"
},
{
"name": "Makefile",
"bytes": "18654"
},
{
"name": "Shell",
"bytes": "13103"
},
{
"name": "TypeScript",
"bytes": "839905"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="generator" content="AsciiDoc 8.6.6" />
<title>parse-options API</title>
<style type="text/css">
/* Shared CSS for AsciiDoc xhtml11 and html5 backends */
/* Default font. */
body {
font-family: Georgia,serif;
}
/* Title font. */
h1, h2, h3, h4, h5, h6,
div.title, caption.title,
thead, p.table.header,
#toctitle,
#author, #revnumber, #revdate, #revremark,
#footer {
font-family: Arial,Helvetica,sans-serif;
}
body {
margin: 1em 5% 1em 5%;
}
a {
color: blue;
text-decoration: underline;
}
a:visited {
color: fuchsia;
}
em {
font-style: italic;
color: navy;
}
strong {
font-weight: bold;
color: #083194;
}
h1, h2, h3, h4, h5, h6 {
color: #527bbd;
margin-top: 1.2em;
margin-bottom: 0.5em;
line-height: 1.3;
}
h1, h2, h3 {
border-bottom: 2px solid silver;
}
h2 {
padding-top: 0.5em;
}
h3 {
float: left;
}
h3 + * {
clear: left;
}
h5 {
font-size: 1.0em;
}
div.sectionbody {
margin-left: 0;
}
hr {
border: 1px solid silver;
}
p {
margin-top: 0.5em;
margin-bottom: 0.5em;
}
ul, ol, li > p {
margin-top: 0;
}
ul > li { color: #aaa; }
ul > li > * { color: black; }
pre {
padding: 0;
margin: 0;
}
#author {
color: #527bbd;
font-weight: bold;
font-size: 1.1em;
}
#email {
}
#revnumber, #revdate, #revremark {
}
#footer {
font-size: small;
border-top: 2px solid silver;
padding-top: 0.5em;
margin-top: 4.0em;
}
#footer-text {
float: left;
padding-bottom: 0.5em;
}
#footer-badges {
float: right;
padding-bottom: 0.5em;
}
#preamble {
margin-top: 1.5em;
margin-bottom: 1.5em;
}
div.imageblock, div.exampleblock, div.verseblock,
div.quoteblock, div.literalblock, div.listingblock, div.sidebarblock,
div.admonitionblock {
margin-top: 1.0em;
margin-bottom: 1.5em;
}
div.admonitionblock {
margin-top: 2.0em;
margin-bottom: 2.0em;
margin-right: 10%;
color: #606060;
}
div.content { /* Block element content. */
padding: 0;
}
/* Block element titles. */
div.title, caption.title {
color: #527bbd;
font-weight: bold;
text-align: left;
margin-top: 1.0em;
margin-bottom: 0.5em;
}
div.title + * {
margin-top: 0;
}
td div.title:first-child {
margin-top: 0.0em;
}
div.content div.title:first-child {
margin-top: 0.0em;
}
div.content + div.title {
margin-top: 0.0em;
}
div.sidebarblock > div.content {
background: #ffffee;
border: 1px solid #dddddd;
border-left: 4px solid #f0f0f0;
padding: 0.5em;
}
div.listingblock > div.content {
border: 1px solid #dddddd;
border-left: 5px solid #f0f0f0;
background: #f8f8f8;
padding: 0.5em;
}
div.quoteblock, div.verseblock {
padding-left: 1.0em;
margin-left: 1.0em;
margin-right: 10%;
border-left: 5px solid #f0f0f0;
color: #888;
}
div.quoteblock > div.attribution {
padding-top: 0.5em;
text-align: right;
}
div.verseblock > pre.content {
font-family: inherit;
font-size: inherit;
}
div.verseblock > div.attribution {
padding-top: 0.75em;
text-align: left;
}
/* DEPRECATED: Pre version 8.2.7 verse style literal block. */
div.verseblock + div.attribution {
text-align: left;
}
div.admonitionblock .icon {
vertical-align: top;
font-size: 1.1em;
font-weight: bold;
text-decoration: underline;
color: #527bbd;
padding-right: 0.5em;
}
div.admonitionblock td.content {
padding-left: 0.5em;
border-left: 3px solid #dddddd;
}
div.exampleblock > div.content {
border-left: 3px solid #dddddd;
padding-left: 0.5em;
}
div.imageblock div.content { padding-left: 0; }
span.image img { border-style: none; }
a.image:visited { color: white; }
dl {
margin-top: 0.8em;
margin-bottom: 0.8em;
}
dt {
margin-top: 0.5em;
margin-bottom: 0;
font-style: normal;
color: navy;
}
dd > *:first-child {
margin-top: 0.1em;
}
ul, ol {
list-style-position: outside;
}
ol.arabic {
list-style-type: decimal;
}
ol.loweralpha {
list-style-type: lower-alpha;
}
ol.upperalpha {
list-style-type: upper-alpha;
}
ol.lowerroman {
list-style-type: lower-roman;
}
ol.upperroman {
list-style-type: upper-roman;
}
div.compact ul, div.compact ol,
div.compact p, div.compact p,
div.compact div, div.compact div {
margin-top: 0.1em;
margin-bottom: 0.1em;
}
tfoot {
font-weight: bold;
}
td > div.verse {
white-space: pre;
}
div.hdlist {
margin-top: 0.8em;
margin-bottom: 0.8em;
}
div.hdlist tr {
padding-bottom: 15px;
}
dt.hdlist1.strong, td.hdlist1.strong {
font-weight: bold;
}
td.hdlist1 {
vertical-align: top;
font-style: normal;
padding-right: 0.8em;
color: navy;
}
td.hdlist2 {
vertical-align: top;
}
div.hdlist.compact tr {
margin: 0;
padding-bottom: 0;
}
.comment {
background: yellow;
}
.footnote, .footnoteref {
font-size: 0.8em;
}
span.footnote, span.footnoteref {
vertical-align: super;
}
#footnotes {
margin: 20px 0 20px 0;
padding: 7px 0 0 0;
}
#footnotes div.footnote {
margin: 0 0 5px 0;
}
#footnotes hr {
border: none;
border-top: 1px solid silver;
height: 1px;
text-align: left;
margin-left: 0;
width: 20%;
min-width: 100px;
}
div.colist td {
padding-right: 0.5em;
padding-bottom: 0.3em;
vertical-align: top;
}
div.colist td img {
margin-top: 0.3em;
}
@media print {
#footer-badges { display: none; }
}
#toc {
margin-bottom: 2.5em;
}
#toctitle {
color: #527bbd;
font-size: 1.1em;
font-weight: bold;
margin-top: 1.0em;
margin-bottom: 0.1em;
}
div.toclevel1, div.toclevel2, div.toclevel3, div.toclevel4 {
margin-top: 0;
margin-bottom: 0;
}
div.toclevel2 {
margin-left: 2em;
font-size: 0.9em;
}
div.toclevel3 {
margin-left: 4em;
font-size: 0.9em;
}
div.toclevel4 {
margin-left: 6em;
font-size: 0.9em;
}
span.aqua { color: aqua; }
span.black { color: black; }
span.blue { color: blue; }
span.fuchsia { color: fuchsia; }
span.gray { color: gray; }
span.green { color: green; }
span.lime { color: lime; }
span.maroon { color: maroon; }
span.navy { color: navy; }
span.olive { color: olive; }
span.purple { color: purple; }
span.red { color: red; }
span.silver { color: silver; }
span.teal { color: teal; }
span.white { color: white; }
span.yellow { color: yellow; }
span.aqua-background { background: aqua; }
span.black-background { background: black; }
span.blue-background { background: blue; }
span.fuchsia-background { background: fuchsia; }
span.gray-background { background: gray; }
span.green-background { background: green; }
span.lime-background { background: lime; }
span.maroon-background { background: maroon; }
span.navy-background { background: navy; }
span.olive-background { background: olive; }
span.purple-background { background: purple; }
span.red-background { background: red; }
span.silver-background { background: silver; }
span.teal-background { background: teal; }
span.white-background { background: white; }
span.yellow-background { background: yellow; }
span.big { font-size: 2em; }
span.small { font-size: 0.6em; }
span.underline { text-decoration: underline; }
span.overline { text-decoration: overline; }
span.line-through { text-decoration: line-through; }
/*
* xhtml11 specific
*
* */
tt {
font-family: monospace;
font-size: inherit;
color: navy;
}
div.tableblock {
margin-top: 1.0em;
margin-bottom: 1.5em;
}
div.tableblock > table {
border: 3px solid #527bbd;
}
thead, p.table.header {
font-weight: bold;
color: #527bbd;
}
p.table {
margin-top: 0;
}
/* Because the table frame attribute is overriden by CSS in most browsers. */
div.tableblock > table[frame="void"] {
border-style: none;
}
div.tableblock > table[frame="hsides"] {
border-left-style: none;
border-right-style: none;
}
div.tableblock > table[frame="vsides"] {
border-top-style: none;
border-bottom-style: none;
}
/*
* html5 specific
*
* */
.monospaced {
font-family: monospace;
font-size: inherit;
color: navy;
}
table.tableblock {
margin-top: 1.0em;
margin-bottom: 1.5em;
}
thead, p.tableblock.header {
font-weight: bold;
color: #527bbd;
}
p.tableblock {
margin-top: 0;
}
table.tableblock {
border-width: 3px;
border-spacing: 0px;
border-style: solid;
border-color: #527bbd;
border-collapse: collapse;
}
th.tableblock, td.tableblock {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #527bbd;
}
table.tableblock.frame-topbot {
border-left-style: hidden;
border-right-style: hidden;
}
table.tableblock.frame-sides {
border-top-style: hidden;
border-bottom-style: hidden;
}
table.tableblock.frame-none {
border-style: hidden;
}
th.tableblock.halign-left, td.tableblock.halign-left {
text-align: left;
}
th.tableblock.halign-center, td.tableblock.halign-center {
text-align: center;
}
th.tableblock.halign-right, td.tableblock.halign-right {
text-align: right;
}
th.tableblock.valign-top, td.tableblock.valign-top {
vertical-align: top;
}
th.tableblock.valign-middle, td.tableblock.valign-middle {
vertical-align: middle;
}
th.tableblock.valign-bottom, td.tableblock.valign-bottom {
vertical-align: bottom;
}
/*
* manpage specific
*
* */
body.manpage h1 {
padding-top: 0.5em;
padding-bottom: 0.5em;
border-top: 2px solid silver;
border-bottom: 2px solid silver;
}
body.manpage h2 {
border-style: none;
}
body.manpage div.sectionbody {
margin-left: 3em;
}
@media print {
body.manpage div#toc { display: none; }
}
</style>
<script type="text/javascript">
/*<+'])');
// Function that scans the DOM tree for header elements (the DOM2
// nodeIterator API would be a better technique but not supported by all
// browsers).
var iterate = function (el) {
for (var i = el.firstChild; i != null; i = i.nextSibling) {
if (i.nodeType == 1 /* Node.ELEMENT_NODE */) {
var mo = re.exec(i.tagName);
if (mo && (i.getAttribute("class") || i.getAttribute("className")) != "float") {
result[result.length] = new TocEntry(i, getText(i), mo[1]-1);
}
iterate(i);
}
}
}
iterate(el);
return result;
}
var toc = document.getElementById("toc");
if (!toc) {
return;
}
// Delete existing TOC entries in case we're reloading the TOC.
var tocEntriesToRemove = [];
var i;
for (i = 0; i < toc.childNodes.length; i++) {
var entry = toc.childNodes[i];
if (entry.nodeName == 'div'
&& entry.getAttribute("class")
&& entry.getAttribute("class").match(/^toclevel/))
tocEntriesToRemove.push(entry);
}
for (i = 0; i < tocEntriesToRemove.length; i++) {
toc.removeChild(tocEntriesToRemove[i]);
}
// Rebuild TOC entries.
var entries = tocEntries(document.getElementById("content"), toclevels);
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i];
if (entry.element.id == "")
entry.element.id = "_toc_" + i;
var a = document.createElement("a");
a.href = "#" + entry.element.id;
a.appendChild(document.createTextNode(entry.text));
var div = document.createElement("div");
div.appendChild(a);
div.className = "toclevel" + entry.toclevel;
toc.appendChild(div);
}
if (entries.length == 0)
toc.parentNode.removeChild(toc);
},
/////////////////////////////////////////////////////////////////////
// Footnotes generator
/////////////////////////////////////////////////////////////////////
/* Based on footnote generation code from:
* http://www.brandspankingnew.net/archive/2005/07/format_footnote.html
*/
footnotes: function () {
// Delete existing footnote entries in case we're reloading the footnodes.
var i;
var noteholder = document.getElementById("footnotes");
if (!noteholder) {
return;
}
var entriesToRemove = [];
for (i = 0; i < noteholder.childNodes.length; i++) {
var entry = noteholder.childNodes[i];
if (entry.nodeName == 'div' && entry.getAttribute("class") == "footnote")
entriesToRemove.push(entry);
}
for (i = 0; i < entriesToRemove.length; i++) {
noteholder.removeChild(entriesToRemove[i]);
}
// Rebuild footnote entries.
var cont = document.getElementById("content");
var spans = cont.getElementsByTagName("span");
var refs = {};
var n = 0;
for (i=0; i<spans.length; i++) {
if (spans[i].className == "footnote") {
n++;
var note = spans[i].getAttribute("data-note");
if (!note) {
// Use [\s\S] in place of . so multi-line matches work.
// Because JavaScript has no s (dotall) regex flag.
note = spans[i].innerHTML.match(/\s*\[([\s\S]*)]\s*/)[1];
spans[i].innerHTML =
"[<a id='_footnoteref_" + n + "' href='#_footnote_" + n +
"' title='View footnote' class='footnote'>" + n + "</a>]";
spans[i].setAttribute("data-note", note);
}
noteholder.innerHTML +=
"<div class='footnote' id='_footnote_" + n + "'>" +
"<a href='#_footnoteref_" + n + "' title='Return to text'>" +
n + "</a>. " + note + "</div>";
var id =spans[i].getAttribute("id");
if (id != null) refs["#"+id] = n;
}
}
if (n == 0)
noteholder.parentNode.removeChild(noteholder);
else {
// Process footnoterefs.
for (i=0; i<spans.length; i++) {
if (spans[i].className == "footnoteref") {
var href = spans[i].getElementsByTagName("a")[0].getAttribute("href");
href = href.match(/#.*/)[0]; // Because IE return full URL.
n = refs[href];
spans[i].innerHTML =
"[<a href='#_footnote_" + n +
"' title='View footnote' class='footnote'>" + n + "</a>]";
}
}
}
},
install: function(toclevels) {
var timerId;
function reinstall() {
asciidoc.footnotes();
if (toclevels) {
asciidoc.toc(toclevels);
}
}
function reinstallAndRemoveTimer() {
clearInterval(timerId);
reinstall();
}
timerId = setInterval(reinstall, 500);
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", reinstallAndRemoveTimer, false);
else
window.onload = reinstallAndRemoveTimer;
}
}
asciidoc.install();
/*]]>*/
</script>
</head>
<body class="article">
<div id="header">
<h1>parse-options API</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph"><p>The parse-options API is used to parse and massage options in Git
and to provide a usage help with consistent look.</p></div>
</div>
</div>
<div class="sect1">
<h2 id="_basics">Basics</h2>
<div class="sectionbody">
<div class="paragraph"><p>The argument vector <tt>argv[]</tt> may usually contain mandatory or optional
<em>non-option arguments</em>, e.g. a filename or a branch, and <em>options</em>.
Options are optional arguments that start with a dash and
that allow to change the behavior of a command.</p></div>
<div class="ulist"><ul>
<li>
<p>
There are basically three types of options:
<em>boolean</em> options,
options with (mandatory) <em>arguments</em> and
options with <em>optional arguments</em>
(i.e. a boolean option that can be adjusted).
</p>
</li>
<li>
<p>
There are basically two forms of options:
<em>Short options</em> consist of one dash (<tt>-</tt>) and one alphanumeric
character.
<em>Long options</em> begin with two dashes (<tt>--</tt>) and some
alphanumeric characters.
</p>
</li>
<li>
<p>
Options are case-sensitive.
Please define <em>lower-case long options</em> only.
</p>
</li>
</ul></div>
<div class="paragraph"><p>The parse-options API allows:</p></div>
<div class="ulist"><ul>
<li>
<p>
<em>stuck</em> and <em>separate form</em> of options with arguments.
<tt>-oArg</tt> is stuck, <tt>-o Arg</tt> is separate form.
<tt>--option=Arg</tt> is stuck, <tt>--option Arg</tt> is separate form.
</p>
</li>
<li>
<p>
Long options may be <em>abbreviated</em>, as long as the abbreviation
is unambiguous.
</p>
</li>
<li>
<p>
Short options may be bundled, e.g. <tt>-a -b</tt> can be specified as <tt>-ab</tt>.
</p>
</li>
<li>
<p>
Boolean long options can be <em>negated</em> (or <em>unset</em>) by prepending
<tt>no-</tt>, e.g. <tt>--no-abbrev</tt> instead of <tt>--abbrev</tt>. Conversely,
options that begin with <tt>no-</tt> can be <em>negated</em> by removing it.
Other long options can be unset (e.g., set string to NULL, set
integer to 0) by prepending <tt>no-</tt>.
</p>
</li>
<li>
<p>
Options and non-option arguments can clearly be separated using the <tt>--</tt>
option, e.g. <tt>-a -b --option -- --this-is-a-file</tt> indicates that
<tt>--this-is-a-file</tt> must not be processed as an option.
</p>
</li>
</ul></div>
</div>
</div>
<div class="sect1">
<h2 id="_steps_to_parse_options">Steps to parse options</h2>
<div class="sectionbody">
<div class="olist arabic"><ol class="arabic">
<li>
<p>
<tt>#include "parse-options.h"</tt>
</p>
</li>
<li>
<p>
define a NULL-terminated
<tt>static const char * const builtin_foo_usage[]</tt> array
containing alternative usage strings
</p>
</li>
<li>
<p>
define <tt>builtin_foo_options</tt> array as described below
in section <em>Data Structure</em>.
</p>
</li>
<li>
<p>
in <tt>cmd_foo(int argc, const char **argv, const char *prefix)</tt>
call
</p>
<div class="literalblock">
<div class="content">
<pre><tt>argc = parse_options(argc, argv, prefix, builtin_foo_options, builtin_foo_usage, flags);</tt></pre>
</div></div>
<div class="paragraph"><p><tt>parse_options()</tt> will filter out the processed options of <tt>argv[]</tt> and leave the
non-option arguments in <tt>argv[]</tt>.
<tt>argc</tt> is updated appropriately because of the assignment.</p></div>
<div class="paragraph"><p>You can also pass NULL instead of a usage array as the fifth parameter of
parse_options(), to avoid displaying a help screen with usage info and
option list. This should only be done if necessary, e.g. to implement
a limited parser for only a subset of the options that needs to be run
before the full parser, which in turn shows the full help message.</p></div>
<div class="paragraph"><p>Flags are the bitwise-or of:</p></div>
<div class="dlist"><dl>
<dt class="hdlist1">
<tt>PARSE_OPT_KEEP_DASHDASH</tt>
</dt>
<dd>
<p>
Keep the <tt>--</tt> that usually separates options from
non-option arguments.
</p>
</dd>
<dt class="hdlist1">
<tt>PARSE_OPT_STOP_AT_NON_OPTION</tt>
</dt>
<dd>
<p>
Usually the whole argument vector is massaged and reordered.
Using this flag, processing is stopped at the first non-option
argument.
</p>
</dd>
<dt class="hdlist1">
<tt>PARSE_OPT_KEEP_ARGV0</tt>
</dt>
<dd>
<p>
Keep the first argument, which contains the program name. It’s
removed from argv[] by default.
</p>
</dd>
<dt class="hdlist1">
<tt>PARSE_OPT_KEEP_UNKNOWN</tt>
</dt>
<dd>
<p>
Keep unknown arguments instead of erroring out. This doesn’t
work for all combinations of arguments as users might expect
it to do. E.g. if the first argument in <tt>--unknown --known</tt>
takes a value (which we can’t know), the second one is
mistakenly interpreted as a known option. Similarly, if
<tt>PARSE_OPT_STOP_AT_NON_OPTION</tt> is set, the second argument in
<tt>--unknown value</tt> will be mistakenly interpreted as a
non-option, not as a value belonging to the unknown option,
the parser early. That’s why parse_options() errors out if
both options are set.
</p>
</dd>
<dt class="hdlist1">
<tt>PARSE_OPT_NO_INTERNAL_HELP</tt>
</dt>
<dd>
<p>
By default, parse_options() handles <tt>-h</tt>, <tt>--help</tt> and
<tt>--help-all</tt> internally, by showing a help screen. This option
turns it off and allows one to add custom handlers for these
options, or to just leave them unknown.
</p>
</dd>
</dl></div>
</li>
</ol></div>
</div>
</div>
<div class="sect1">
<h2 id="_data_structure">Data Structure</h2>
<div class="sectionbody">
<div class="paragraph"><p>The main data structure is an array of the <tt>option</tt> struct,
say <tt>static struct option builtin_add_options[]</tt>.
There are some macros to easily define options:</p></div>
<div class="dlist"><dl>
<dt class="hdlist1">
<tt>OPT__ABBREV(&int_var)</tt>
</dt>
<dd>
<p>
Add <tt>--abbrev[=<n>]</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT__COLOR(&int_var, description)</tt>
</dt>
<dd>
<p>
Add <tt>--color[=<when>]</tt> and <tt>--no-color</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT__DRY_RUN(&int_var, description)</tt>
</dt>
<dd>
<p>
Add <tt>-n, --dry-run</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT__FORCE(&int_var, description)</tt>
</dt>
<dd>
<p>
Add <tt>-f, --force</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT__QUIET(&int_var, description)</tt>
</dt>
<dd>
<p>
Add <tt>-q, --quiet</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT__VERBOSE(&int_var, description)</tt>
</dt>
<dd>
<p>
Add <tt>-v, --verbose</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_GROUP(description)</tt>
</dt>
<dd>
<p>
Start an option group. <tt>description</tt> is a short string that
describes the group or an empty string.
Start the description with an upper-case letter.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_BOOL(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce a boolean option. <tt>int_var</tt> is set to one with
<tt>--option</tt> and set to zero with <tt>--no-option</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_COUNTUP(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce a count-up option.
<tt>int_var</tt> is incremented on each use of <tt>--option</tt>, and
reset to zero with <tt>--no-option</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_BIT(short, long, &int_var, description, mask)</tt>
</dt>
<dd>
<p>
Introduce a boolean option.
If used, <tt>int_var</tt> is bitwise-ored with <tt>mask</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_NEGBIT(short, long, &int_var, description, mask)</tt>
</dt>
<dd>
<p>
Introduce a boolean option.
If used, <tt>int_var</tt> is bitwise-anded with the inverted <tt>mask</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_SET_INT(short, long, &int_var, description, integer)</tt>
</dt>
<dd>
<p>
Introduce an integer option.
<tt>int_var</tt> is set to <tt>integer</tt> with <tt>--option</tt>, and
reset to zero with <tt>--no-option</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_STRING(short, long, &str_var, arg_str, description)</tt>
</dt>
<dd>
<p>
Introduce an option with string argument.
The string argument is put into <tt>str_var</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_INTEGER(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce an option with integer argument.
The integer is put into <tt>int_var</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_DATE(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce an option with date argument, see <tt>approxidate()</tt>.
The timestamp is put into <tt>int_var</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_EXPIRY_DATE(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce an option with expiry date argument, see <tt>parse_expiry_date()</tt>.
The timestamp is put into <tt>int_var</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_CALLBACK(short, long, &var, arg_str, description, func_ptr)</tt>
</dt>
<dd>
<p>
Introduce an option with argument.
The argument will be fed into the function given by <tt>func_ptr</tt>
and the result will be put into <tt>var</tt>.
See <em>Option Callbacks</em> below for a more elaborate description.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_FILENAME(short, long, &var, description)</tt>
</dt>
<dd>
<p>
Introduce an option with a filename argument.
The filename will be prefixed by passing the filename along with
the prefix argument of <tt>parse_options()</tt> to <tt>prefix_filename()</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_ARGUMENT(long, description)</tt>
</dt>
<dd>
<p>
Introduce a long-option argument that will be kept in <tt>argv[]</tt>.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_NUMBER_CALLBACK(&var, description, func_ptr)</tt>
</dt>
<dd>
<p>
Recognize numerical options like -123 and feed the integer as
if it was an argument to the function given by <tt>func_ptr</tt>.
The result will be put into <tt>var</tt>. There can be only one such
option definition. It cannot be negated and it takes no
arguments. Short options that happen to be digits take
precedence over it.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_COLOR_FLAG(short, long, &int_var, description)</tt>
</dt>
<dd>
<p>
Introduce an option that takes an optional argument that can
have one of three values: "always", "never", or "auto". If the
argument is not given, it defaults to "always". The <tt>--no-</tt> form
works like <tt>--long=never</tt>; it cannot take an argument. If
"always", set <tt>int_var</tt> to 1; if "never", set <tt>int_var</tt> to 0; if
"auto", set <tt>int_var</tt> to 1 if stdout is a tty or a pager,
0 otherwise.
</p>
</dd>
<dt class="hdlist1">
<tt>OPT_NOOP_NOARG(short, long)</tt>
</dt>
<dd>
<p>
Introduce an option that has no effect and takes no arguments.
Use it to hide deprecated options that are still to be recognized
and ignored silently.
</p>
</dd>
</dl></div>
<div class="paragraph"><p>The last element of the array must be <tt>OPT_END()</tt>.</p></div>
<div class="paragraph"><p>If not stated otherwise, interpret the arguments as follows:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>short</tt> is a character for the short option
(e.g. <tt>'e'</tt> for <tt>-e</tt>, use <tt>0</tt> to omit),
</p>
</li>
<li>
<p>
<tt>long</tt> is a string for the long option
(e.g. <tt>"example"</tt> for <tt>--example</tt>, use <tt>NULL</tt> to omit),
</p>
</li>
<li>
<p>
<tt>int_var</tt> is an integer variable,
</p>
</li>
<li>
<p>
<tt>str_var</tt> is a string variable (<tt>char *</tt>),
</p>
</li>
<li>
<p>
<tt>arg_str</tt> is the string that is shown as argument
(e.g. <tt>"branch"</tt> will result in <tt><branch></tt>).
If set to <tt>NULL</tt>, three dots (<tt>...</tt>) will be displayed.
</p>
</li>
<li>
<p>
<tt>description</tt> is a short string to describe the effect of the option.
It shall begin with a lower-case letter and a full stop (<tt>.</tt>) shall be
omitted at the end.
</p>
</li>
</ul></div>
</div>
</div>
<div class="sect1">
<h2 id="_option_callbacks">Option Callbacks</h2>
<div class="sectionbody">
<div class="paragraph"><p>The function must be defined in this form:</p></div>
<div class="literalblock">
<div class="content">
<pre><tt>int func(const struct option *opt, const char *arg, int unset)</tt></pre>
</div></div>
<div class="paragraph"><p>The callback mechanism is as follows:</p></div>
<div class="ulist"><ul>
<li>
<p>
Inside <tt>func</tt>, the only interesting member of the structure
given by <tt>opt</tt> is the void pointer <tt>opt->value</tt>.
<tt>*opt->value</tt> will be the value that is saved into <tt>var</tt>, if you
use <tt>OPT_CALLBACK()</tt>.
For example, do <tt>*(unsigned long *)opt->value = 42;</tt> to get 42
into an <tt>unsigned long</tt> variable.
</p>
</li>
<li>
<p>
Return value <tt>0</tt> indicates success and non-zero return
value will invoke <tt>usage_with_options()</tt> and, thus, die.
</p>
</li>
<li>
<p>
If the user negates the option, <tt>arg</tt> is <tt>NULL</tt> and <tt>unset</tt> is 1.
</p>
</li>
</ul></div>
</div>
</div>
<div class="sect1">
<h2 id="_sophisticated_option_parsing">Sophisticated option parsing</h2>
<div class="sectionbody">
<div class="paragraph"><p>If you need, for example, option callbacks with optional arguments
or without arguments at all, or if you need other special cases,
that are not handled by the macros above, you need to specify the
members of the <tt>option</tt> structure manually.</p></div>
<div class="paragraph"><p>This is not covered in this document, but well documented
in <tt>parse-options.h</tt> itself.</p></div>
</div>
</div>
<div class="sect1">
<h2 id="_examples">Examples</h2>
<div class="sectionbody">
<div class="paragraph"><p>See <tt>test-parse-options.c</tt> and
<tt>builtin/add.c</tt>,
<tt>builtin/clone.c</tt>,
<tt>builtin/commit.c</tt>,
<tt>builtin/fetch.c</tt>,
<tt>builtin/fsck.c</tt>,
<tt>builtin/rm.c</tt>
for real-world examples.</p></div>
</div>
</div>
</div>
<div id="footnotes"><hr /></div>
<div id="footer">
<div id="footer-text">
Last updated 2014-04-08 12:47:26 PDT
</div>
</div>
</body>
</html>
| {
"content_hash": "4219cfc13ee9e553ea0cad5e41ca3421",
"timestamp": "",
"source": "github",
"line_count": 1244,
"max_line_length": 121,
"avg_line_length": 24.173633440514468,
"alnum_prop": 0.6375033253524873,
"repo_name": "padamshrestha/portable_nodejs_git",
"id": "6fd19cd1c882b8066cadb117b06901c0d0f7649b",
"size": "30072",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Git/doc/git/html/technical/api-parse-options.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "18617"
},
{
"name": "C",
"bytes": "275803"
},
{
"name": "C++",
"bytes": "164357"
},
{
"name": "CSS",
"bytes": "15143"
},
{
"name": "Emacs Lisp",
"bytes": "30222"
},
{
"name": "HTML",
"bytes": "6835201"
},
{
"name": "JavaScript",
"bytes": "77298"
},
{
"name": "M4",
"bytes": "193907"
},
{
"name": "Makefile",
"bytes": "2531"
},
{
"name": "NewLisp",
"bytes": "37316"
},
{
"name": "Perl",
"bytes": "5146825"
},
{
"name": "Perl6",
"bytes": "473997"
},
{
"name": "PowerShell",
"bytes": "991"
},
{
"name": "Prolog",
"bytes": "553295"
},
{
"name": "Ruby",
"bytes": "28952"
},
{
"name": "Shell",
"bytes": "273882"
},
{
"name": "Smalltalk",
"bytes": "25677"
},
{
"name": "SystemVerilog",
"bytes": "27798"
},
{
"name": "Tcl",
"bytes": "2257519"
},
{
"name": "VimL",
"bytes": "680966"
},
{
"name": "Visual Basic",
"bytes": "691"
},
{
"name": "XSLT",
"bytes": "50637"
}
],
"symlink_target": ""
} |
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**href** | **str** | | [optional]
**items** | [**[bt_invitation_info.BTInvitationInfo]**](BTInvitationInfo.md) | | [optional]
**previous** | **str** | | [optional]
**next** | **str** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
| {
"content_hash": "ec891f0148f5467f84023fc714ea1ad6",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 161,
"avg_line_length": 46.6,
"alnum_prop": 0.5364806866952789,
"repo_name": "onshape-public/onshape-clients",
"id": "44f388b8a48482ee81fb6a24210c9e20a7042630",
"size": "550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/docs/BTListResponseBTInvitationInfo.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4873"
},
{
"name": "Go",
"bytes": "59674"
},
{
"name": "HTML",
"bytes": "3851790"
},
{
"name": "JavaScript",
"bytes": "2217"
},
{
"name": "Makefile",
"bytes": "559"
},
{
"name": "Python",
"bytes": "7560009"
},
{
"name": "Shell",
"bytes": "3475"
},
{
"name": "TypeScript",
"bytes": "1412661"
}
],
"symlink_target": ""
} |
<?php
namespace Flugg\Responder\Contracts;
use Flugg\Responder\TransformBuilder;
/**
* A contract for transforming data, without the serializing.
*
* @package flugger/laravel-responder
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
interface SimpleTransformer
{
/**
* Transform the data without serializing, using the given transformer.
*
* @param mixed $data
* @param \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
* @param string|null $resourceKey
* @return \Flugg\Responder\TransformBuilder
*/
public function make($data = null, $transformer = null, string $resourceKey = null): TransformBuilder;
} | {
"content_hash": "6f01ecbd9f620148c2d7625ab90c8fa5",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 106,
"avg_line_length": 33.04,
"alnum_prop": 0.6222760290556901,
"repo_name": "flugger/laravel-responder",
"id": "43bb31b86051164f1ba90cfc7f0fa8ff445ddbc3",
"size": "828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Contracts/SimpleTransformer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "283912"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Sat Jan 30 22:26:12 CST 2016 -->
<title>II2cDeviceClient.ReadWindow</title>
<meta name="date" content="2016-01-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="II2cDeviceClient.ReadWindow";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation
links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces"><span class="typeNameLink">Prev Class</span></a>
</li>
<li>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.TimestampedData.html"
title="class in org.ftccommunity.i2clibrary.interfaces"><span class="typeNameLink">Next Class</span></a>
</li>
</ul>
<ul class="navList">
<li>
<a href="../../../../index.html?org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
target="_top">Frames</a></li>
<li><a href="II2cDeviceClient.ReadWindow.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.ftccommunity.i2clibrary.interfaces</div>
<h2 title="Class II2cDeviceClient.ReadWindow" class="title">Class
II2cDeviceClient.ReadWindow</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing interface:</dt>
<dd>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.html"
title="interface in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient</a>
</dd>
</dl>
<hr>
<br>
<pre>public static class <span class="typeNameLabel">II2cDeviceClient.ReadWindow</span>
extends java.lang.Object</pre>
<div class="block">RegWindow is a utility class for managing the window of I2C
register bytes that are read from
our I2C device on every hardware cycle
</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0"
summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#cregReadMax">cregReadMax</a></span></code>
<div class="block">enableI2cReadMode and enableI2cWriteMode both
impose a maximum length on the size of data
that can be read or written at one time.
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#cregWriteMax">cregWriteMax</a></span></code>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0"
summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span>
</caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#ReadWindow-int-int-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.READ_MODE-">ReadWindow</a></span>(int iregFirst,
int creg,
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.READ_MODE</a> readMode)</code>
<div class="block">Create a new register window with the
indicated starting register and register count
</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0"
summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0"
class="activeTableTab"><span>All Methods</span><span
class="tabEnd"> </span></span><span id="t2"
class="tableTab"><span><a
href="javascript:show(2);">Instance Methods</a></span><span
class="tabEnd"> </span></span><span id="t4"
class="tableTab"><span><a
href="javascript:show(8);">Concrete Methods</a></span><span
class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#contains-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">contains</a></span>(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</code>
<div class="block">Answers as to whether the receiver wholly
contains the indicated window.
</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#contains-int-int-">contains</a></span>(int ireg,
int creg)</code>
<div class="block">Answers as to whether the receiver wholly
contains the indicated set of registers.
</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#containsWithSameMode-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">containsWithSameMode</a></span>(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</code>
<div class="block">Answers as to whether the receiver wholly
contains the indicated window and also has the
same modality.
</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a></code>
</td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#freshCopy--">freshCopy</a></span>()</code>
<div class="block">Returns a copy of this window but with the <a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#readIssued"><code>readIssued</code></a>
flag clear
</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#getCreg--">getCreg</a></span>()</code>
<div class="block">Returns the number of registers in the
window
</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#getIregFirst--">getIregFirst</a></span>()</code>
<div class="block">Returns the first register in the window
</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#getIregMax--">getIregMax</a></span>()</code>
<div class="block">Returns the first register NOT in the
window
</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#getReadIssued--">getReadIssued</a></span>()</code>
<div class="block">Returns whether a read has ever been issued
for this window or not
</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.READ_MODE</a></code>
</td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#getReadMode--">getReadMode</a></span>()</code>
<div class="block">Returns the mode of the window</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#isOkToRead--">isOkToRead</a></span>()</code>
<div class="block">Answers as to whether we're allowed to read
using this window.
</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#maySwitchToReadMode--">maySwitchToReadMode</a></span>()</code>
<div class="block">Answers as to whether this window in its
present state ought to cause a transition to
read-mode when there's nothing else for the device to be
doing.
</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#sameAsIncludingMode-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">sameAsIncludingMode</a></span>(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</code>
<div class="block">Do the receiver and the indicated register
window cover exactly the same set of registers
and have the same modality?
</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#setReadIssued--">setReadIssued</a></span>()</code>
<div class="block">Sets that a read has in fact been issued for
this window
</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a
name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify,
notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="cregReadMax">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>cregReadMax</h4>
<pre>public static final int cregReadMax</pre>
<div class="block">enableI2cReadMode and enableI2cWriteMode both
impose a maximum length on the size of data
that can be read or written at one time. cregReadMax and
cregWriteMax indicate those
maximum sizes.
</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#cregWriteMax"><code>cregWriteMax</code></a>,
<a href="../../../../constant-values.html#org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow.cregReadMax">Constant
Field Values</a></dd>
</dl>
</li>
</ul>
<a name="cregWriteMax">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>cregWriteMax</h4>
<pre>public static final int cregWriteMax</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#cregReadMax"><code>cregReadMax</code></a>,
<a href="../../../../constant-values.html#org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow.cregWriteMax">Constant
Field Values</a></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ReadWindow-int-int-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.READ_MODE-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ReadWindow</h4>
<pre>public ReadWindow(int iregFirst,
int creg,
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.READ_MODE</a> readMode)</pre>
<div class="block">Create a new register window with the indicated
starting register and register count
</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>iregFirst</code> - the index of the first register to
read
</dd>
<dd><code>creg</code> - the number of registers to read</dd>
<dd><code>readMode</code> - whether to repeat-read or read only
once
</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getIregFirst--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getIregFirst</h4>
<pre>public int getIregFirst()</pre>
<div class="block">Returns the first register in the window</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the first register in the window</dd>
</dl>
</li>
</ul>
<a name="getIregMax--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getIregMax</h4>
<pre>public int getIregMax()</pre>
<div class="block">Returns the first register NOT in the window
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the first register NOT in the window</dd>
</dl>
</li>
</ul>
<a name="getCreg--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCreg</h4>
<pre>public int getCreg()</pre>
<div class="block">Returns the number of registers in the window
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the number of registers in the window</dd>
</dl>
</li>
</ul>
<a name="getReadMode--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getReadMode</h4>
<pre>public <a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.READ_MODE</a> getReadMode()</pre>
<div class="block">Returns the mode of the window</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the mode of the window</dd>
</dl>
</li>
</ul>
<a name="getReadIssued--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getReadIssued</h4>
<pre>public boolean getReadIssued()</pre>
<div class="block">Returns whether a read has ever been issued for
this window or not
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether a read has ever been issued for this window or not
</dd>
</dl>
</li>
</ul>
<a name="setReadIssued--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setReadIssued</h4>
<pre>public void setReadIssued()</pre>
<div class="block">Sets that a read has in fact been issued for this
window
</div>
</li>
</ul>
<a name="isOkToRead--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isOkToRead</h4>
<pre>public boolean isOkToRead()</pre>
<div class="block">Answers as to whether we're allowed to read using
this window. This will return false for
ONLY_ONCE windows after <a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#setReadIssued--"><code>setReadIssued()</code></a>
has been called on them.
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether it is permitted to perform a read for this window.
</dd>
</dl>
</li>
</ul>
<a name="maySwitchToReadMode--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>maySwitchToReadMode</h4>
<pre>public boolean maySwitchToReadMode()</pre>
<div class="block">Answers as to whether this window in its present
state ought to cause a transition to
read-mode when there's nothing else for the device to be doing.
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether this device should cause a read mode transition</dd>
</dl>
</li>
</ul>
<a name="freshCopy--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>freshCopy</h4>
<pre>public <a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> freshCopy()</pre>
<div class="block">Returns a copy of this window but with the <a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#readIssued"><code>readIssued</code></a>
flag clear
</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>a fresh readable copy of the window</dd>
</dl>
</li>
</ul>
<a name="sameAsIncludingMode-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sameAsIncludingMode</h4>
<pre>public boolean sameAsIncludingMode(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</pre>
<div class="block">Do the receiver and the indicated register window
cover exactly the same set of registers
and have the same modality?
</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>him</code> - the other window to compare to</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the result of the comparison</dd>
</dl>
</li>
</ul>
<a name="contains-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>contains</h4>
<pre>public boolean contains(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</pre>
<div class="block">Answers as to whether the receiver wholly
contains the indicated window.
</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>him</code> - the window we wish to see whether we
contain
</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether or not we contain the window</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html#contains-int-int-"><code>contains(int,
int)</code></a></dd>
</dl>
</li>
</ul>
<a name="containsWithSameMode-org.ftccommunity.i2clibrary.interfaces.II2cDeviceClient.ReadWindow-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>containsWithSameMode</h4>
<pre>public boolean containsWithSameMode(<a
href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
title="class in org.ftccommunity.i2clibrary.interfaces">II2cDeviceClient.ReadWindow</a> him)</pre>
<div class="block">Answers as to whether the receiver wholly
contains the indicated window and also has the
same modality.
</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>him</code> - the window we wish to see whether we
contain
</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether or not we contain the window</dd>
</dl>
</li>
</ul>
<a name="contains-int-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>contains</h4>
<pre>public boolean contains(int ireg,
int creg)</pre>
<div class="block">Answers as to whether the receiver wholly
contains the indicated set of registers.
</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ireg</code> - the first register of interest</dd>
<dd><code>creg</code> - the number of registers of interest</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>whether or not the receiver contains this set of registers
</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><code>#contains(ReadWindow)</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation
links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.READ_MODE.html"
title="enum in org.ftccommunity.i2clibrary.interfaces"><span class="typeNameLink">Prev Class</span></a>
</li>
<li>
<a href="../../../../org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.TimestampedData.html"
title="class in org.ftccommunity.i2clibrary.interfaces"><span class="typeNameLink">Next Class</span></a>
</li>
</ul>
<ul class="navList">
<li>
<a href="../../../../index.html?org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html"
target="_top">Frames</a></li>
<li><a href="II2cDeviceClient.ReadWindow.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "989bbb7a2a47d07ef405fbe542225174",
"timestamp": "",
"source": "github",
"line_count": 802,
"max_line_length": 258,
"avg_line_length": 56.47755610972568,
"alnum_prop": 0.4096037090186555,
"repo_name": "MHS-FIRSTrobotics/TeamClutch-FTC2016",
"id": "12e0a9dcd2820e56153e6ae2c39861c4eb1e421a",
"size": "45295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/FtcXtensible/org/ftccommunity/i2clibrary/interfaces/II2cDeviceClient.ReadWindow.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2055373"
}
],
"symlink_target": ""
} |
FOUNDATION_EXPORT double Pods_LLVCS_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LLVCS_ExampleVersionString[];
| {
"content_hash": "fe0b8367db3a49494617010a97abc5d4",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 72,
"avg_line_length": 44,
"alnum_prop": 0.8560606060606061,
"repo_name": "Niday/LLVCS",
"id": "e9baf333a56068ddb77df6f7ac8018857fc34e2e",
"size": "328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/Pods/Target Support Files/Pods-LLVCS_Example/Pods-LLVCS_Example-umbrella.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "933"
},
{
"name": "Objective-C",
"bytes": "475269"
},
{
"name": "Ruby",
"bytes": "3472"
},
{
"name": "Shell",
"bytes": "25840"
}
],
"symlink_target": ""
} |
package org.apache.sling.event.impl.jobs.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.event.impl.support.ResourceHelper;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
/**
* The queue manager manages queue configurations.
*/
@Component
@Service(value=QueueConfigurationManager.class)
public class QueueConfigurationManager {
/** Configurations - ordered by service ranking. */
private volatile InternalQueueConfiguration[] orderedConfigs = new InternalQueueConfiguration[0];
/** Service tracker for the configurations. */
private ServiceTracker configTracker;
/** Tracker count to detect changes. */
private volatile int lastTrackerCount = -1;
@Reference
private MainQueueConfiguration mainQueueConfiguration;
/**
* Activate this component.
* Create the service tracker and start it.
*/
@Activate
protected void activate(final BundleContext bundleContext)
throws LoginException, PersistenceException {
this.configTracker = new ServiceTracker(bundleContext,
InternalQueueConfiguration.class.getName(), null);
this.configTracker.open();
}
/**
* Deactivate this component.
* Stop the service tracker.
*/
@Deactivate
protected void deactivate() {
if ( this.configTracker != null ) {
this.configTracker.close();
this.configTracker = null;
}
}
/**
* Return all configurations.
*/
public InternalQueueConfiguration[] getConfigurations() {
final int count = this.configTracker.getTrackingCount();
InternalQueueConfiguration[] configurations = this.orderedConfigs;
if ( this.lastTrackerCount < count ) {
synchronized ( this ) {
configurations = this.orderedConfigs;
if ( this.lastTrackerCount < count ) {
final Object[] trackedConfigs = this.configTracker.getServices();
if ( trackedConfigs == null || trackedConfigs.length == 0 ) {
configurations = new InternalQueueConfiguration[0];
} else {
final List<InternalQueueConfiguration> configs = new ArrayList<InternalQueueConfiguration>();
for(final Object entry : trackedConfigs) {
final InternalQueueConfiguration config = (InternalQueueConfiguration)entry;
configs.add(config);
}
Collections.sort(configs);
configurations = configs.toArray(new InternalQueueConfiguration[configs.size()]);
}
this.orderedConfigs = configurations;
this.lastTrackerCount = count;
}
}
}
return configurations;
}
public InternalQueueConfiguration getMainQueueConfiguration() {
return this.mainQueueConfiguration.getMainConfiguration();
}
public static final class QueueInfo {
public InternalQueueConfiguration queueConfiguration;
public String queueName;
public String targetId;
}
/**
* Find the queue configuration for the job.
* This method only returns a configuration if one matches.
*/
public QueueInfo getQueueInfo(final String topic) {
final InternalQueueConfiguration[] configurations = this.getConfigurations();
for(final InternalQueueConfiguration config : configurations) {
if ( config.isValid() ) {
final String qn = config.match(topic);
if ( qn != null ) {
final QueueInfo result = new QueueInfo();
result.queueConfiguration = config;
result.queueName = ResourceHelper.filterName(qn);
return result;
}
}
}
final QueueInfo result = new QueueInfo();
result.queueConfiguration = this.mainQueueConfiguration.getMainConfiguration();
result.queueName = result.queueConfiguration.getName();
return result;
}
public int getChangeCount() {
return this.configTracker.getTrackingCount();
}
}
| {
"content_hash": "77bee041db0fdb84c3748778f2c5eca6",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 117,
"avg_line_length": 36.099236641221374,
"alnum_prop": 0.6413618101078452,
"repo_name": "MRivas-XumaK/slingBuild",
"id": "4a4851ec7732284ed886619fe158424910c1e3f1",
"size": "5536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/config/QueueConfigurationManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "78948"
},
{
"name": "Groovy",
"bytes": "7964"
},
{
"name": "Java",
"bytes": "15000817"
},
{
"name": "JavaScript",
"bytes": "380961"
},
{
"name": "Python",
"bytes": "298"
},
{
"name": "Scala",
"bytes": "127988"
},
{
"name": "Shell",
"bytes": "5532"
},
{
"name": "XProc",
"bytes": "2290"
},
{
"name": "XSLT",
"bytes": "10005"
}
],
"symlink_target": ""
} |
package demo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.bus.runner.EnableMessageBus;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@EnableMessageBus
@ImportResource("classpath:/config/ticker.xml")
@PropertySource("classpath:/config/ticker.properties")
public class ModuleApplication {
public static void main(String[] args) throws InterruptedException {
new SpringApplicationBuilder().sources(ModuleApplication.class).run(args);
}
}
| {
"content_hash": "c1b26bc65fc75bcf2416cfd4665f499c",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 76,
"avg_line_length": 34.8421052631579,
"alnum_prop": 0.8429003021148036,
"repo_name": "spring-projects/spring-bus",
"id": "03007d978b76dfb08cd1689bde4d5062e0957313",
"size": "662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-xd-samples/source-xml/src/main/java/demo/ModuleApplication.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "76884"
}
],
"symlink_target": ""
} |
var cola;
(function (cola) {
var packingOptions = {
PADDING: 10,
GOLDEN_SECTION: (1 + Math.sqrt(5)) / 2,
FLOAT_EPSILON: 0.0001,
MAX_INERATIONS: 100
};
// assign x, y to nodes while using box packing algorithm for disconnected graphs
function applyPacking(graphs, w, h, node_size, desired_ratio) {
if (desired_ratio === void 0) { desired_ratio = 1; }
var init_x = 0, init_y = 0, svg_width = w, svg_height = h, desired_ratio = typeof desired_ratio !== 'undefined' ? desired_ratio : 1, node_size = typeof node_size !== 'undefined' ? node_size : 0, real_width = 0, real_height = 0, min_width = 0, global_bottom = 0, line = [];
if (graphs.length == 0)
return;
/// that would take care of single nodes problem
// graphs.forEach(function (g) {
// if (g.array.length == 1) {
// g.array[0].x = 0;
// g.array[0].y = 0;
// }
// });
calculate_bb(graphs);
apply(graphs, desired_ratio);
put_nodes_to_right_positions(graphs);
// get bounding boxes for all separate graphs
function calculate_bb(graphs) {
graphs.forEach(function (g) {
calculate_single_bb(g);
});
function calculate_single_bb(graph) {
var min_x = Number.MAX_VALUE, min_y = Number.MAX_VALUE, max_x = 0, max_y = 0;
graph.array.forEach(function (v) {
var w = typeof v.width !== 'undefined' ? v.width : node_size;
var h = typeof v.height !== 'undefined' ? v.height : node_size;
w /= 2;
h /= 2;
max_x = Math.max(v.x + w, max_x);
min_x = Math.min(v.x - w, min_x);
max_y = Math.max(v.y + h, max_y);
min_y = Math.min(v.y - h, min_y);
});
graph.width = max_x - min_x;
graph.height = max_y - min_y;
}
}
//function plot(data, left, right, opt_x, opt_y) {
// // plot the cost function
// var plot_svg = d3.select("body").append("svg")
// .attr("width", function () { return 2 * (right - left); })
// .attr("height", 200);
// var x = d3.time.scale().range([0, 2 * (right - left)]);
// var xAxis = d3.svg.axis().scale(x).orient("bottom");
// plot_svg.append("g").attr("class", "x axis")
// .attr("transform", "translate(0, 199)")
// .call(xAxis);
// var lastX = 0;
// var lastY = 0;
// var value = 0;
// for (var r = left; r < right; r += 1) {
// value = step(data, r);
// // value = 1;
// plot_svg.append("line").attr("x1", 2 * (lastX - left))
// .attr("y1", 200 - 30 * lastY)
// .attr("x2", 2 * r - 2 * left)
// .attr("y2", 200 - 30 * value)
// .style("stroke", "rgb(6,120,155)");
// lastX = r;
// lastY = value;
// }
// plot_svg.append("circle").attr("cx", 2 * opt_x - 2 * left).attr("cy", 200 - 30 * opt_y)
// .attr("r", 5).style('fill', "rgba(0,0,0,0.5)");
//}
// actual assigning of position to nodes
function put_nodes_to_right_positions(graphs) {
graphs.forEach(function (g) {
// calculate current graph center:
var center = { x: 0, y: 0 };
g.array.forEach(function (node) {
center.x += node.x;
center.y += node.y;
});
center.x /= g.array.length;
center.y /= g.array.length;
// calculate current top left corner:
var corner = { x: center.x - g.width / 2, y: center.y - g.height / 2 };
var offset = { x: g.x - corner.x + svg_width / 2 - real_width / 2, y: g.y - corner.y + svg_height / 2 - real_height / 2 };
// put nodes:
g.array.forEach(function (node) {
node.x += offset.x;
node.y += offset.y;
});
});
}
// starts box packing algorithm
// desired ratio is 1 by default
function apply(data, desired_ratio) {
var curr_best_f = Number.POSITIVE_INFINITY;
var curr_best = 0;
data.sort(function (a, b) { return b.height - a.height; });
min_width = data.reduce(function (a, b) {
return a.width < b.width ? a.width : b.width;
});
var left = x1 = min_width;
var right = x2 = get_entire_width(data);
var iterationCounter = 0;
var f_x1 = Number.MAX_VALUE;
var f_x2 = Number.MAX_VALUE;
var flag = -1; // determines which among f_x1 and f_x2 to recompute
var dx = Number.MAX_VALUE;
var df = Number.MAX_VALUE;
while ((dx > min_width) || df > packingOptions.FLOAT_EPSILON) {
if (flag != 1) {
var x1 = right - (right - left) / packingOptions.GOLDEN_SECTION;
var f_x1 = step(data, x1);
}
if (flag != 0) {
var x2 = left + (right - left) / packingOptions.GOLDEN_SECTION;
var f_x2 = step(data, x2);
}
dx = Math.abs(x1 - x2);
df = Math.abs(f_x1 - f_x2);
if (f_x1 < curr_best_f) {
curr_best_f = f_x1;
curr_best = x1;
}
if (f_x2 < curr_best_f) {
curr_best_f = f_x2;
curr_best = x2;
}
if (f_x1 > f_x2) {
left = x1;
x1 = x2;
f_x1 = f_x2;
flag = 1;
}
else {
right = x2;
x2 = x1;
f_x2 = f_x1;
flag = 0;
}
if (iterationCounter++ > 100) {
break;
}
}
// plot(data, min_width, get_entire_width(data), curr_best, curr_best_f);
step(data, curr_best);
}
// one iteration of the optimization method
// (gives a proper, but not necessarily optimal packing)
function step(data, max_width) {
line = [];
real_width = 0;
real_height = 0;
global_bottom = init_y;
for (var i = 0; i < data.length; i++) {
var o = data[i];
put_rect(o, max_width);
}
return Math.abs(get_real_ratio() - desired_ratio);
}
// looking for a position to one box
function put_rect(rect, max_width) {
var parent = undefined;
for (var i = 0; i < line.length; i++) {
if ((line[i].space_left >= rect.height) && (line[i].x + line[i].width + rect.width + packingOptions.PADDING - max_width) <= packingOptions.FLOAT_EPSILON) {
parent = line[i];
break;
}
}
line.push(rect);
if (parent !== undefined) {
rect.x = parent.x + parent.width + packingOptions.PADDING;
rect.y = parent.bottom;
rect.space_left = rect.height;
rect.bottom = rect.y;
parent.space_left -= rect.height + packingOptions.PADDING;
parent.bottom += rect.height + packingOptions.PADDING;
}
else {
rect.y = global_bottom;
global_bottom += rect.height + packingOptions.PADDING;
rect.x = init_x;
rect.bottom = rect.y;
rect.space_left = rect.height;
}
if (rect.y + rect.height - real_height > -packingOptions.FLOAT_EPSILON)
real_height = rect.y + rect.height - init_y;
if (rect.x + rect.width - real_width > -packingOptions.FLOAT_EPSILON)
real_width = rect.x + rect.width - init_x;
}
;
function get_entire_width(data) {
var width = 0;
data.forEach(function (d) { return width += d.width + packingOptions.PADDING; });
return width;
}
function get_real_ratio() {
return (real_width / real_height);
}
}
cola.applyPacking = applyPacking;
/**
* connected components of graph
* returns an array of {}
*/
function separateGraphs(nodes, links) {
var marks = {};
var ways = {};
var graphs = [];
var clusters = 0;
for (var i = 0; i < links.length; i++) {
var link = links[i];
var n1 = link.source;
var n2 = link.target;
if (ways[n1.index])
ways[n1.index].push(n2);
else
ways[n1.index] = [n2];
if (ways[n2.index])
ways[n2.index].push(n1);
else
ways[n2.index] = [n1];
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (marks[node.index])
continue;
explore_node(node, true);
}
function explore_node(n, is_new) {
if (marks[n.index] !== undefined)
return;
if (is_new) {
clusters++;
graphs.push({ array: [] });
}
marks[n.index] = clusters;
graphs[clusters - 1].array.push(n);
var adjacent = ways[n.index];
if (!adjacent)
return;
for (var j = 0; j < adjacent.length; j++) {
explore_node(adjacent[j], false);
}
}
return graphs;
}
cola.separateGraphs = separateGraphs;
})(cola || (cola = {}));
var cola;
(function (cola) {
var vpsc;
(function (vpsc) {
var PositionStats = (function () {
function PositionStats(scale) {
this.scale = scale;
this.AB = 0;
this.AD = 0;
this.A2 = 0;
}
PositionStats.prototype.addVariable = function (v) {
var ai = this.scale / v.scale;
var bi = v.offset / v.scale;
var wi = v.weight;
this.AB += wi * ai * bi;
this.AD += wi * ai * v.desiredPosition;
this.A2 += wi * ai * ai;
};
PositionStats.prototype.getPosn = function () {
return (this.AD - this.AB) / this.A2;
};
return PositionStats;
})();
vpsc.PositionStats = PositionStats;
var Constraint = (function () {
function Constraint(left, right, gap, equality) {
if (equality === void 0) { equality = false; }
this.left = left;
this.right = right;
this.gap = gap;
this.equality = equality;
this.active = false;
this.unsatisfiable = false;
this.left = left;
this.right = right;
this.gap = gap;
this.equality = equality;
}
Constraint.prototype.slack = function () {
return this.unsatisfiable ? Number.MAX_VALUE
: this.right.scale * this.right.position() - this.gap
- this.left.scale * this.left.position();
};
return Constraint;
})();
vpsc.Constraint = Constraint;
var Variable = (function () {
function Variable(desiredPosition, weight, scale) {
if (weight === void 0) { weight = 1; }
if (scale === void 0) { scale = 1; }
this.desiredPosition = desiredPosition;
this.weight = weight;
this.scale = scale;
this.offset = 0;
}
Variable.prototype.dfdv = function () {
return 2.0 * this.weight * (this.position() - this.desiredPosition);
};
Variable.prototype.position = function () {
return (this.block.ps.scale * this.block.posn + this.offset) / this.scale;
};
// visit neighbours by active constraints within the same block
Variable.prototype.visitNeighbours = function (prev, f) {
var ff = function (c, next) { return c.active && prev !== next && f(c, next); };
this.cOut.forEach(function (c) { return ff(c, c.right); });
this.cIn.forEach(function (c) { return ff(c, c.left); });
};
return Variable;
})();
vpsc.Variable = Variable;
var Block = (function () {
function Block(v) {
this.vars = [];
v.offset = 0;
this.ps = new PositionStats(v.scale);
this.addVariable(v);
}
Block.prototype.addVariable = function (v) {
v.block = this;
this.vars.push(v);
this.ps.addVariable(v);
this.posn = this.ps.getPosn();
};
// move the block where it needs to be to minimize cost
Block.prototype.updateWeightedPosition = function () {
this.ps.AB = this.ps.AD = this.ps.A2 = 0;
for (var i = 0, n = this.vars.length; i < n; ++i)
this.ps.addVariable(this.vars[i]);
this.posn = this.ps.getPosn();
};
Block.prototype.compute_lm = function (v, u, postAction) {
var _this = this;
var dfdv = v.dfdv();
v.visitNeighbours(u, function (c, next) {
var _dfdv = _this.compute_lm(next, v, postAction);
if (next === c.right) {
dfdv += _dfdv * c.left.scale;
c.lm = _dfdv;
}
else {
dfdv += _dfdv * c.right.scale;
c.lm = -_dfdv;
}
postAction(c);
});
return dfdv / v.scale;
};
Block.prototype.populateSplitBlock = function (v, prev) {
var _this = this;
v.visitNeighbours(prev, function (c, next) {
next.offset = v.offset + (next === c.right ? c.gap : -c.gap);
_this.addVariable(next);
_this.populateSplitBlock(next, v);
});
};
// traverse the active constraint tree applying visit to each active constraint
Block.prototype.traverse = function (visit, acc, v, prev) {
var _this = this;
if (v === void 0) { v = this.vars[0]; }
if (prev === void 0) { prev = null; }
v.visitNeighbours(prev, function (c, next) {
acc.push(visit(c));
_this.traverse(visit, acc, next, v);
});
};
// calculate lagrangian multipliers on constraints and
// find the active constraint in this block with the smallest lagrangian.
// if the lagrangian is negative, then the constraint is a split candidate.
Block.prototype.findMinLM = function () {
var m = null;
this.compute_lm(this.vars[0], null, function (c) {
if (!c.equality && (m === null || c.lm < m.lm))
m = c;
});
return m;
};
Block.prototype.findMinLMBetween = function (lv, rv) {
this.compute_lm(lv, null, function () { });
var m = null;
this.findPath(lv, null, rv, function (c, next) {
if (!c.equality && c.right === next && (m === null || c.lm < m.lm))
m = c;
});
return m;
};
Block.prototype.findPath = function (v, prev, to, visit) {
var _this = this;
var endFound = false;
v.visitNeighbours(prev, function (c, next) {
if (!endFound && (next === to || _this.findPath(next, v, to, visit))) {
endFound = true;
visit(c, next);
}
});
return endFound;
};
// Search active constraint tree from u to see if there is a directed path to v.
// Returns true if path is found.
Block.prototype.isActiveDirectedPathBetween = function (u, v) {
if (u === v)
return true;
var i = u.cOut.length;
while (i--) {
var c = u.cOut[i];
if (c.active && this.isActiveDirectedPathBetween(c.right, v))
return true;
}
return false;
};
// split the block into two by deactivating the specified constraint
Block.split = function (c) {
/* DEBUG
console.log("split on " + c);
console.assert(c.active, "attempt to split on inactive constraint");
DEBUG */
c.active = false;
return [Block.createSplitBlock(c.left), Block.createSplitBlock(c.right)];
};
Block.createSplitBlock = function (startVar) {
var b = new Block(startVar);
b.populateSplitBlock(startVar, null);
return b;
};
// find a split point somewhere between the specified variables
Block.prototype.splitBetween = function (vl, vr) {
/* DEBUG
console.assert(vl.block === this);
console.assert(vr.block === this);
DEBUG */
var c = this.findMinLMBetween(vl, vr);
if (c !== null) {
var bs = Block.split(c);
return { constraint: c, lb: bs[0], rb: bs[1] };
}
// couldn't find a split point - for example the active path is all equality constraints
return null;
};
Block.prototype.mergeAcross = function (b, c, dist) {
c.active = true;
for (var i = 0, n = b.vars.length; i < n; ++i) {
var v = b.vars[i];
v.offset += dist;
this.addVariable(v);
}
this.posn = this.ps.getPosn();
};
Block.prototype.cost = function () {
var sum = 0, i = this.vars.length;
while (i--) {
var v = this.vars[i], d = v.position() - v.desiredPosition;
sum += d * d * v.weight;
}
return sum;
};
return Block;
})();
vpsc.Block = Block;
var Blocks = (function () {
function Blocks(vs) {
this.vs = vs;
var n = vs.length;
this.list = new Array(n);
while (n--) {
var b = new Block(vs[n]);
this.list[n] = b;
b.blockInd = n;
}
}
Blocks.prototype.cost = function () {
var sum = 0, i = this.list.length;
while (i--)
sum += this.list[i].cost();
return sum;
};
Blocks.prototype.insert = function (b) {
/* DEBUG
console.assert(!this.contains(b), "blocks error: tried to reinsert block " + b.blockInd)
DEBUG */
b.blockInd = this.list.length;
this.list.push(b);
/* DEBUG
console.log("insert block: " + b.blockInd);
this.contains(b);
DEBUG */
};
Blocks.prototype.remove = function (b) {
/* DEBUG
console.log("remove block: " + b.blockInd);
console.assert(this.contains(b));
DEBUG */
var last = this.list.length - 1;
var swapBlock = this.list[last];
this.list.length = last;
if (b !== swapBlock) {
this.list[b.blockInd] = swapBlock;
swapBlock.blockInd = b.blockInd;
}
};
// merge the blocks on either side of the specified constraint, by copying the smaller block into the larger
// and deleting the smaller.
Blocks.prototype.merge = function (c) {
var l = c.left.block, r = c.right.block;
/* DEBUG
console.assert(l!==r, "attempt to merge within the same block");
DEBUG */
var dist = c.right.offset - c.left.offset - c.gap;
if (l.vars.length < r.vars.length) {
r.mergeAcross(l, c, dist);
this.remove(l);
}
else {
l.mergeAcross(r, c, -dist);
this.remove(r);
}
/* DEBUG
console.assert(Math.abs(c.slack()) < 1e-6, "Error: Constraint should be at equality after merge!");
console.log("merged on " + c);
DEBUG */
};
Blocks.prototype.forEach = function (f) {
this.list.forEach(f);
};
// useful, for example, after variable desired positions change.
Blocks.prototype.updateBlockPositions = function () {
this.list.forEach(function (b) { return b.updateWeightedPosition(); });
};
// split each block across its constraint with the minimum lagrangian
Blocks.prototype.split = function (inactive) {
var _this = this;
this.updateBlockPositions();
this.list.forEach(function (b) {
var v = b.findMinLM();
if (v !== null && v.lm < Solver.LAGRANGIAN_TOLERANCE) {
b = v.left.block;
Block.split(v).forEach(function (nb) { return _this.insert(nb); });
_this.remove(b);
inactive.push(v);
}
});
};
return Blocks;
})();
vpsc.Blocks = Blocks;
var Solver = (function () {
function Solver(vs, cs) {
this.vs = vs;
this.cs = cs;
this.vs = vs;
vs.forEach(function (v) {
v.cIn = [], v.cOut = [];
/* DEBUG
v.toString = () => "v" + vs.indexOf(v);
DEBUG */
});
this.cs = cs;
cs.forEach(function (c) {
c.left.cOut.push(c);
c.right.cIn.push(c);
/* DEBUG
c.toString = () => c.left + "+" + c.gap + "<=" + c.right + " slack=" + c.slack() + " active=" + c.active;
DEBUG */
});
this.inactive = cs.map(function (c) { c.active = false; return c; });
this.bs = null;
}
Solver.prototype.cost = function () {
return this.bs.cost();
};
// set starting positions without changing desired positions.
// Note: it throws away any previous block structure.
Solver.prototype.setStartingPositions = function (ps) {
this.inactive = this.cs.map(function (c) { c.active = false; return c; });
this.bs = new Blocks(this.vs);
this.bs.forEach(function (b, i) { return b.posn = ps[i]; });
};
Solver.prototype.setDesiredPositions = function (ps) {
this.vs.forEach(function (v, i) { return v.desiredPosition = ps[i]; });
};
/* DEBUG
private getId(v: Variable): number {
return this.vs.indexOf(v);
}
// sanity check of the index integrity of the inactive list
checkInactive(): void {
var inactiveCount = 0;
this.cs.forEach(c=> {
var i = this.inactive.indexOf(c);
console.assert(!c.active && i >= 0 || c.active && i < 0, "constraint should be in the inactive list if it is not active: " + c);
if (i >= 0) {
inactiveCount++;
} else {
console.assert(c.active, "inactive constraint not found in inactive list: " + c);
}
});
console.assert(inactiveCount === this.inactive.length, inactiveCount + " inactive constraints found, " + this.inactive.length + "in inactive list");
}
// after every call to satisfy the following should check should pass
checkSatisfied(): void {
this.cs.forEach(c=>console.assert(c.slack() >= vpsc.Solver.ZERO_UPPERBOUND, "Error: Unsatisfied constraint! "+c));
}
DEBUG */
Solver.prototype.mostViolated = function () {
var minSlack = Number.MAX_VALUE, v = null, l = this.inactive, n = l.length, deletePoint = n;
for (var i = 0; i < n; ++i) {
var c = l[i];
if (c.unsatisfiable)
continue;
var slack = c.slack();
if (c.equality || slack < minSlack) {
minSlack = slack;
v = c;
deletePoint = i;
if (c.equality)
break;
}
}
if (deletePoint !== n &&
(minSlack < Solver.ZERO_UPPERBOUND && !v.active || v.equality)) {
l[deletePoint] = l[n - 1];
l.length = n - 1;
}
return v;
};
// satisfy constraints by building block structure over violated constraints
// and moving the blocks to their desired positions
Solver.prototype.satisfy = function () {
if (this.bs == null) {
this.bs = new Blocks(this.vs);
}
/* DEBUG
console.log("satisfy: " + this.bs);
DEBUG */
this.bs.split(this.inactive);
var v = null;
while ((v = this.mostViolated()) && (v.equality || v.slack() < Solver.ZERO_UPPERBOUND && !v.active)) {
var lb = v.left.block, rb = v.right.block;
/* DEBUG
console.log("most violated is: " + v);
this.bs.contains(lb);
this.bs.contains(rb);
DEBUG */
if (lb !== rb) {
this.bs.merge(v);
}
else {
if (lb.isActiveDirectedPathBetween(v.right, v.left)) {
// cycle found!
v.unsatisfiable = true;
continue;
}
// constraint is within block, need to split first
var split = lb.splitBetween(v.left, v.right);
if (split !== null) {
this.bs.insert(split.lb);
this.bs.insert(split.rb);
this.bs.remove(lb);
this.inactive.push(split.constraint);
}
else {
/* DEBUG
console.log("unsatisfiable constraint found");
DEBUG */
v.unsatisfiable = true;
continue;
}
if (v.slack() >= 0) {
/* DEBUG
console.log("violated constraint indirectly satisfied: " + v);
DEBUG */
// v was satisfied by the above split!
this.inactive.push(v);
}
else {
/* DEBUG
console.log("merge after split:");
DEBUG */
this.bs.merge(v);
}
}
}
/* DEBUG
this.checkSatisfied();
DEBUG */
};
// repeatedly build and split block structure until we converge to an optimal solution
Solver.prototype.solve = function () {
this.satisfy();
var lastcost = Number.MAX_VALUE, cost = this.bs.cost();
while (Math.abs(lastcost - cost) > 0.0001) {
this.satisfy();
lastcost = cost;
cost = this.bs.cost();
}
return cost;
};
Solver.LAGRANGIAN_TOLERANCE = -1e-4;
Solver.ZERO_UPPERBOUND = -1e-10;
return Solver;
})();
vpsc.Solver = Solver;
})(vpsc = cola.vpsc || (cola.vpsc = {}));
})(cola || (cola = {}));
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var cola;
(function (cola) {
var vpsc;
(function (vpsc) {
//Based on js_es:
//
//https://github.com/vadimg/js_bintrees
//
//Copyright (C) 2011 by Vadim Graboys
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
var TreeBase = (function () {
function TreeBase() {
// returns iterator to node if found, null otherwise
this.findIter = function (data) {
var res = this._root;
var iter = this.iterator();
while (res !== null) {
var c = this._comparator(data, res.data);
if (c === 0) {
iter._cursor = res;
return iter;
}
else {
iter._ancestors.push(res);
res = res.get_child(c > 0);
}
}
return null;
};
}
// removes all nodes from the tree
TreeBase.prototype.clear = function () {
this._root = null;
this.size = 0;
};
;
// returns node data if found, null otherwise
TreeBase.prototype.find = function (data) {
var res = this._root;
while (res !== null) {
var c = this._comparator(data, res.data);
if (c === 0) {
return res.data;
}
else {
res = res.get_child(c > 0);
}
}
return null;
};
;
// Returns an interator to the tree node immediately before (or at) the element
TreeBase.prototype.lowerBound = function (data) {
return this._bound(data, this._comparator);
};
;
// Returns an interator to the tree node immediately after (or at) the element
TreeBase.prototype.upperBound = function (data) {
var cmp = this._comparator;
function reverse_cmp(a, b) {
return cmp(b, a);
}
return this._bound(data, reverse_cmp);
};
;
// returns null if tree is empty
TreeBase.prototype.min = function () {
var res = this._root;
if (res === null) {
return null;
}
while (res.left !== null) {
res = res.left;
}
return res.data;
};
;
// returns null if tree is empty
TreeBase.prototype.max = function () {
var res = this._root;
if (res === null) {
return null;
}
while (res.right !== null) {
res = res.right;
}
return res.data;
};
;
// returns a null iterator
// call next() or prev() to point to an element
TreeBase.prototype.iterator = function () {
return new Iterator(this);
};
;
// calls cb on each node's data, in order
TreeBase.prototype.each = function (cb) {
var it = this.iterator(), data;
while ((data = it.next()) !== null) {
cb(data);
}
};
;
// calls cb on each node's data, in reverse order
TreeBase.prototype.reach = function (cb) {
var it = this.iterator(), data;
while ((data = it.prev()) !== null) {
cb(data);
}
};
;
// used for lowerBound and upperBound
TreeBase.prototype._bound = function (data, cmp) {
var cur = this._root;
var iter = this.iterator();
while (cur !== null) {
var c = this._comparator(data, cur.data);
if (c === 0) {
iter._cursor = cur;
return iter;
}
iter._ancestors.push(cur);
cur = cur.get_child(c > 0);
}
for (var i = iter._ancestors.length - 1; i >= 0; --i) {
cur = iter._ancestors[i];
if (cmp(data, cur.data) > 0) {
iter._cursor = cur;
iter._ancestors.length = i;
return iter;
}
}
iter._ancestors.length = 0;
return iter;
};
;
return TreeBase;
})();
vpsc.TreeBase = TreeBase;
var Iterator = (function () {
function Iterator(tree) {
this._tree = tree;
this._ancestors = [];
this._cursor = null;
}
Iterator.prototype.data = function () {
return this._cursor !== null ? this._cursor.data : null;
};
;
// if null-iterator, returns first node
// otherwise, returns next node
Iterator.prototype.next = function () {
if (this._cursor === null) {
var root = this._tree._root;
if (root !== null) {
this._minNode(root);
}
}
else {
if (this._cursor.right === null) {
// no greater node in subtree, go up to parent
// if coming from a right child, continue up the stack
var save;
do {
save = this._cursor;
if (this._ancestors.length) {
this._cursor = this._ancestors.pop();
}
else {
this._cursor = null;
break;
}
} while (this._cursor.right === save);
}
else {
// get the next node from the subtree
this._ancestors.push(this._cursor);
this._minNode(this._cursor.right);
}
}
return this._cursor !== null ? this._cursor.data : null;
};
;
// if null-iterator, returns last node
// otherwise, returns previous node
Iterator.prototype.prev = function () {
if (this._cursor === null) {
var root = this._tree._root;
if (root !== null) {
this._maxNode(root);
}
}
else {
if (this._cursor.left === null) {
var save;
do {
save = this._cursor;
if (this._ancestors.length) {
this._cursor = this._ancestors.pop();
}
else {
this._cursor = null;
break;
}
} while (this._cursor.left === save);
}
else {
this._ancestors.push(this._cursor);
this._maxNode(this._cursor.left);
}
}
return this._cursor !== null ? this._cursor.data : null;
};
;
Iterator.prototype._minNode = function (start) {
while (start.left !== null) {
this._ancestors.push(start);
start = start.left;
}
this._cursor = start;
};
;
Iterator.prototype._maxNode = function (start) {
while (start.right !== null) {
this._ancestors.push(start);
start = start.right;
}
this._cursor = start;
};
;
return Iterator;
})();
vpsc.Iterator = Iterator;
var Node = (function () {
function Node(data) {
this.data = data;
this.left = null;
this.right = null;
this.red = true;
}
Node.prototype.get_child = function (dir) {
return dir ? this.right : this.left;
};
;
Node.prototype.set_child = function (dir, val) {
if (dir) {
this.right = val;
}
else {
this.left = val;
}
};
;
return Node;
})();
var RBTree = (function (_super) {
__extends(RBTree, _super);
function RBTree(comparator) {
_super.call(this);
this._root = null;
this._comparator = comparator;
this.size = 0;
}
// returns true if inserted, false if duplicate
RBTree.prototype.insert = function (data) {
var ret = false;
if (this._root === null) {
// empty tree
this._root = new Node(data);
ret = true;
this.size++;
}
else {
var head = new Node(undefined); // fake tree root
var dir = false;
var last = false;
// setup
var gp = null; // grandparent
var ggp = head; // grand-grand-parent
var p = null; // parent
var node = this._root;
ggp.right = this._root;
// search down
while (true) {
if (node === null) {
// insert new node at the bottom
node = new Node(data);
p.set_child(dir, node);
ret = true;
this.size++;
}
else if (RBTree.is_red(node.left) && RBTree.is_red(node.right)) {
// color flip
node.red = true;
node.left.red = false;
node.right.red = false;
}
// fix red violation
if (RBTree.is_red(node) && RBTree.is_red(p)) {
var dir2 = ggp.right === gp;
if (node === p.get_child(last)) {
ggp.set_child(dir2, RBTree.single_rotate(gp, !last));
}
else {
ggp.set_child(dir2, RBTree.double_rotate(gp, !last));
}
}
var cmp = this._comparator(node.data, data);
// stop if found
if (cmp === 0) {
break;
}
last = dir;
dir = cmp < 0;
// update helpers
if (gp !== null) {
ggp = gp;
}
gp = p;
p = node;
node = node.get_child(dir);
}
// update root
this._root = head.right;
}
// make root black
this._root.red = false;
return ret;
};
;
// returns true if removed, false if not found
RBTree.prototype.remove = function (data) {
if (this._root === null) {
return false;
}
var head = new Node(undefined); // fake tree root
var node = head;
node.right = this._root;
var p = null; // parent
var gp = null; // grand parent
var found = null; // found item
var dir = true;
while (node.get_child(dir) !== null) {
var last = dir;
// update helpers
gp = p;
p = node;
node = node.get_child(dir);
var cmp = this._comparator(data, node.data);
dir = cmp > 0;
// save found node
if (cmp === 0) {
found = node;
}
// push the red node down
if (!RBTree.is_red(node) && !RBTree.is_red(node.get_child(dir))) {
if (RBTree.is_red(node.get_child(!dir))) {
var sr = RBTree.single_rotate(node, dir);
p.set_child(last, sr);
p = sr;
}
else if (!RBTree.is_red(node.get_child(!dir))) {
var sibling = p.get_child(!last);
if (sibling !== null) {
if (!RBTree.is_red(sibling.get_child(!last)) && !RBTree.is_red(sibling.get_child(last))) {
// color flip
p.red = false;
sibling.red = true;
node.red = true;
}
else {
var dir2 = gp.right === p;
if (RBTree.is_red(sibling.get_child(last))) {
gp.set_child(dir2, RBTree.double_rotate(p, last));
}
else if (RBTree.is_red(sibling.get_child(!last))) {
gp.set_child(dir2, RBTree.single_rotate(p, last));
}
// ensure correct coloring
var gpc = gp.get_child(dir2);
gpc.red = true;
node.red = true;
gpc.left.red = false;
gpc.right.red = false;
}
}
}
}
}
// replace and remove if found
if (found !== null) {
found.data = node.data;
p.set_child(p.right === node, node.get_child(node.left === null));
this.size--;
}
// update root and make it black
this._root = head.right;
if (this._root !== null) {
this._root.red = false;
}
return found !== null;
};
;
RBTree.is_red = function (node) {
return node !== null && node.red;
};
RBTree.single_rotate = function (root, dir) {
var save = root.get_child(!dir);
root.set_child(!dir, save.get_child(dir));
save.set_child(dir, root);
root.red = true;
save.red = false;
return save;
};
RBTree.double_rotate = function (root, dir) {
root.set_child(!dir, RBTree.single_rotate(root.get_child(!dir), !dir));
return RBTree.single_rotate(root, dir);
};
return RBTree;
})(TreeBase);
vpsc.RBTree = RBTree;
})(vpsc = cola.vpsc || (cola.vpsc = {}));
})(cola || (cola = {}));
///<reference path="vpsc.ts"/>
///<reference path="rbtree.ts"/>
var cola;
(function (cola) {
var vpsc;
(function (vpsc) {
function computeGroupBounds(g) {
g.bounds = typeof g.leaves !== "undefined" ?
g.leaves.reduce(function (r, c) { return c.bounds.union(r); }, Rectangle.empty()) :
Rectangle.empty();
if (typeof g.groups !== "undefined")
g.bounds = g.groups.reduce(function (r, c) { return computeGroupBounds(c).union(r); }, g.bounds);
g.bounds = g.bounds.inflate(g.padding);
return g.bounds;
}
vpsc.computeGroupBounds = computeGroupBounds;
var Rectangle = (function () {
function Rectangle(x, X, y, Y) {
this.x = x;
this.X = X;
this.y = y;
this.Y = Y;
}
Rectangle.empty = function () { return new Rectangle(Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY); };
Rectangle.prototype.cx = function () { return (this.x + this.X) / 2; };
Rectangle.prototype.cy = function () { return (this.y + this.Y) / 2; };
Rectangle.prototype.overlapX = function (r) {
var ux = this.cx(), vx = r.cx();
if (ux <= vx && r.x < this.X)
return this.X - r.x;
if (vx <= ux && this.x < r.X)
return r.X - this.x;
return 0;
};
Rectangle.prototype.overlapY = function (r) {
var uy = this.cy(), vy = r.cy();
if (uy <= vy && r.y < this.Y)
return this.Y - r.y;
if (vy <= uy && this.y < r.Y)
return r.Y - this.y;
return 0;
};
Rectangle.prototype.setXCentre = function (cx) {
var dx = cx - this.cx();
this.x += dx;
this.X += dx;
};
Rectangle.prototype.setYCentre = function (cy) {
var dy = cy - this.cy();
this.y += dy;
this.Y += dy;
};
Rectangle.prototype.width = function () {
return this.X - this.x;
};
Rectangle.prototype.height = function () {
return this.Y - this.y;
};
Rectangle.prototype.union = function (r) {
return new Rectangle(Math.min(this.x, r.x), Math.max(this.X, r.X), Math.min(this.y, r.y), Math.max(this.Y, r.Y));
};
/**
* return any intersection points between the given line and the sides of this rectangle
* @method lineIntersection
* @param x1 number first x coord of line
* @param y1 number first y coord of line
* @param x2 number second x coord of line
* @param y2 number second y coord of line
* @return any intersection points found
*/
Rectangle.prototype.lineIntersections = function (x1, y1, x2, y2) {
var sides = [[this.x, this.y, this.X, this.y],
[this.X, this.y, this.X, this.Y],
[this.X, this.Y, this.x, this.Y],
[this.x, this.Y, this.x, this.y]];
var intersections = [];
for (var i = 0; i < 4; ++i) {
var r = Rectangle.lineIntersection(x1, y1, x2, y2, sides[i][0], sides[i][1], sides[i][2], sides[i][3]);
if (r !== null)
intersections.push({ x: r.x, y: r.y });
}
return intersections;
};
/**
* return any intersection points between a line extending from the centre of this rectangle to the given point,
* and the sides of this rectangle
* @method lineIntersection
* @param x2 number second x coord of line
* @param y2 number second y coord of line
* @return any intersection points found
*/
Rectangle.prototype.rayIntersection = function (x2, y2) {
var ints = this.lineIntersections(this.cx(), this.cy(), x2, y2);
return ints.length > 0 ? ints[0] : null;
};
Rectangle.prototype.vertices = function () {
return [
{ x: this.x, y: this.y },
{ x: this.X, y: this.y },
{ x: this.X, y: this.Y },
{ x: this.x, y: this.Y },
{ x: this.x, y: this.y }];
};
Rectangle.lineIntersection = function (x1, y1, x2, y2, x3, y3, x4, y4) {
var dx12 = x2 - x1, dx34 = x4 - x3, dy12 = y2 - y1, dy34 = y4 - y3, denominator = dy34 * dx12 - dx34 * dy12;
if (denominator == 0)
return null;
var dx31 = x1 - x3, dy31 = y1 - y3, numa = dx34 * dy31 - dy34 * dx31, a = numa / denominator, numb = dx12 * dy31 - dy12 * dx31, b = numb / denominator;
if (a >= 0 && a <= 1 && b >= 0 && b <= 1) {
return {
x: x1 + a * dx12,
y: y1 + a * dy12
};
}
return null;
};
Rectangle.prototype.inflate = function (pad) {
return new Rectangle(this.x - pad, this.X + pad, this.y - pad, this.Y + pad);
};
return Rectangle;
})();
vpsc.Rectangle = Rectangle;
function makeEdgeBetween(link, source, target, ah) {
var si = source.rayIntersection(target.cx(), target.cy());
if (!si)
si = { x: source.cx(), y: source.cy() };
var ti = target.rayIntersection(source.cx(), source.cy());
if (!ti)
ti = { x: target.cx(), y: target.cy() };
var dx = ti.x - si.x, dy = ti.y - si.y, l = Math.sqrt(dx * dx + dy * dy), al = l - ah;
link.sourceIntersection = si;
link.targetIntersection = ti;
link.arrowStart = { x: si.x + al * dx / l, y: si.y + al * dy / l };
}
vpsc.makeEdgeBetween = makeEdgeBetween;
function makeEdgeTo(s, target, ah) {
var ti = target.rayIntersection(s.x, s.y);
if (!ti)
ti = { x: target.cx(), y: target.cy() };
var dx = ti.x - s.x, dy = ti.y - s.y, l = Math.sqrt(dx * dx + dy * dy);
return { x: ti.x - ah * dx / l, y: ti.y - ah * dy / l };
}
vpsc.makeEdgeTo = makeEdgeTo;
var Node = (function () {
function Node(v, r, pos) {
this.v = v;
this.r = r;
this.pos = pos;
this.prev = makeRBTree();
this.next = makeRBTree();
}
return Node;
})();
var Event = (function () {
function Event(isOpen, v, pos) {
this.isOpen = isOpen;
this.v = v;
this.pos = pos;
}
return Event;
})();
function compareEvents(a, b) {
if (a.pos > b.pos) {
return 1;
}
if (a.pos < b.pos) {
return -1;
}
if (a.isOpen) {
// open must come before close
return -1;
}
return 0;
}
function makeRBTree() {
return new vpsc.RBTree(function (a, b) { return a.pos - b.pos; });
}
var xRect = {
getCentre: function (r) { return r.cx(); },
getOpen: function (r) { return r.y; },
getClose: function (r) { return r.Y; },
getSize: function (r) { return r.width(); },
makeRect: function (open, close, center, size) { return new Rectangle(center - size / 2, center + size / 2, open, close); },
findNeighbours: findXNeighbours
};
var yRect = {
getCentre: function (r) { return r.cy(); },
getOpen: function (r) { return r.x; },
getClose: function (r) { return r.X; },
getSize: function (r) { return r.height(); },
makeRect: function (open, close, center, size) { return new Rectangle(open, close, center - size / 2, center + size / 2); },
findNeighbours: findYNeighbours
};
function generateGroupConstraints(root, f, minSep, isContained) {
if (isContained === void 0) { isContained = false; }
var padding = root.padding, gn = typeof root.groups !== 'undefined' ? root.groups.length : 0, ln = typeof root.leaves !== 'undefined' ? root.leaves.length : 0, childConstraints = !gn ? []
: root.groups.reduce(function (ccs, g) { return ccs.concat(generateGroupConstraints(g, f, minSep, true)); }, []), n = (isContained ? 2 : 0) + ln + gn, vs = new Array(n), rs = new Array(n), i = 0, add = function (r, v) { rs[i] = r; vs[i++] = v; };
if (isContained) {
// if this group is contained by another, then we add two dummy vars and rectangles for the borders
var b = root.bounds, c = f.getCentre(b), s = f.getSize(b) / 2, open = f.getOpen(b), close = f.getClose(b), min = c - s + padding / 2, max = c + s - padding / 2;
root.minVar.desiredPosition = min;
add(f.makeRect(open, close, min, padding), root.minVar);
root.maxVar.desiredPosition = max;
add(f.makeRect(open, close, max, padding), root.maxVar);
}
if (ln)
root.leaves.forEach(function (l) { return add(l.bounds, l.variable); });
if (gn)
root.groups.forEach(function (g) {
var b = g.bounds;
add(f.makeRect(f.getOpen(b), f.getClose(b), f.getCentre(b), f.getSize(b)), g.minVar);
});
var cs = generateConstraints(rs, vs, f, minSep);
if (gn) {
vs.forEach(function (v) { v.cOut = [], v.cIn = []; });
cs.forEach(function (c) { c.left.cOut.push(c), c.right.cIn.push(c); });
root.groups.forEach(function (g) {
var gapAdjustment = (g.padding - f.getSize(g.bounds)) / 2;
g.minVar.cIn.forEach(function (c) { return c.gap += gapAdjustment; });
g.minVar.cOut.forEach(function (c) { c.left = g.maxVar; c.gap += gapAdjustment; });
});
}
return childConstraints.concat(cs);
}
function generateConstraints(rs, vars, rect, minSep) {
var i, n = rs.length;
var N = 2 * n;
console.assert(vars.length >= n);
var events = new Array(N);
for (i = 0; i < n; ++i) {
var r = rs[i];
var v = new Node(vars[i], r, rect.getCentre(r));
events[i] = new Event(true, v, rect.getOpen(r));
events[i + n] = new Event(false, v, rect.getClose(r));
}
events.sort(compareEvents);
var cs = new Array();
var scanline = makeRBTree();
for (i = 0; i < N; ++i) {
var e = events[i];
var v = e.v;
if (e.isOpen) {
scanline.insert(v);
rect.findNeighbours(v, scanline);
}
else {
// close event
scanline.remove(v);
var makeConstraint = function (l, r) {
var sep = (rect.getSize(l.r) + rect.getSize(r.r)) / 2 + minSep;
cs.push(new vpsc.Constraint(l.v, r.v, sep));
};
var visitNeighbours = function (forward, reverse, mkcon) {
var u, it = v[forward].iterator();
while ((u = it[forward]()) !== null) {
mkcon(u, v);
u[reverse].remove(v);
}
};
visitNeighbours("prev", "next", function (u, v) { return makeConstraint(u, v); });
visitNeighbours("next", "prev", function (u, v) { return makeConstraint(v, u); });
}
}
console.assert(scanline.size === 0);
return cs;
}
function findXNeighbours(v, scanline) {
var f = function (forward, reverse) {
var it = scanline.findIter(v);
var u;
while ((u = it[forward]()) !== null) {
var uovervX = u.r.overlapX(v.r);
if (uovervX <= 0 || uovervX <= u.r.overlapY(v.r)) {
v[forward].insert(u);
u[reverse].insert(v);
}
if (uovervX <= 0) {
break;
}
}
};
f("next", "prev");
f("prev", "next");
}
function findYNeighbours(v, scanline) {
var f = function (forward, reverse) {
var u = scanline.findIter(v)[forward]();
if (u !== null && u.r.overlapX(v.r) > 0) {
v[forward].insert(u);
u[reverse].insert(v);
}
};
f("next", "prev");
f("prev", "next");
}
function generateXConstraints(rs, vars) {
return generateConstraints(rs, vars, xRect, 1e-6);
}
vpsc.generateXConstraints = generateXConstraints;
function generateYConstraints(rs, vars) {
return generateConstraints(rs, vars, yRect, 1e-6);
}
vpsc.generateYConstraints = generateYConstraints;
function generateXGroupConstraints(root) {
return generateGroupConstraints(root, xRect, 1e-6);
}
vpsc.generateXGroupConstraints = generateXGroupConstraints;
function generateYGroupConstraints(root) {
return generateGroupConstraints(root, yRect, 1e-6);
}
vpsc.generateYGroupConstraints = generateYGroupConstraints;
function removeOverlaps(rs) {
var vs = rs.map(function (r) { return new vpsc.Variable(r.cx()); });
var cs = vpsc.generateXConstraints(rs, vs);
var solver = new vpsc.Solver(vs, cs);
solver.solve();
vs.forEach(function (v, i) { return rs[i].setXCentre(v.position()); });
vs = rs.map(function (r) {
return new vpsc.Variable(r.cy());
});
cs = vpsc.generateYConstraints(rs, vs);
solver = new vpsc.Solver(vs, cs);
solver.solve();
vs.forEach(function (v, i) { return rs[i].setYCentre(v.position()); });
}
vpsc.removeOverlaps = removeOverlaps;
var IndexedVariable = (function (_super) {
__extends(IndexedVariable, _super);
function IndexedVariable(index, w) {
_super.call(this, 0, w);
this.index = index;
}
return IndexedVariable;
})(vpsc.Variable);
vpsc.IndexedVariable = IndexedVariable;
var Projection = (function () {
function Projection(nodes, groups, rootGroup, constraints, avoidOverlaps) {
var _this = this;
if (rootGroup === void 0) { rootGroup = null; }
if (constraints === void 0) { constraints = null; }
if (avoidOverlaps === void 0) { avoidOverlaps = false; }
this.nodes = nodes;
this.groups = groups;
this.rootGroup = rootGroup;
this.avoidOverlaps = avoidOverlaps;
this.variables = nodes.map(function (v, i) {
return v.variable = new IndexedVariable(i, 1);
});
if (constraints)
this.createConstraints(constraints);
if (avoidOverlaps && rootGroup && typeof rootGroup.groups !== 'undefined') {
nodes.forEach(function (v) {
if (!v.width || !v.height) {
//If undefined, default to nothing
v.bounds = new vpsc.Rectangle(v.x, v.x, v.y, v.y);
return;
}
var w2 = v.width / 2, h2 = v.height / 2;
v.bounds = new vpsc.Rectangle(v.x - w2, v.x + w2, v.y - h2, v.y + h2);
});
computeGroupBounds(rootGroup);
var i = nodes.length;
groups.forEach(function (g) {
_this.variables[i] = g.minVar = new IndexedVariable(i++, typeof g.stiffness !== "undefined" ? g.stiffness : 0.01);
_this.variables[i] = g.maxVar = new IndexedVariable(i++, typeof g.stiffness !== "undefined" ? g.stiffness : 0.01);
});
}
}
Projection.prototype.createSeparation = function (c) {
return new vpsc.Constraint(this.nodes[c.left].variable, this.nodes[c.right].variable, c.gap, typeof c.equality !== "undefined" ? c.equality : false);
};
Projection.prototype.makeFeasible = function (c) {
var _this = this;
if (!this.avoidOverlaps)
return;
var axis = 'x', dim = 'width';
if (c.axis === 'x')
axis = 'y', dim = 'height';
var vs = c.offsets.map(function (o) { return _this.nodes[o.node]; }).sort(function (a, b) { return a[axis] - b[axis]; });
var p = null;
vs.forEach(function (v) {
if (p)
v[axis] = p[axis] + p[dim] + 1;
p = v;
});
};
Projection.prototype.createAlignment = function (c) {
var _this = this;
var u = this.nodes[c.offsets[0].node].variable;
this.makeFeasible(c);
var cs = c.axis === 'x' ? this.xConstraints : this.yConstraints;
c.offsets.slice(1).forEach(function (o) {
var v = _this.nodes[o.node].variable;
cs.push(new vpsc.Constraint(u, v, o.offset, true));
});
};
Projection.prototype.createConstraints = function (constraints) {
var _this = this;
var isSep = function (c) { return typeof c.type === 'undefined' || c.type === 'separation'; };
this.xConstraints = constraints
.filter(function (c) { return c.axis === "x" && isSep(c); })
.map(function (c) { return _this.createSeparation(c); });
this.yConstraints = constraints
.filter(function (c) { return c.axis === "y" && isSep(c); })
.map(function (c) { return _this.createSeparation(c); });
constraints
.filter(function (c) { return c.type === 'alignment'; })
.forEach(function (c) { return _this.createAlignment(c); });
};
Projection.prototype.setupVariablesAndBounds = function (x0, y0, desired, getDesired) {
this.nodes.forEach(function (v, i) {
if (v.fixed) {
v.variable.weight = 1000;
desired[i] = getDesired(v);
}
else {
v.variable.weight = 1;
}
var w = (v.width || 0) / 2, h = (v.height || 0) / 2;
var ix = x0[i], iy = y0[i];
v.bounds = new Rectangle(ix - w, ix + w, iy - h, iy + h);
});
};
Projection.prototype.xProject = function (x0, y0, x) {
if (!this.rootGroup && !(this.avoidOverlaps || this.xConstraints))
return;
this.project(x0, y0, x0, x, function (v) { return v.px; }, this.xConstraints, generateXGroupConstraints, function (v) { return v.bounds.setXCentre(x[v.variable.index] = v.variable.position()); }, function (g) {
var xmin = x[g.minVar.index] = g.minVar.position();
var xmax = x[g.maxVar.index] = g.maxVar.position();
var p2 = g.padding / 2;
g.bounds.x = xmin - p2;
g.bounds.X = xmax + p2;
});
};
Projection.prototype.yProject = function (x0, y0, y) {
if (!this.rootGroup && !this.yConstraints)
return;
this.project(x0, y0, y0, y, function (v) { return v.py; }, this.yConstraints, generateYGroupConstraints, function (v) { return v.bounds.setYCentre(y[v.variable.index] = v.variable.position()); }, function (g) {
var ymin = y[g.minVar.index] = g.minVar.position();
var ymax = y[g.maxVar.index] = g.maxVar.position();
var p2 = g.padding / 2;
g.bounds.y = ymin - p2;
;
g.bounds.Y = ymax + p2;
});
};
Projection.prototype.projectFunctions = function () {
var _this = this;
return [
function (x0, y0, x) { return _this.xProject(x0, y0, x); },
function (x0, y0, y) { return _this.yProject(x0, y0, y); }
];
};
Projection.prototype.project = function (x0, y0, start, desired, getDesired, cs, generateConstraints, updateNodeBounds, updateGroupBounds) {
this.setupVariablesAndBounds(x0, y0, desired, getDesired);
if (this.rootGroup && this.avoidOverlaps) {
computeGroupBounds(this.rootGroup);
cs = cs.concat(generateConstraints(this.rootGroup));
}
this.solve(this.variables, cs, start, desired);
this.nodes.forEach(updateNodeBounds);
if (this.rootGroup && this.avoidOverlaps) {
this.groups.forEach(updateGroupBounds);
}
};
Projection.prototype.solve = function (vs, cs, starting, desired) {
var solver = new vpsc.Solver(vs, cs);
solver.setStartingPositions(starting);
solver.setDesiredPositions(desired);
solver.solve();
};
return Projection;
})();
vpsc.Projection = Projection;
})(vpsc = cola.vpsc || (cola.vpsc = {}));
})(cola || (cola = {}));
///<reference path="vpsc.ts"/>
///<reference path="rectangle.ts"/>
var cola;
(function (cola) {
var geom;
(function (geom) {
var Point = (function () {
function Point() {
}
return Point;
})();
geom.Point = Point;
var LineSegment = (function () {
function LineSegment(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
return LineSegment;
})();
geom.LineSegment = LineSegment;
var PolyPoint = (function (_super) {
__extends(PolyPoint, _super);
function PolyPoint() {
_super.apply(this, arguments);
}
return PolyPoint;
})(Point);
geom.PolyPoint = PolyPoint;
/** tests if a point is Left|On|Right of an infinite line.
* @param points P0, P1, and P2
* @return >0 for P2 left of the line through P0 and P1
* =0 for P2 on the line
* <0 for P2 right of the line
*/
function isLeft(P0, P1, P2) {
return (P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y);
}
geom.isLeft = isLeft;
function above(p, vi, vj) {
return isLeft(p, vi, vj) > 0;
}
function below(p, vi, vj) {
return isLeft(p, vi, vj) < 0;
}
/**
* returns the convex hull of a set of points using Andrew's monotone chain algorithm
* see: http://geomalgorithms.com/a10-_hull-1.html#Monotone%20Chain
* @param S array of points
* @return the convex hull as an array of points
*/
function ConvexHull(S) {
var P = S.slice(0).sort(function (a, b) { return a.x !== b.x ? b.x - a.x : b.y - a.y; });
var n = S.length, i;
var minmin = 0;
var xmin = P[0].x;
for (i = 1; i < n; ++i) {
if (P[i].x !== xmin)
break;
}
var minmax = i - 1;
var H = [];
H.push(P[minmin]); // push minmin point onto stack
if (minmax === n - 1) {
if (P[minmax].y !== P[minmin].y)
H.push(P[minmax]);
}
else {
// Get the indices of points with max x-coord and min|max y-coord
var maxmin, maxmax = n - 1;
var xmax = P[n - 1].x;
for (i = n - 2; i >= 0; i--)
if (P[i].x !== xmax)
break;
maxmin = i + 1;
// Compute the lower hull on the stack H
i = minmax;
while (++i <= maxmin) {
// the lower line joins P[minmin] with P[maxmin]
if (isLeft(P[minmin], P[maxmin], P[i]) >= 0 && i < maxmin)
continue; // ignore P[i] above or on the lower line
while (H.length > 1) {
// test if P[i] is left of the line at the stack top
if (isLeft(H[H.length - 2], H[H.length - 1], P[i]) > 0)
break; // P[i] is a new hull vertex
else
H.length -= 1; // pop top point off stack
}
if (i != minmin)
H.push(P[i]);
}
// Next, compute the upper hull on the stack H above the bottom hull
if (maxmax != maxmin)
H.push(P[maxmax]); // push maxmax point onto stack
var bot = H.length; // the bottom point of the upper hull stack
i = maxmin;
while (--i >= minmax) {
// the upper line joins P[maxmax] with P[minmax]
if (isLeft(P[maxmax], P[minmax], P[i]) >= 0 && i > minmax)
continue; // ignore P[i] below or on the upper line
while (H.length > bot) {
// test if P[i] is left of the line at the stack top
if (isLeft(H[H.length - 2], H[H.length - 1], P[i]) > 0)
break; // P[i] is a new hull vertex
else
H.length -= 1; // pop top point off stack
}
if (i != minmin)
H.push(P[i]); // push P[i] onto stack
}
}
return H;
}
geom.ConvexHull = ConvexHull;
// apply f to the points in P in clockwise order around the point p
function clockwiseRadialSweep(p, P, f) {
P.slice(0).sort(function (a, b) { return Math.atan2(a.y - p.y, a.x - p.x) - Math.atan2(b.y - p.y, b.x - p.x); }).forEach(f);
}
geom.clockwiseRadialSweep = clockwiseRadialSweep;
function nextPolyPoint(p, ps) {
if (p.polyIndex === ps.length - 1)
return ps[0];
return ps[p.polyIndex + 1];
}
function prevPolyPoint(p, ps) {
if (p.polyIndex === 0)
return ps[ps.length - 1];
return ps[p.polyIndex - 1];
}
// tangent_PointPolyC(): fast binary search for tangents to a convex polygon
// Input: P = a 2D point (exterior to the polygon)
// n = number of polygon vertices
// V = array of vertices for a 2D convex polygon with V[n] = V[0]
// Output: rtan = index of rightmost tangent point V[rtan]
// ltan = index of leftmost tangent point V[ltan]
function tangent_PointPolyC(P, V) {
return { rtan: Rtangent_PointPolyC(P, V), ltan: Ltangent_PointPolyC(P, V) };
}
// Rtangent_PointPolyC(): binary search for convex polygon right tangent
// Input: P = a 2D point (exterior to the polygon)
// n = number of polygon vertices
// V = array of vertices for a 2D convex polygon with V[n] = V[0]
// Return: index "i" of rightmost tangent point V[i]
function Rtangent_PointPolyC(P, V) {
var n = V.length - 1;
// use binary search for large convex polygons
var a, b, c; // indices for edge chain endpoints
var upA, dnC; // test for up direction of edges a and c
// rightmost tangent = maximum for the isLeft() ordering
// test if V[0] is a local maximum
if (below(P, V[1], V[0]) && !above(P, V[n - 1], V[0]))
return 0; // V[0] is the maximum tangent point
for (a = 0, b = n;;) {
if (b - a === 1)
if (above(P, V[a], V[b]))
return a;
else
return b;
c = Math.floor((a + b) / 2); // midpoint of [a,b], and 0<c<n
dnC = below(P, V[c + 1], V[c]);
if (dnC && !above(P, V[c - 1], V[c]))
return c; // V[c] is the maximum tangent point
// no max yet, so continue with the binary search
// pick one of the two subchains [a,c] or [c,b]
upA = above(P, V[a + 1], V[a]);
if (upA) {
if (dnC)
b = c; // select [a,c]
else {
if (above(P, V[a], V[c]))
b = c; // select [a,c]
else
a = c; // select [c,b]
}
}
else {
if (!dnC)
a = c; // select [c,b]
else {
if (below(P, V[a], V[c]))
b = c; // select [a,c]
else
a = c; // select [c,b]
}
}
}
}
// Ltangent_PointPolyC(): binary search for convex polygon left tangent
// Input: P = a 2D point (exterior to the polygon)
// n = number of polygon vertices
// V = array of vertices for a 2D convex polygon with V[n]=V[0]
// Return: index "i" of leftmost tangent point V[i]
function Ltangent_PointPolyC(P, V) {
var n = V.length - 1;
// use binary search for large convex polygons
var a, b, c; // indices for edge chain endpoints
var dnA, dnC; // test for down direction of edges a and c
// leftmost tangent = minimum for the isLeft() ordering
// test if V[0] is a local minimum
if (above(P, V[n - 1], V[0]) && !below(P, V[1], V[0]))
return 0; // V[0] is the minimum tangent point
for (a = 0, b = n;;) {
if (b - a === 1)
if (below(P, V[a], V[b]))
return a;
else
return b;
c = Math.floor((a + b) / 2); // midpoint of [a,b], and 0<c<n
dnC = below(P, V[c + 1], V[c]);
if (above(P, V[c - 1], V[c]) && !dnC)
return c; // V[c] is the minimum tangent point
// no min yet, so continue with the binary search
// pick one of the two subchains [a,c] or [c,b]
dnA = below(P, V[a + 1], V[a]);
if (dnA) {
if (!dnC)
b = c; // select [a,c]
else {
if (below(P, V[a], V[c]))
b = c; // select [a,c]
else
a = c; // select [c,b]
}
}
else {
if (dnC)
a = c; // select [c,b]
else {
if (above(P, V[a], V[c]))
b = c; // select [a,c]
else
a = c; // select [c,b]
}
}
}
}
// RLtangent_PolyPolyC(): get the RL tangent between two convex polygons
// Input: m = number of vertices in polygon 1
// V = array of vertices for convex polygon 1 with V[m]=V[0]
// n = number of vertices in polygon 2
// W = array of vertices for convex polygon 2 with W[n]=W[0]
// Output: *t1 = index of tangent point V[t1] for polygon 1
// *t2 = index of tangent point W[t2] for polygon 2
function tangent_PolyPolyC(V, W, t1, t2, cmp1, cmp2) {
var ix1, ix2; // search indices for polygons 1 and 2
// first get the initial vertex on each polygon
ix1 = t1(W[0], V); // right tangent from W[0] to V
ix2 = t2(V[ix1], W); // left tangent from V[ix1] to W
// ping-pong linear search until it stabilizes
var done = false; // flag when done
while (!done) {
done = true; // assume done until...
while (true) {
if (ix1 === V.length - 1)
ix1 = 0;
if (cmp1(W[ix2], V[ix1], V[ix1 + 1]))
break;
++ix1; // get Rtangent from W[ix2] to V
}
while (true) {
if (ix2 === 0)
ix2 = W.length - 1;
if (cmp2(V[ix1], W[ix2], W[ix2 - 1]))
break;
--ix2; // get Ltangent from V[ix1] to W
done = false; // not done if had to adjust this
}
}
return { t1: ix1, t2: ix2 };
}
geom.tangent_PolyPolyC = tangent_PolyPolyC;
function LRtangent_PolyPolyC(V, W) {
var rl = RLtangent_PolyPolyC(W, V);
return { t1: rl.t2, t2: rl.t1 };
}
geom.LRtangent_PolyPolyC = LRtangent_PolyPolyC;
function RLtangent_PolyPolyC(V, W) {
return tangent_PolyPolyC(V, W, Rtangent_PointPolyC, Ltangent_PointPolyC, above, below);
}
geom.RLtangent_PolyPolyC = RLtangent_PolyPolyC;
function LLtangent_PolyPolyC(V, W) {
return tangent_PolyPolyC(V, W, Ltangent_PointPolyC, Ltangent_PointPolyC, below, below);
}
geom.LLtangent_PolyPolyC = LLtangent_PolyPolyC;
function RRtangent_PolyPolyC(V, W) {
return tangent_PolyPolyC(V, W, Rtangent_PointPolyC, Rtangent_PointPolyC, above, above);
}
geom.RRtangent_PolyPolyC = RRtangent_PolyPolyC;
var BiTangent = (function () {
function BiTangent(t1, t2) {
this.t1 = t1;
this.t2 = t2;
}
return BiTangent;
})();
geom.BiTangent = BiTangent;
var BiTangents = (function () {
function BiTangents() {
}
return BiTangents;
})();
geom.BiTangents = BiTangents;
var TVGPoint = (function (_super) {
__extends(TVGPoint, _super);
function TVGPoint() {
_super.apply(this, arguments);
}
return TVGPoint;
})(Point);
geom.TVGPoint = TVGPoint;
var VisibilityVertex = (function () {
function VisibilityVertex(id, polyid, polyvertid, p) {
this.id = id;
this.polyid = polyid;
this.polyvertid = polyvertid;
this.p = p;
p.vv = this;
}
return VisibilityVertex;
})();
geom.VisibilityVertex = VisibilityVertex;
var VisibilityEdge = (function () {
function VisibilityEdge(source, target) {
this.source = source;
this.target = target;
}
VisibilityEdge.prototype.length = function () {
var dx = this.source.p.x - this.target.p.x;
var dy = this.source.p.y - this.target.p.y;
return Math.sqrt(dx * dx + dy * dy);
};
return VisibilityEdge;
})();
geom.VisibilityEdge = VisibilityEdge;
var TangentVisibilityGraph = (function () {
function TangentVisibilityGraph(P, g0) {
this.P = P;
this.V = [];
this.E = [];
if (!g0) {
var n = P.length;
for (var i = 0; i < n; i++) {
var p = P[i];
for (var j = 0; j < p.length; ++j) {
var pj = p[j], vv = new VisibilityVertex(this.V.length, i, j, pj);
this.V.push(vv);
if (j > 0)
this.E.push(new VisibilityEdge(p[j - 1].vv, vv));
}
}
for (var i = 0; i < n - 1; i++) {
var Pi = P[i];
for (var j = i + 1; j < n; j++) {
var Pj = P[j], t = geom.tangents(Pi, Pj);
for (var q in t) {
var c = t[q], source = Pi[c.t1], target = Pj[c.t2];
this.addEdgeIfVisible(source, target, i, j);
}
}
}
}
else {
this.V = g0.V.slice(0);
this.E = g0.E.slice(0);
}
}
TangentVisibilityGraph.prototype.addEdgeIfVisible = function (u, v, i1, i2) {
if (!this.intersectsPolys(new LineSegment(u.x, u.y, v.x, v.y), i1, i2)) {
this.E.push(new VisibilityEdge(u.vv, v.vv));
}
};
TangentVisibilityGraph.prototype.addPoint = function (p, i1) {
var n = this.P.length;
this.V.push(new VisibilityVertex(this.V.length, n, 0, p));
for (var i = 0; i < n; ++i) {
if (i === i1)
continue;
var poly = this.P[i], t = tangent_PointPolyC(p, poly);
this.addEdgeIfVisible(p, poly[t.ltan], i1, i);
this.addEdgeIfVisible(p, poly[t.rtan], i1, i);
}
return p.vv;
};
TangentVisibilityGraph.prototype.intersectsPolys = function (l, i1, i2) {
for (var i = 0, n = this.P.length; i < n; ++i) {
if (i != i1 && i != i2 && intersects(l, this.P[i]).length > 0) {
return true;
}
}
return false;
};
return TangentVisibilityGraph;
})();
geom.TangentVisibilityGraph = TangentVisibilityGraph;
function intersects(l, P) {
var ints = [];
for (var i = 1, n = P.length; i < n; ++i) {
var int = cola.vpsc.Rectangle.lineIntersection(l.x1, l.y1, l.x2, l.y2, P[i - 1].x, P[i - 1].y, P[i].x, P[i].y);
if (int)
ints.push(int);
}
return ints;
}
function tangents(V, W) {
var m = V.length - 1, n = W.length - 1;
var bt = new BiTangents();
for (var i = 0; i < m; ++i) {
for (var j = 0; j < n; ++j) {
var v1 = V[i == 0 ? m - 1 : i - 1];
var v2 = V[i];
var v3 = V[i + 1];
var w1 = W[j == 0 ? n - 1 : j - 1];
var w2 = W[j];
var w3 = W[j + 1];
var v1v2w2 = isLeft(v1, v2, w2);
var v2w1w2 = isLeft(v2, w1, w2);
var v2w2w3 = isLeft(v2, w2, w3);
var w1w2v2 = isLeft(w1, w2, v2);
var w2v1v2 = isLeft(w2, v1, v2);
var w2v2v3 = isLeft(w2, v2, v3);
if (v1v2w2 >= 0 && v2w1w2 >= 0 && v2w2w3 < 0
&& w1w2v2 >= 0 && w2v1v2 >= 0 && w2v2v3 < 0) {
bt.ll = new BiTangent(i, j);
}
else if (v1v2w2 <= 0 && v2w1w2 <= 0 && v2w2w3 > 0
&& w1w2v2 <= 0 && w2v1v2 <= 0 && w2v2v3 > 0) {
bt.rr = new BiTangent(i, j);
}
else if (v1v2w2 <= 0 && v2w1w2 > 0 && v2w2w3 <= 0
&& w1w2v2 >= 0 && w2v1v2 < 0 && w2v2v3 >= 0) {
bt.rl = new BiTangent(i, j);
}
else if (v1v2w2 >= 0 && v2w1w2 < 0 && v2w2w3 >= 0
&& w1w2v2 <= 0 && w2v1v2 > 0 && w2v2v3 <= 0) {
bt.lr = new BiTangent(i, j);
}
}
}
return bt;
}
geom.tangents = tangents;
function isPointInsidePoly(p, poly) {
for (var i = 1, n = poly.length; i < n; ++i)
if (below(poly[i - 1], poly[i], p))
return false;
return true;
}
function isAnyPInQ(p, q) {
return !p.every(function (v) { return !isPointInsidePoly(v, q); });
}
function polysOverlap(p, q) {
if (isAnyPInQ(p, q))
return true;
if (isAnyPInQ(q, p))
return true;
for (var i = 1, n = p.length; i < n; ++i) {
var v = p[i], u = p[i - 1];
if (intersects(new LineSegment(u.x, u.y, v.x, v.y), q).length > 0)
return true;
}
return false;
}
geom.polysOverlap = polysOverlap;
})(geom = cola.geom || (cola.geom = {}));
})(cola || (cola = {}));
/**
* @module cola
*/
var cola;
(function (cola) {
/**
* Descent respects a collection of locks over nodes that should not move
* @class Locks
*/
var Locks = (function () {
function Locks() {
this.locks = {};
}
/**
* add a lock on the node at index id
* @method add
* @param id index of node to be locked
* @param x required position for node
*/
Locks.prototype.add = function (id, x) {
/* DEBUG
if (isNaN(x[0]) || isNaN(x[1])) debugger;
DEBUG */
this.locks[id] = x;
};
/**
* @method clear clear all locks
*/
Locks.prototype.clear = function () {
this.locks = {};
};
/**
* @isEmpty
* @returns false if no locks exist
*/
Locks.prototype.isEmpty = function () {
for (var l in this.locks)
return false;
return true;
};
/**
* perform an operation on each lock
* @apply
*/
Locks.prototype.apply = function (f) {
for (var l in this.locks) {
f(l, this.locks[l]);
}
};
return Locks;
})();
cola.Locks = Locks;
/**
* Uses a gradient descent approach to reduce a stress or p-stress goal function over a graph with specified ideal edge lengths or a square matrix of dissimilarities.
* The standard stress function over a graph nodes with position vectors x,y,z is (mathematica input):
* stress[x_,y_,z_,D_,w_]:=Sum[w[[i,j]] (length[x[[i]],y[[i]],z[[i]],x[[j]],y[[j]],z[[j]]]-d[[i,j]])^2,{i,Length[x]-1},{j,i+1,Length[x]}]
* where: D is a square matrix of ideal separations between nodes, w is matrix of weights for those separations
* length[x1_, y1_, z1_, x2_, y2_, z2_] = Sqrt[(x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2]
* below, we use wij = 1/(Dij^2)
*
* @class Descent
*/
var Descent = (function () {
/**
* @method constructor
* @param x {number[][]} initial coordinates for nodes
* @param D {number[][]} matrix of desired distances between pairs of nodes
* @param G {number[][]} [default=null] if specified, G is a matrix of weights for goal terms between pairs of nodes.
* If G[i][j] > 1 and the separation between nodes i and j is greater than their ideal distance, then there is no contribution for this pair to the goal
* If G[i][j] <= 1 then it is used as a weighting on the contribution of the variance between ideal and actual separation between i and j to the goal function
*/
function Descent(x, D, G) {
if (G === void 0) { G = null; }
this.D = D;
this.G = G;
this.threshold = 0.0001;
// Parameters for grid snap stress.
// TODO: Make a pluggable "StressTerm" class instead of this
// mess.
this.numGridSnapNodes = 0;
this.snapGridSize = 100;
this.snapStrength = 1000;
this.scaleSnapByMaxH = false;
this.random = new PseudoRandom();
this.project = null;
this.x = x;
this.k = x.length; // dimensionality
var n = this.n = x[0].length; // number of nodes
this.H = new Array(this.k);
this.g = new Array(this.k);
this.Hd = new Array(this.k);
this.a = new Array(this.k);
this.b = new Array(this.k);
this.c = new Array(this.k);
this.d = new Array(this.k);
this.e = new Array(this.k);
this.ia = new Array(this.k);
this.ib = new Array(this.k);
this.xtmp = new Array(this.k);
this.locks = new Locks();
this.minD = Number.MAX_VALUE;
var i = n, j;
while (i--) {
j = n;
while (--j > i) {
var d = D[i][j];
if (d > 0 && d < this.minD) {
this.minD = d;
}
}
}
if (this.minD === Number.MAX_VALUE)
this.minD = 1;
i = this.k;
while (i--) {
this.g[i] = new Array(n);
this.H[i] = new Array(n);
j = n;
while (j--) {
this.H[i][j] = new Array(n);
}
this.Hd[i] = new Array(n);
this.a[i] = new Array(n);
this.b[i] = new Array(n);
this.c[i] = new Array(n);
this.d[i] = new Array(n);
this.e[i] = new Array(n);
this.ia[i] = new Array(n);
this.ib[i] = new Array(n);
this.xtmp[i] = new Array(n);
}
}
Descent.createSquareMatrix = function (n, f) {
var M = new Array(n);
for (var i = 0; i < n; ++i) {
M[i] = new Array(n);
for (var j = 0; j < n; ++j) {
M[i][j] = f(i, j);
}
}
return M;
};
Descent.prototype.offsetDir = function () {
var _this = this;
var u = new Array(this.k);
var l = 0;
for (var i = 0; i < this.k; ++i) {
var x = u[i] = this.random.getNextBetween(0.01, 1) - 0.5;
l += x * x;
}
l = Math.sqrt(l);
return u.map(function (x) { return x *= _this.minD / l; });
};
// compute first and second derivative information storing results in this.g and this.H
Descent.prototype.computeDerivatives = function (x) {
var _this = this;
var n = this.n;
if (n < 1)
return;
var i;
/* DEBUG
for (var u: number = 0; u < n; ++u)
for (i = 0; i < this.k; ++i)
if (isNaN(x[i][u])) debugger;
DEBUG */
var d = new Array(this.k);
var d2 = new Array(this.k);
var Huu = new Array(this.k);
var maxH = 0;
for (var u = 0; u < n; ++u) {
for (i = 0; i < this.k; ++i)
Huu[i] = this.g[i][u] = 0;
for (var v = 0; v < n; ++v) {
if (u === v)
continue;
// The following loop randomly displaces nodes that are at identical positions
var maxDisplaces = n; // avoid infinite loop in the case of numerical issues, such as huge values
while (maxDisplaces--) {
var sd2 = 0;
for (i = 0; i < this.k; ++i) {
var dx = d[i] = x[i][u] - x[i][v];
sd2 += d2[i] = dx * dx;
}
if (sd2 > 1e-9)
break;
var rd = this.offsetDir();
for (i = 0; i < this.k; ++i)
x[i][v] += rd[i];
}
var l = Math.sqrt(sd2);
var D = this.D[u][v];
var weight = this.G != null ? this.G[u][v] : 1;
if (weight > 1 && l > D || !isFinite(D)) {
for (i = 0; i < this.k; ++i)
this.H[i][u][v] = 0;
continue;
}
if (weight > 1) {
weight = 1;
}
var D2 = D * D;
var gs = 2 * weight * (l - D) / (D2 * l);
var l3 = l * l * l;
var hs = 2 * -weight / (D2 * l3);
if (!isFinite(gs))
console.log(gs);
for (i = 0; i < this.k; ++i) {
this.g[i][u] += d[i] * gs;
Huu[i] -= this.H[i][u][v] = hs * (l3 + D * (d2[i] - sd2) + l * sd2);
}
}
for (i = 0; i < this.k; ++i)
maxH = Math.max(maxH, this.H[i][u][u] = Huu[i]);
}
// Grid snap forces
var r = this.snapGridSize / 2;
var g = this.snapGridSize;
var w = this.snapStrength;
var k = w / (r * r);
var numNodes = this.numGridSnapNodes;
//var numNodes = n;
for (var u = 0; u < numNodes; ++u) {
for (i = 0; i < this.k; ++i) {
var xiu = this.x[i][u];
var m = xiu / g;
var f = m % 1;
var q = m - f;
var a = Math.abs(f);
var dx = (a <= 0.5) ? xiu - q * g :
(xiu > 0) ? xiu - (q + 1) * g : xiu - (q - 1) * g;
if (-r < dx && dx <= r) {
if (this.scaleSnapByMaxH) {
this.g[i][u] += maxH * k * dx;
this.H[i][u][u] += maxH * k;
}
else {
this.g[i][u] += k * dx;
this.H[i][u][u] += k;
}
}
}
}
if (!this.locks.isEmpty()) {
this.locks.apply(function (u, p) {
for (i = 0; i < _this.k; ++i) {
_this.H[i][u][u] += maxH;
_this.g[i][u] -= maxH * (p[i] - x[i][u]);
}
});
}
/* DEBUG
for (var u: number = 0; u < n; ++u)
for (i = 0; i < this.k; ++i) {
if (isNaN(this.g[i][u])) debugger;
for (var v: number = 0; v < n; ++v)
if (isNaN(this.H[i][u][v])) debugger;
}
DEBUG */
};
Descent.dotProd = function (a, b) {
var x = 0, i = a.length;
while (i--)
x += a[i] * b[i];
return x;
};
// result r = matrix m * vector v
Descent.rightMultiply = function (m, v, r) {
var i = m.length;
while (i--)
r[i] = Descent.dotProd(m[i], v);
};
// computes the optimal step size to take in direction d using the
// derivative information in this.g and this.H
// returns the scalar multiplier to apply to d to get the optimal step
Descent.prototype.computeStepSize = function (d) {
var numerator = 0, denominator = 0;
for (var i = 0; i < this.k; ++i) {
numerator += Descent.dotProd(this.g[i], d[i]);
Descent.rightMultiply(this.H[i], d[i], this.Hd[i]);
denominator += Descent.dotProd(d[i], this.Hd[i]);
}
if (denominator === 0 || !isFinite(denominator))
return 0;
return 1 * numerator / denominator;
};
Descent.prototype.reduceStress = function () {
this.computeDerivatives(this.x);
var alpha = this.computeStepSize(this.g);
for (var i = 0; i < this.k; ++i) {
this.takeDescentStep(this.x[i], this.g[i], alpha);
}
return this.computeStress();
};
Descent.copy = function (a, b) {
var m = a.length, n = b[0].length;
for (var i = 0; i < m; ++i) {
for (var j = 0; j < n; ++j) {
b[i][j] = a[i][j];
}
}
};
// takes a step of stepSize * d from x0, and then project against any constraints.
// result is returned in r.
// x0: starting positions
// r: result positions will be returned here
// d: unconstrained descent vector
// stepSize: amount to step along d
Descent.prototype.stepAndProject = function (x0, r, d, stepSize) {
Descent.copy(x0, r);
this.takeDescentStep(r[0], d[0], stepSize);
if (this.project)
this.project[0](x0[0], x0[1], r[0]);
this.takeDescentStep(r[1], d[1], stepSize);
if (this.project)
this.project[1](r[0], x0[1], r[1]);
// todo: allow projection against constraints in higher dimensions
for (var i = 2; i < this.k; i++)
this.takeDescentStep(r[i], d[i], stepSize);
// the following makes locks extra sticky... but hides the result of the projection from the consumer
//if (!this.locks.isEmpty()) {
// this.locks.apply((u, p) => {
// for (var i = 0; i < this.k; i++) {
// r[i][u] = p[i];
// }
// });
//}
};
Descent.mApply = function (m, n, f) {
var i = m;
while (i-- > 0) {
var j = n;
while (j-- > 0)
f(i, j);
}
};
Descent.prototype.matrixApply = function (f) {
Descent.mApply(this.k, this.n, f);
};
Descent.prototype.computeNextPosition = function (x0, r) {
var _this = this;
this.computeDerivatives(x0);
var alpha = this.computeStepSize(this.g);
this.stepAndProject(x0, r, this.g, alpha);
/* DEBUG
for (var u: number = 0; u < this.n; ++u)
for (var i = 0; i < this.k; ++i)
if (isNaN(r[i][u])) debugger;
DEBUG */
if (this.project) {
this.matrixApply(function (i, j) { return _this.e[i][j] = x0[i][j] - r[i][j]; });
var beta = this.computeStepSize(this.e);
beta = Math.max(0.2, Math.min(beta, 1));
this.stepAndProject(x0, r, this.e, beta);
}
};
Descent.prototype.run = function (iterations) {
var stress = Number.MAX_VALUE, converged = false;
while (!converged && iterations-- > 0) {
var s = this.rungeKutta();
converged = Math.abs(stress / s - 1) < this.threshold;
stress = s;
}
return stress;
};
Descent.prototype.rungeKutta = function () {
var _this = this;
this.computeNextPosition(this.x, this.a);
Descent.mid(this.x, this.a, this.ia);
this.computeNextPosition(this.ia, this.b);
Descent.mid(this.x, this.b, this.ib);
this.computeNextPosition(this.ib, this.c);
this.computeNextPosition(this.c, this.d);
var disp = 0;
this.matrixApply(function (i, j) {
var x = (_this.a[i][j] + 2.0 * _this.b[i][j] + 2.0 * _this.c[i][j] + _this.d[i][j]) / 6.0, d = _this.x[i][j] - x;
disp += d * d;
_this.x[i][j] = x;
});
return disp;
};
Descent.mid = function (a, b, m) {
Descent.mApply(a.length, a[0].length, function (i, j) {
return m[i][j] = a[i][j] + (b[i][j] - a[i][j]) / 2.0;
});
};
Descent.prototype.takeDescentStep = function (x, d, stepSize) {
for (var i = 0; i < this.n; ++i) {
x[i] = x[i] - stepSize * d[i];
}
};
Descent.prototype.computeStress = function () {
var stress = 0;
for (var u = 0, nMinus1 = this.n - 1; u < nMinus1; ++u) {
for (var v = u + 1, n = this.n; v < n; ++v) {
var l = 0;
for (var i = 0; i < this.k; ++i) {
var dx = this.x[i][u] - this.x[i][v];
l += dx * dx;
}
l = Math.sqrt(l);
var d = this.D[u][v];
if (!isFinite(d))
continue;
var rl = d - l;
var d2 = d * d;
stress += rl * rl / d2;
}
}
return stress;
};
Descent.zeroDistance = 1e-10;
return Descent;
})();
cola.Descent = Descent;
// Linear congruential pseudo random number generator
var PseudoRandom = (function () {
function PseudoRandom(seed) {
if (seed === void 0) { seed = 1; }
this.seed = seed;
this.a = 214013;
this.c = 2531011;
this.m = 2147483648;
this.range = 32767;
}
// random real between 0 and 1
PseudoRandom.prototype.getNext = function () {
this.seed = (this.seed * this.a + this.c) % this.m;
return (this.seed >> 16) / this.range;
};
// random real between min and max
PseudoRandom.prototype.getNextBetween = function (min, max) {
return min + this.getNext() * (max - min);
};
return PseudoRandom;
})();
cola.PseudoRandom = PseudoRandom;
})(cola || (cola = {}));
var cola;
(function (cola) {
var powergraph;
(function (powergraph) {
var PowerEdge = (function () {
function PowerEdge(source, target, type) {
this.source = source;
this.target = target;
this.type = type;
}
return PowerEdge;
})();
powergraph.PowerEdge = PowerEdge;
var Configuration = (function () {
function Configuration(n, edges, linkAccessor, rootGroup) {
var _this = this;
this.linkAccessor = linkAccessor;
this.modules = new Array(n);
this.roots = [];
if (rootGroup) {
this.initModulesFromGroup(rootGroup);
}
else {
this.roots.push(new ModuleSet());
for (var i = 0; i < n; ++i)
this.roots[0].add(this.modules[i] = new Module(i));
}
this.R = edges.length;
edges.forEach(function (e) {
var s = _this.modules[linkAccessor.getSourceIndex(e)], t = _this.modules[linkAccessor.getTargetIndex(e)], type = linkAccessor.getType(e);
s.outgoing.add(type, t);
t.incoming.add(type, s);
});
}
Configuration.prototype.initModulesFromGroup = function (group) {
var moduleSet = new ModuleSet();
this.roots.push(moduleSet);
for (var i = 0; i < group.leaves.length; ++i) {
var node = group.leaves[i];
var module = new Module(node.id);
this.modules[node.id] = module;
moduleSet.add(module);
}
if (group.groups) {
for (var j = 0; j < group.groups.length; ++j) {
var child = group.groups[j];
// Propagate group properties (like padding, stiffness, ...) as module definition so that the generated power graph group will inherit it
var definition = {};
for (var prop in child)
if (prop !== "leaves" && prop !== "groups" && child.hasOwnProperty(prop))
definition[prop] = child[prop];
// Use negative module id to avoid clashes between predefined and generated modules
moduleSet.add(new Module(-1 - j, new LinkSets(), new LinkSets(), this.initModulesFromGroup(child), definition));
}
}
return moduleSet;
};
// merge modules a and b keeping track of their power edges and removing the from roots
Configuration.prototype.merge = function (a, b, k) {
if (k === void 0) { k = 0; }
var inInt = a.incoming.intersection(b.incoming), outInt = a.outgoing.intersection(b.outgoing);
var children = new ModuleSet();
children.add(a);
children.add(b);
var m = new Module(this.modules.length, outInt, inInt, children);
this.modules.push(m);
var update = function (s, i, o) {
s.forAll(function (ms, linktype) {
ms.forAll(function (n) {
var nls = n[i];
nls.add(linktype, m);
nls.remove(linktype, a);
nls.remove(linktype, b);
a[o].remove(linktype, n);
b[o].remove(linktype, n);
});
});
};
update(outInt, "incoming", "outgoing");
update(inInt, "outgoing", "incoming");
this.R -= inInt.count() + outInt.count();
this.roots[k].remove(a);
this.roots[k].remove(b);
this.roots[k].add(m);
return m;
};
Configuration.prototype.rootMerges = function (k) {
if (k === void 0) { k = 0; }
var rs = this.roots[k].modules();
var n = rs.length;
var merges = new Array(n * (n - 1));
var ctr = 0;
for (var i = 0, i_ = n - 1; i < i_; ++i) {
for (var j = i + 1; j < n; ++j) {
var a = rs[i], b = rs[j];
merges[ctr] = { id: ctr, nEdges: this.nEdges(a, b), a: a, b: b };
ctr++;
}
}
return merges;
};
Configuration.prototype.greedyMerge = function () {
for (var i = 0; i < this.roots.length; ++i) {
// Handle single nested module case
if (this.roots[i].modules().length < 2)
continue;
// find the merge that allows for the most edges to be removed. secondary ordering based on arbitrary id (for predictability)
var ms = this.rootMerges(i).sort(function (a, b) { return a.nEdges == b.nEdges ? a.id - b.id : a.nEdges - b.nEdges; });
var m = ms[0];
if (m.nEdges >= this.R)
continue;
this.merge(m.a, m.b, i);
return true;
}
};
Configuration.prototype.nEdges = function (a, b) {
var inInt = a.incoming.intersection(b.incoming), outInt = a.outgoing.intersection(b.outgoing);
return this.R - inInt.count() - outInt.count();
};
Configuration.prototype.getGroupHierarchy = function (retargetedEdges) {
var _this = this;
var groups = [];
var root = {};
toGroups(this.roots[0], root, groups);
var es = this.allEdges();
es.forEach(function (e) {
var a = _this.modules[e.source];
var b = _this.modules[e.target];
retargetedEdges.push(new PowerEdge(typeof a.gid === "undefined" ? e.source : groups[a.gid], typeof b.gid === "undefined" ? e.target : groups[b.gid], e.type));
});
return groups;
};
Configuration.prototype.allEdges = function () {
var es = [];
Configuration.getEdges(this.roots[0], es);
return es;
};
Configuration.getEdges = function (modules, es) {
modules.forAll(function (m) {
m.getEdges(es);
Configuration.getEdges(m.children, es);
});
};
return Configuration;
})();
powergraph.Configuration = Configuration;
function toGroups(modules, group, groups) {
modules.forAll(function (m) {
if (m.isLeaf()) {
if (!group.leaves)
group.leaves = [];
group.leaves.push(m.id);
}
else {
var g = group;
m.gid = groups.length;
if (!m.isIsland() || m.isPredefined()) {
g = { id: m.gid };
if (m.isPredefined())
// Apply original group properties
for (var prop in m.definition)
g[prop] = m.definition[prop];
if (!group.groups)
group.groups = [];
group.groups.push(m.gid);
groups.push(g);
}
toGroups(m.children, g, groups);
}
});
}
var Module = (function () {
function Module(id, outgoing, incoming, children, definition) {
if (outgoing === void 0) { outgoing = new LinkSets(); }
if (incoming === void 0) { incoming = new LinkSets(); }
if (children === void 0) { children = new ModuleSet(); }
this.id = id;
this.outgoing = outgoing;
this.incoming = incoming;
this.children = children;
this.definition = definition;
}
Module.prototype.getEdges = function (es) {
var _this = this;
this.outgoing.forAll(function (ms, edgetype) {
ms.forAll(function (target) {
es.push(new PowerEdge(_this.id, target.id, edgetype));
});
});
};
Module.prototype.isLeaf = function () {
return this.children.count() === 0;
};
Module.prototype.isIsland = function () {
return this.outgoing.count() === 0 && this.incoming.count() === 0;
};
Module.prototype.isPredefined = function () {
return typeof this.definition !== "undefined";
};
return Module;
})();
powergraph.Module = Module;
function intersection(m, n) {
var i = {};
for (var v in m)
if (v in n)
i[v] = m[v];
return i;
}
var ModuleSet = (function () {
function ModuleSet() {
this.table = {};
}
ModuleSet.prototype.count = function () {
return Object.keys(this.table).length;
};
ModuleSet.prototype.intersection = function (other) {
var result = new ModuleSet();
result.table = intersection(this.table, other.table);
return result;
};
ModuleSet.prototype.intersectionCount = function (other) {
return this.intersection(other).count();
};
ModuleSet.prototype.contains = function (id) {
return id in this.table;
};
ModuleSet.prototype.add = function (m) {
this.table[m.id] = m;
};
ModuleSet.prototype.remove = function (m) {
delete this.table[m.id];
};
ModuleSet.prototype.forAll = function (f) {
for (var mid in this.table) {
f(this.table[mid]);
}
};
ModuleSet.prototype.modules = function () {
var vs = [];
this.forAll(function (m) {
if (!m.isPredefined())
vs.push(m);
});
return vs;
};
return ModuleSet;
})();
powergraph.ModuleSet = ModuleSet;
var LinkSets = (function () {
function LinkSets() {
this.sets = {};
this.n = 0;
}
LinkSets.prototype.count = function () {
return this.n;
};
LinkSets.prototype.contains = function (id) {
var result = false;
this.forAllModules(function (m) {
if (!result && m.id == id) {
result = true;
}
});
return result;
};
LinkSets.prototype.add = function (linktype, m) {
var s = linktype in this.sets ? this.sets[linktype] : this.sets[linktype] = new ModuleSet();
s.add(m);
++this.n;
};
LinkSets.prototype.remove = function (linktype, m) {
var ms = this.sets[linktype];
ms.remove(m);
if (ms.count() === 0) {
delete this.sets[linktype];
}
--this.n;
};
LinkSets.prototype.forAll = function (f) {
for (var linktype in this.sets) {
f(this.sets[linktype], linktype);
}
};
LinkSets.prototype.forAllModules = function (f) {
this.forAll(function (ms, lt) { return ms.forAll(f); });
};
LinkSets.prototype.intersection = function (other) {
var result = new LinkSets();
this.forAll(function (ms, lt) {
if (lt in other.sets) {
var i = ms.intersection(other.sets[lt]), n = i.count();
if (n > 0) {
result.sets[lt] = i;
result.n += n;
}
}
});
return result;
};
return LinkSets;
})();
powergraph.LinkSets = LinkSets;
function intersectionCount(m, n) {
return Object.keys(intersection(m, n)).length;
}
function getGroups(nodes, links, la, rootGroup) {
var n = nodes.length, c = new powergraph.Configuration(n, links, la, rootGroup);
while (c.greedyMerge())
;
var powerEdges = [];
var g = c.getGroupHierarchy(powerEdges);
powerEdges.forEach(function (e) {
var f = function (end) {
var g = e[end];
if (typeof g == "number")
e[end] = nodes[g];
};
f("source");
f("target");
});
return { groups: g, powerEdges: powerEdges };
}
powergraph.getGroups = getGroups;
})(powergraph = cola.powergraph || (cola.powergraph = {}));
})(cola || (cola = {}));
/**
* @module cola
*/
var cola;
(function (cola) {
// compute the size of the union of two sets a and b
function unionCount(a, b) {
var u = {};
for (var i in a)
u[i] = {};
for (var i in b)
u[i] = {};
return Object.keys(u).length;
}
// compute the size of the intersection of two sets a and b
function intersectionCount(a, b) {
var n = 0;
for (var i in a)
if (typeof b[i] !== 'undefined')
++n;
return n;
}
function getNeighbours(links, la) {
var neighbours = {};
var addNeighbours = function (u, v) {
if (typeof neighbours[u] === 'undefined')
neighbours[u] = {};
neighbours[u][v] = {};
};
links.forEach(function (e) {
var u = la.getSourceIndex(e), v = la.getTargetIndex(e);
addNeighbours(u, v);
addNeighbours(v, u);
});
return neighbours;
}
// modify the lengths of the specified links by the result of function f weighted by w
function computeLinkLengths(links, w, f, la) {
var neighbours = getNeighbours(links, la);
links.forEach(function (l) {
var a = neighbours[la.getSourceIndex(l)];
var b = neighbours[la.getTargetIndex(l)];
la.setLength(l, 1 + w * f(a, b));
});
}
/** modify the specified link lengths based on the symmetric difference of their neighbours
* @class symmetricDiffLinkLengths
*/
function symmetricDiffLinkLengths(links, la, w) {
if (w === void 0) { w = 1; }
computeLinkLengths(links, w, function (a, b) { return Math.sqrt(unionCount(a, b) - intersectionCount(a, b)); }, la);
}
cola.symmetricDiffLinkLengths = symmetricDiffLinkLengths;
/** modify the specified links lengths based on the jaccard difference between their neighbours
* @class jaccardLinkLengths
*/
function jaccardLinkLengths(links, la, w) {
if (w === void 0) { w = 1; }
computeLinkLengths(links, w, function (a, b) {
return Math.min(Object.keys(a).length, Object.keys(b).length) < 1.1 ? 0 : intersectionCount(a, b) / unionCount(a, b);
}, la);
}
cola.jaccardLinkLengths = jaccardLinkLengths;
/** generate separation constraints for all edges unless both their source and sink are in the same strongly connected component
* @class generateDirectedEdgeConstraints
*/
function generateDirectedEdgeConstraints(n, links, axis, la) {
var components = stronglyConnectedComponents(n, links, la);
var nodes = {};
components.forEach(function (c, i) {
return c.forEach(function (v) { return nodes[v] = i; });
});
var constraints = [];
links.forEach(function (l) {
var ui = la.getSourceIndex(l), vi = la.getTargetIndex(l), u = nodes[ui], v = nodes[vi];
if (u !== v) {
constraints.push({
axis: axis,
left: ui,
right: vi,
gap: la.getMinSeparation(l)
});
}
});
return constraints;
}
cola.generateDirectedEdgeConstraints = generateDirectedEdgeConstraints;
/**
* Tarjan's strongly connected components algorithm for directed graphs
* returns an array of arrays of node indicies in each of the strongly connected components.
* a vertex not in a SCC of two or more nodes is it's own SCC.
* adaptation of https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*/
function stronglyConnectedComponents(numVertices, edges, la) {
var nodes = [];
var index = 0;
var stack = [];
var components = [];
function strongConnect(v) {
// Set the depth index for v to the smallest unused index
v.index = v.lowlink = index++;
stack.push(v);
v.onStack = true;
// Consider successors of v
for (var _i = 0, _a = v.out; _i < _a.length; _i++) {
var w = _a[_i];
if (typeof w.index === 'undefined') {
// Successor w has not yet been visited; recurse on it
strongConnect(w);
v.lowlink = Math.min(v.lowlink, w.lowlink);
}
else if (w.onStack) {
// Successor w is in stack S and hence in the current SCC
v.lowlink = Math.min(v.lowlink, w.index);
}
}
// If v is a root node, pop the stack and generate an SCC
if (v.lowlink === v.index) {
// start a new strongly connected component
var component = [];
while (stack.length) {
w = stack.pop();
w.onStack = false;
//add w to current strongly connected component
component.push(w);
if (w === v)
break;
}
// output the current strongly connected component
components.push(component.map(function (v) { return v.id; }));
}
}
for (var i = 0; i < numVertices; i++) {
nodes.push({ id: i, out: [] });
}
for (var _i = 0; _i < edges.length; _i++) {
var e = edges[_i];
var v_1 = nodes[la.getSourceIndex(e)], w = nodes[la.getTargetIndex(e)];
v_1.out.push(w);
}
for (var _a = 0; _a < nodes.length; _a++) {
var v = nodes[_a];
if (typeof v.index === 'undefined')
strongConnect(v);
}
return components;
}
cola.stronglyConnectedComponents = stronglyConnectedComponents;
})(cola || (cola = {}));
var PairingHeap = (function () {
// from: https://gist.github.com/nervoussystem
//{elem:object, subheaps:[array of heaps]}
function PairingHeap(elem) {
this.elem = elem;
this.subheaps = [];
}
PairingHeap.prototype.toString = function (selector) {
var str = "", needComma = false;
for (var i = 0; i < this.subheaps.length; ++i) {
var subheap = this.subheaps[i];
if (!subheap.elem) {
needComma = false;
continue;
}
if (needComma) {
str = str + ",";
}
str = str + subheap.toString(selector);
needComma = true;
}
if (str !== "") {
str = "(" + str + ")";
}
return (this.elem ? selector(this.elem) : "") + str;
};
PairingHeap.prototype.forEach = function (f) {
if (!this.empty()) {
f(this.elem, this);
this.subheaps.forEach(function (s) { return s.forEach(f); });
}
};
PairingHeap.prototype.count = function () {
return this.empty() ? 0 : 1 + this.subheaps.reduce(function (n, h) {
return n + h.count();
}, 0);
};
PairingHeap.prototype.min = function () {
return this.elem;
};
PairingHeap.prototype.empty = function () {
return this.elem == null;
};
PairingHeap.prototype.contains = function (h) {
if (this === h)
return true;
for (var i = 0; i < this.subheaps.length; i++) {
if (this.subheaps[i].contains(h))
return true;
}
return false;
};
PairingHeap.prototype.isHeap = function (lessThan) {
var _this = this;
return this.subheaps.every(function (h) { return lessThan(_this.elem, h.elem) && h.isHeap(lessThan); });
};
PairingHeap.prototype.insert = function (obj, lessThan) {
return this.merge(new PairingHeap(obj), lessThan);
};
PairingHeap.prototype.merge = function (heap2, lessThan) {
if (this.empty())
return heap2;
else if (heap2.empty())
return this;
else if (lessThan(this.elem, heap2.elem)) {
this.subheaps.push(heap2);
return this;
}
else {
heap2.subheaps.push(this);
return heap2;
}
};
PairingHeap.prototype.removeMin = function (lessThan) {
if (this.empty())
return null;
else
return this.mergePairs(lessThan);
};
PairingHeap.prototype.mergePairs = function (lessThan) {
if (this.subheaps.length == 0)
return new PairingHeap(null);
else if (this.subheaps.length == 1) {
return this.subheaps[0];
}
else {
var firstPair = this.subheaps.pop().merge(this.subheaps.pop(), lessThan);
var remaining = this.mergePairs(lessThan);
return firstPair.merge(remaining, lessThan);
}
};
PairingHeap.prototype.decreaseKey = function (subheap, newValue, setHeapNode, lessThan) {
var newHeap = subheap.removeMin(lessThan);
//reassign subheap values to preserve tree
subheap.elem = newHeap.elem;
subheap.subheaps = newHeap.subheaps;
if (setHeapNode !== null && newHeap.elem !== null) {
setHeapNode(subheap.elem, subheap);
}
var pairingNode = new PairingHeap(newValue);
if (setHeapNode !== null) {
setHeapNode(newValue, pairingNode);
}
return this.merge(pairingNode, lessThan);
};
return PairingHeap;
})();
/**
* @class PriorityQueue a min priority queue backed by a pairing heap
*/
var PriorityQueue = (function () {
function PriorityQueue(lessThan) {
this.lessThan = lessThan;
}
/**
* @method top
* @return the top element (the min element as defined by lessThan)
*/
PriorityQueue.prototype.top = function () {
if (this.empty()) {
return null;
}
return this.root.elem;
};
/**
* @method push
* put things on the heap
*/
PriorityQueue.prototype.push = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
var pairingNode;
for (var i = 0, arg; arg = args[i]; ++i) {
pairingNode = new PairingHeap(arg);
this.root = this.empty() ?
pairingNode : this.root.merge(pairingNode, this.lessThan);
}
return pairingNode;
};
/**
* @method empty
* @return true if no more elements in queue
*/
PriorityQueue.prototype.empty = function () {
return !this.root || !this.root.elem;
};
/**
* @method isHeap check heap condition (for testing)
* @return true if queue is in valid state
*/
PriorityQueue.prototype.isHeap = function () {
return this.root.isHeap(this.lessThan);
};
/**
* @method forEach apply f to each element of the queue
* @param f function to apply
*/
PriorityQueue.prototype.forEach = function (f) {
this.root.forEach(f);
};
/**
* @method pop remove and return the min element from the queue
*/
PriorityQueue.prototype.pop = function () {
if (this.empty()) {
return null;
}
var obj = this.root.min();
this.root = this.root.removeMin(this.lessThan);
return obj;
};
/**
* @method reduceKey reduce the key value of the specified heap node
*/
PriorityQueue.prototype.reduceKey = function (heapNode, newKey, setHeapNode) {
if (setHeapNode === void 0) { setHeapNode = null; }
this.root = this.root.decreaseKey(heapNode, newKey, setHeapNode, this.lessThan);
};
PriorityQueue.prototype.toString = function (selector) {
return this.root.toString(selector);
};
/**
* @method count
* @return number of elements in queue
*/
PriorityQueue.prototype.count = function () {
return this.root.count();
};
return PriorityQueue;
})();
///<reference path="pqueue.ts"/>
/**
* @module shortestpaths
*/
var cola;
(function (cola) {
var shortestpaths;
(function (shortestpaths) {
var Neighbour = (function () {
function Neighbour(id, distance) {
this.id = id;
this.distance = distance;
}
return Neighbour;
})();
var Node = (function () {
function Node(id) {
this.id = id;
this.neighbours = [];
}
return Node;
})();
var QueueEntry = (function () {
function QueueEntry(node, prev, d) {
this.node = node;
this.prev = prev;
this.d = d;
}
return QueueEntry;
})();
/**
* calculates all-pairs shortest paths or shortest paths from a single node
* @class Calculator
* @constructor
* @param n {number} number of nodes
* @param es {Edge[]} array of edges
*/
var Calculator = (function () {
function Calculator(n, es, getSourceIndex, getTargetIndex, getLength) {
this.n = n;
this.es = es;
this.neighbours = new Array(this.n);
var i = this.n;
while (i--)
this.neighbours[i] = new Node(i);
i = this.es.length;
while (i--) {
var e = this.es[i];
var u = getSourceIndex(e), v = getTargetIndex(e);
var d = getLength(e);
this.neighbours[u].neighbours.push(new Neighbour(v, d));
this.neighbours[v].neighbours.push(new Neighbour(u, d));
}
}
/**
* compute shortest paths for graph over n nodes with edges an array of source/target pairs
* edges may optionally have a length attribute. 1 is the default.
* Uses Johnson's algorithm.
*
* @method DistanceMatrix
* @return the distance matrix
*/
Calculator.prototype.DistanceMatrix = function () {
var D = new Array(this.n);
for (var i = 0; i < this.n; ++i) {
D[i] = this.dijkstraNeighbours(i);
}
return D;
};
/**
* get shortest paths from a specified start node
* @method DistancesFromNode
* @param start node index
* @return array of path lengths
*/
Calculator.prototype.DistancesFromNode = function (start) {
return this.dijkstraNeighbours(start);
};
Calculator.prototype.PathFromNodeToNode = function (start, end) {
return this.dijkstraNeighbours(start, end);
};
// find shortest path from start to end, with the opportunity at
// each edge traversal to compute a custom cost based on the
// previous edge. For example, to penalise bends.
Calculator.prototype.PathFromNodeToNodeWithPrevCost = function (start, end, prevCost) {
var q = new PriorityQueue(function (a, b) { return a.d <= b.d; }), u = this.neighbours[start], qu = new QueueEntry(u, null, 0), visitedFrom = {};
q.push(qu);
while (!q.empty()) {
qu = q.pop();
u = qu.node;
if (u.id === end) {
break;
}
var i = u.neighbours.length;
while (i--) {
var neighbour = u.neighbours[i], v = this.neighbours[neighbour.id];
// don't double back
if (qu.prev && v.id === qu.prev.node.id)
continue;
// don't retraverse an edge if it has already been explored
// from a lower cost route
var viduid = v.id + ',' + u.id;
if (viduid in visitedFrom && visitedFrom[viduid] <= qu.d)
continue;
var cc = qu.prev ? prevCost(qu.prev.node.id, u.id, v.id) : 0, t = qu.d + neighbour.distance + cc;
// store cost of this traversal
visitedFrom[viduid] = t;
q.push(new QueueEntry(v, qu, t));
}
}
var path = [];
while (qu.prev) {
qu = qu.prev;
path.push(qu.node.id);
}
return path;
};
Calculator.prototype.dijkstraNeighbours = function (start, dest) {
if (dest === void 0) { dest = -1; }
var q = new PriorityQueue(function (a, b) { return a.d <= b.d; }), i = this.neighbours.length, d = new Array(i);
while (i--) {
var node = this.neighbours[i];
node.d = i === start ? 0 : Number.POSITIVE_INFINITY;
node.q = q.push(node);
}
while (!q.empty()) {
// console.log(q.toString(function (u) { return u.id + "=" + (u.d === Number.POSITIVE_INFINITY ? "\u221E" : u.d.toFixed(2) )}));
var u = q.pop();
d[u.id] = u.d;
if (u.id === dest) {
var path = [];
var v = u;
while (typeof v.prev !== 'undefined') {
path.push(v.prev.id);
v = v.prev;
}
return path;
}
i = u.neighbours.length;
while (i--) {
var neighbour = u.neighbours[i];
var v = this.neighbours[neighbour.id];
var t = u.d + neighbour.distance;
if (u.d !== Number.MAX_VALUE && v.d > t) {
v.d = t;
v.prev = u;
q.reduceKey(v.q, v, function (e, q) { return e.q = q; });
}
}
}
return d;
};
return Calculator;
})();
shortestpaths.Calculator = Calculator;
})(shortestpaths = cola.shortestpaths || (cola.shortestpaths = {}));
})(cola || (cola = {}));
///<reference path="handledisconnected.ts"/>
///<reference path="geom.ts"/>
///<reference path="descent.ts"/>
///<reference path="powergraph.ts"/>
///<reference path="linklengths.ts"/>
///<reference path="shortestpaths.ts"/>
/**
* @module cola
*/
var cola;
(function (cola) {
/**
* The layout process fires three events:
* - start: layout iterations started
* - tick: fired once per iteration, listen to this to animate
* - end: layout converged, you might like to zoom-to-fit or something at notification of this event
*/
(function (EventType) {
EventType[EventType["start"] = 0] = "start";
EventType[EventType["tick"] = 1] = "tick";
EventType[EventType["end"] = 2] = "end";
})(cola.EventType || (cola.EventType = {}));
var EventType = cola.EventType;
;
/**
* Main interface to cola layout.
* @class Layout
*/
var Layout = (function () {
function Layout() {
var _this = this;
this._canvasSize = [1, 1];
this._linkDistance = 20;
this._defaultNodeSize = 10;
this._linkLengthCalculator = null;
this._linkType = null;
this._avoidOverlaps = false;
this._handleDisconnected = true;
this._running = false;
this._nodes = [];
this._groups = [];
this._variables = [];
this._rootGroup = null;
this._links = [];
this._constraints = [];
this._distanceMatrix = null;
this._descent = null;
this._directedLinkConstraints = null;
this._threshold = 0.01;
this._visibilityGraph = null;
this._groupCompactness = 1e-6;
// sub-class and override this property to replace with a more sophisticated eventing mechanism
this.event = null;
this.linkAccessor = {
getSourceIndex: Layout.getSourceIndex, getTargetIndex: Layout.getTargetIndex, setLength: Layout.setLinkLength,
getType: function (l) { return typeof _this._linkType === "function" ? _this._linkType(l) : 0; }
};
}
// subscribe a listener to an event
// sub-class and override this method to replace with a more sophisticated eventing mechanism
Layout.prototype.on = function (e, listener) {
// override me!
if (!this.event)
this.event = {};
if (typeof e === 'string') {
this.event[EventType[e]] = listener;
}
else {
this.event[e] = listener;
}
return this;
};
// a function that is notified of events like "tick"
// sub-class and override this method to replace with a more sophisticated eventing mechanism
Layout.prototype.trigger = function (e) {
if (this.event && typeof this.event[e.type] !== 'undefined') {
this.event[e.type](e);
}
};
// a function that kicks off the iteration tick loop
// it calls tick() repeatedly until tick returns true (is converged)
// subclass and override it with something fancier (e.g. dispatch tick on a timer)
Layout.prototype.kick = function () {
while (!this.tick())
;
};
/**
* iterate the layout. Returns true when layout converged.
*/
Layout.prototype.tick = function () {
if (this._alpha < this._threshold) {
this._running = false;
this.trigger({ type: EventType.end, alpha: this._alpha = 0, stress: this._lastStress });
return true;
}
var n = this._nodes.length, m = this._links.length;
var o, i;
this._descent.locks.clear();
for (i = 0; i < n; ++i) {
o = this._nodes[i];
if (o.fixed) {
if (typeof o.px === 'undefined' || typeof o.py === 'undefined') {
o.px = o.x;
o.py = o.y;
}
var p = [o.px, o.py];
this._descent.locks.add(i, p);
}
}
var s1 = this._descent.rungeKutta();
//var s1 = descent.reduceStress();
if (s1 === 0) {
this._alpha = 0;
}
else if (typeof this._lastStress !== 'undefined') {
this._alpha = s1; //Math.abs(Math.abs(this._lastStress / s1) - 1);
}
this._lastStress = s1;
this.updateNodePositions();
this.trigger({ type: EventType.tick, alpha: this._alpha, stress: this._lastStress });
return false;
};
// copy positions out of descent instance into each of the nodes' center coords
Layout.prototype.updateNodePositions = function () {
var x = this._descent.x[0], y = this._descent.x[1];
var o, i = this._nodes.length;
while (i--) {
o = this._nodes[i];
o.x = x[i];
o.y = y[i];
}
};
Layout.prototype.nodes = function (v) {
if (!v) {
if (this._nodes.length === 0 && this._links.length > 0) {
// if we have links but no nodes, create the nodes array now with empty objects for the links to point at.
var n = 0;
this._links.forEach(function (l) {
n = Math.max(n, l.source, l.target);
});
this._nodes = new Array(++n);
for (var i = 0; i < n; ++i) {
this._nodes[i] = {};
}
}
return this._nodes;
}
this._nodes = v;
return this;
};
Layout.prototype.groups = function (x) {
var _this = this;
if (!x)
return this._groups;
this._groups = x;
this._rootGroup = {};
this._groups.forEach(function (g) {
if (typeof g.padding === "undefined")
g.padding = 1;
if (typeof g.leaves !== "undefined")
g.leaves.forEach(function (v, i) { (g.leaves[i] = _this._nodes[v]).parent = g; });
if (typeof g.groups !== "undefined")
g.groups.forEach(function (gi, i) { (g.groups[i] = _this._groups[gi]).parent = g; });
});
this._rootGroup.leaves = this._nodes.filter(function (v) { return typeof v.parent === 'undefined'; });
this._rootGroup.groups = this._groups.filter(function (g) { return typeof g.parent === 'undefined'; });
return this;
};
Layout.prototype.powerGraphGroups = function (f) {
var g = cola.powergraph.getGroups(this._nodes, this._links, this.linkAccessor, this._rootGroup);
this.groups(g.groups);
f(g);
return this;
};
Layout.prototype.avoidOverlaps = function (v) {
if (!arguments.length)
return this._avoidOverlaps;
this._avoidOverlaps = v;
return this;
};
Layout.prototype.handleDisconnected = function (v) {
if (!arguments.length)
return this._handleDisconnected;
this._handleDisconnected = v;
return this;
};
/**
* causes constraints to be generated such that directed graphs are laid out either from left-to-right or top-to-bottom.
* a separation constraint is generated in the selected axis for each edge that is not involved in a cycle (part of a strongly connected component)
* @param axis {string} 'x' for left-to-right, 'y' for top-to-bottom
* @param minSeparation {number|link=>number} either a number specifying a minimum spacing required across all links or a function to return the minimum spacing for each link
*/
Layout.prototype.flowLayout = function (axis, minSeparation) {
if (!arguments.length)
axis = 'y';
this._directedLinkConstraints = {
axis: axis,
getMinSeparation: typeof minSeparation === 'number' ? function () { return minSeparation; } : minSeparation
};
return this;
};
Layout.prototype.links = function (x) {
if (!arguments.length)
return this._links;
this._links = x;
return this;
};
Layout.prototype.constraints = function (c) {
if (!arguments.length)
return this._constraints;
this._constraints = c;
return this;
};
Layout.prototype.distanceMatrix = function (d) {
if (!arguments.length)
return this._distanceMatrix;
this._distanceMatrix = d;
return this;
};
Layout.prototype.size = function (x) {
if (!x)
return this._canvasSize;
this._canvasSize = x;
return this;
};
Layout.prototype.defaultNodeSize = function (x) {
if (!x)
return this._defaultNodeSize;
this._defaultNodeSize = x;
return this;
};
Layout.prototype.groupCompactness = function (x) {
if (!x)
return this._groupCompactness;
this._groupCompactness = x;
return this;
};
Layout.prototype.linkDistance = function (x) {
if (!x) {
return this._linkDistance;
}
this._linkDistance = typeof x === "function" ? x : +x;
this._linkLengthCalculator = null;
return this;
};
Layout.prototype.linkType = function (f) {
this._linkType = f;
return this;
};
Layout.prototype.convergenceThreshold = function (x) {
if (!x)
return this._threshold;
this._threshold = typeof x === "function" ? x : +x;
return this;
};
Layout.prototype.alpha = function (x) {
if (!arguments.length)
return this._alpha;
else {
x = +x;
if (this._alpha) {
if (x > 0)
this._alpha = x; // we might keep it hot
else
this._alpha = 0; // or, next tick will dispatch "end"
}
else if (x > 0) {
if (!this._running) {
this._running = true;
this.trigger({ type: EventType.start, alpha: this._alpha = x });
this.kick();
}
}
return this;
}
};
Layout.prototype.getLinkLength = function (link) {
return typeof this._linkDistance === "function" ? +(this._linkDistance(link)) : this._linkDistance;
};
Layout.setLinkLength = function (link, length) {
link.length = length;
};
Layout.prototype.getLinkType = function (link) {
return typeof this._linkType === "function" ? this._linkType(link) : 0;
};
/**
* compute an ideal length for each link based on the graph structure around that link.
* you can use this (for example) to create extra space around hub-nodes in dense graphs.
* In particular this calculation is based on the "symmetric difference" in the neighbour sets of the source and target:
* i.e. if neighbours of source is a and neighbours of target are b then calculation is: sqrt(|a union b| - |a intersection b|)
* Actual computation based on inspection of link structure occurs in start(), so links themselves
* don't have to have been assigned before invoking this function.
* @param {number} [idealLength] the base length for an edge when its source and start have no other common neighbours (e.g. 40)
* @param {number} [w] a multiplier for the effect of the length adjustment (e.g. 0.7)
*/
Layout.prototype.symmetricDiffLinkLengths = function (idealLength, w) {
var _this = this;
if (w === void 0) { w = 1; }
this.linkDistance(function (l) { return idealLength * l.length; });
this._linkLengthCalculator = function () { return cola.symmetricDiffLinkLengths(_this._links, _this.linkAccessor, w); };
return this;
};
/**
* compute an ideal length for each link based on the graph structure around that link.
* you can use this (for example) to create extra space around hub-nodes in dense graphs.
* In particular this calculation is based on the "symmetric difference" in the neighbour sets of the source and target:
* i.e. if neighbours of source is a and neighbours of target are b then calculation is: |a intersection b|/|a union b|
* Actual computation based on inspection of link structure occurs in start(), so links themselves
* don't have to have been assigned before invoking this function.
* @param {number} [idealLength] the base length for an edge when its source and start have no other common neighbours (e.g. 40)
* @param {number} [w] a multiplier for the effect of the length adjustment (e.g. 0.7)
*/
Layout.prototype.jaccardLinkLengths = function (idealLength, w) {
var _this = this;
if (w === void 0) { w = 1; }
this.linkDistance(function (l) { return idealLength * l.length; });
this._linkLengthCalculator = function () { return cola.jaccardLinkLengths(_this._links, _this.linkAccessor, w); };
return this;
};
/**
* start the layout process
* @method start
* @param {number} [initialUnconstrainedIterations=0] unconstrained initial layout iterations
* @param {number} [initialUserConstraintIterations=0] initial layout iterations with user-specified constraints
* @param {number} [initialAllConstraintsIterations=0] initial layout iterations with all constraints including non-overlap
* @param {number} [gridSnapIterations=0] iterations of "grid snap", which pulls nodes towards grid cell centers - grid of size node[0].width - only really makes sense if all nodes have the same width and height
* @param [keepRunning=true] keep iterating asynchronously via the tick method
*/
Layout.prototype.start = function (initialUnconstrainedIterations, initialUserConstraintIterations, initialAllConstraintsIterations, gridSnapIterations, keepRunning) {
var _this = this;
if (initialUnconstrainedIterations === void 0) { initialUnconstrainedIterations = 0; }
if (initialUserConstraintIterations === void 0) { initialUserConstraintIterations = 0; }
if (initialAllConstraintsIterations === void 0) { initialAllConstraintsIterations = 0; }
if (gridSnapIterations === void 0) { gridSnapIterations = 0; }
if (keepRunning === void 0) { keepRunning = true; }
var i, j, n = this.nodes().length, N = n + 2 * this._groups.length, m = this._links.length, w = this._canvasSize[0], h = this._canvasSize[1];
if (this._linkLengthCalculator)
this._linkLengthCalculator();
var x = new Array(N), y = new Array(N);
this._variables = new Array(N);
var makeVariable = function (i, w) { return _this._variables[i] = new cola.vpsc.IndexedVariable(i, w); };
var G = null;
var ao = this._avoidOverlaps;
this._nodes.forEach(function (v, i) {
v.index = i;
if (typeof v.x === 'undefined') {
v.x = w / 2, v.y = h / 2;
}
x[i] = v.x, y[i] = v.y;
});
//should we do this to clearly label groups?
//this._groups.forEach((g, i) => g.groupIndex = i);
var distances;
if (this._distanceMatrix) {
// use the user specified distanceMatrix
distances = this._distanceMatrix;
}
else {
// construct an n X n distance matrix based on shortest paths through graph (with respect to edge.length).
distances = (new cola.shortestpaths.Calculator(N, this._links, Layout.getSourceIndex, Layout.getTargetIndex, function (l) { return _this.getLinkLength(l); })).DistanceMatrix();
// G is a square matrix with G[i][j] = 1 iff there exists an edge between node i and node j
// otherwise 2. (
G = cola.Descent.createSquareMatrix(N, function () { return 2; });
this._links.forEach(function (l) {
if (typeof l.source == "number")
l.source = _this._nodes[l.source];
if (typeof l.target == "number")
l.target = _this._nodes[l.target];
});
this._links.forEach(function (e) {
var u = Layout.getSourceIndex(e), v = Layout.getTargetIndex(e);
G[u][v] = G[v][u] = 1;
});
}
var D = cola.Descent.createSquareMatrix(N, function (i, j) {
return distances[i][j];
});
if (this._rootGroup && typeof this._rootGroup.groups !== 'undefined') {
var i = n;
var addAttraction = function (i, j, strength, idealDistance) {
G[i][j] = G[j][i] = strength;
D[i][j] = D[j][i] = idealDistance;
};
this._groups.forEach(function (g) {
addAttraction(i, i + 1, _this._groupCompactness, 0.1);
// todo: add terms here attracting children of the group to the group dummy nodes
//if (typeof g.leaves !== 'undefined')
// g.leaves.forEach(l => {
// addAttraction(l.index, i, 1e-4, 0.1);
// addAttraction(l.index, i + 1, 1e-4, 0.1);
// });
//if (typeof g.groups !== 'undefined')
// g.groups.forEach(g => {
// var gid = n + g.groupIndex * 2;
// addAttraction(gid, i, 0.1, 0.1);
// addAttraction(gid + 1, i, 0.1, 0.1);
// addAttraction(gid, i + 1, 0.1, 0.1);
// addAttraction(gid + 1, i + 1, 0.1, 0.1);
// });
x[i] = 0, y[i++] = 0;
x[i] = 0, y[i++] = 0;
});
}
else
this._rootGroup = { leaves: this._nodes, groups: [] };
var curConstraints = this._constraints || [];
if (this._directedLinkConstraints) {
this.linkAccessor.getMinSeparation = this._directedLinkConstraints.getMinSeparation;
curConstraints = curConstraints.concat(cola.generateDirectedEdgeConstraints(n, this._links, this._directedLinkConstraints.axis, (this.linkAccessor)));
}
this.avoidOverlaps(false);
this._descent = new cola.Descent([x, y], D);
this._descent.locks.clear();
for (var i = 0; i < n; ++i) {
var o = this._nodes[i];
if (o.fixed) {
o.px = o.x;
o.py = o.y;
var p = [o.x, o.y];
this._descent.locks.add(i, p);
}
}
this._descent.threshold = this._threshold;
// apply initialIterations without user constraints or nonoverlap constraints
this._descent.run(initialUnconstrainedIterations);
// apply initialIterations with user constraints but no nonoverlap constraints
if (curConstraints.length > 0)
this._descent.project = new cola.vpsc.Projection(this._nodes, this._groups, this._rootGroup, curConstraints).projectFunctions();
this._descent.run(initialUserConstraintIterations);
this.separateOverlappingComponents(w, h);
// subsequent iterations will apply all constraints
this.avoidOverlaps(ao);
if (ao) {
this._nodes.forEach(function (v, i) { v.x = x[i], v.y = y[i]; });
this._descent.project = new cola.vpsc.Projection(this._nodes, this._groups, this._rootGroup, curConstraints, true).projectFunctions();
this._nodes.forEach(function (v, i) { x[i] = v.x, y[i] = v.y; });
}
// allow not immediately connected nodes to relax apart (p-stress)
this._descent.G = G;
this._descent.run(initialAllConstraintsIterations);
if (gridSnapIterations) {
this._descent.snapStrength = 1000;
this._descent.snapGridSize = this._nodes[0].width;
this._descent.numGridSnapNodes = n;
this._descent.scaleSnapByMaxH = n != N; // if we have groups then need to scale hessian so grid forces still apply
var G0 = cola.Descent.createSquareMatrix(N, function (i, j) {
if (i >= n || j >= n)
return G[i][j];
return 0;
});
this._descent.G = G0;
this._descent.run(gridSnapIterations);
}
this.updateNodePositions();
this.separateOverlappingComponents(w, h);
return keepRunning ? this.resume() : this;
};
// recalculate nodes position for disconnected graphs
Layout.prototype.separateOverlappingComponents = function (width, height) {
var _this = this;
// recalculate nodes position for disconnected graphs
if (!this._distanceMatrix && this._handleDisconnected) {
var x = this._descent.x[0], y = this._descent.x[1];
this._nodes.forEach(function (v, i) { v.x = x[i], v.y = y[i]; });
var graphs = cola.separateGraphs(this._nodes, this._links);
cola.applyPacking(graphs, width, height, this._defaultNodeSize);
this._nodes.forEach(function (v, i) {
_this._descent.x[0][i] = v.x, _this._descent.x[1][i] = v.y;
if (v.bounds) {
v.bounds.setXCentre(v.x);
v.bounds.setYCentre(v.y);
}
});
}
};
Layout.prototype.resume = function () {
return this.alpha(0.1);
};
Layout.prototype.stop = function () {
return this.alpha(0);
};
/// find a visibility graph over the set of nodes. assumes all nodes have a
/// bounds property (a rectangle) and that no pair of bounds overlaps.
Layout.prototype.prepareEdgeRouting = function (nodeMargin) {
if (nodeMargin === void 0) { nodeMargin = 0; }
this._visibilityGraph = new cola.geom.TangentVisibilityGraph(this._nodes.map(function (v) {
return v.bounds.inflate(-nodeMargin).vertices();
}));
};
/// find a route avoiding node bounds for the given edge.
/// assumes the visibility graph has been created (by prepareEdgeRouting method)
/// and also assumes that nodes have an index property giving their position in the
/// node array. This index property is created by the start() method.
Layout.prototype.routeEdge = function (edge, draw) {
var lineData = [];
//if (d.source.id === 10 && d.target.id === 11) {
// debugger;
//}
var vg2 = new cola.geom.TangentVisibilityGraph(this._visibilityGraph.P, { V: this._visibilityGraph.V, E: this._visibilityGraph.E }), port1 = { x: edge.source.x, y: edge.source.y }, port2 = { x: edge.target.x, y: edge.target.y }, start = vg2.addPoint(port1, edge.source.index), end = vg2.addPoint(port2, edge.target.index);
vg2.addEdgeIfVisible(port1, port2, edge.source.index, edge.target.index);
if (typeof draw !== 'undefined') {
draw(vg2);
}
var sourceInd = function (e) { return e.source.index; }, targetInd = function (e) { return e.target.index; }, length = function (e) { return e.length(); }, spCalc = new cola.shortestpaths.Calculator(vg2.V.length, vg2.E, sourceInd, targetInd, length), shortestPath = spCalc.PathFromNodeToNode(start.id, end.id);
if (shortestPath.length === 1 || shortestPath.length === vg2.V.length) {
cola.vpsc.makeEdgeBetween(edge, edge.source.innerBounds, edge.target.innerBounds, 5);
lineData = [{ x: edge.sourceIntersection.x, y: edge.sourceIntersection.y }, { x: edge.arrowStart.x, y: edge.arrowStart.y }];
}
else {
var n = shortestPath.length - 2, p = vg2.V[shortestPath[n]].p, q = vg2.V[shortestPath[0]].p, lineData = [edge.source.innerBounds.rayIntersection(p.x, p.y)];
for (var i = n; i >= 0; --i)
lineData.push(vg2.V[shortestPath[i]].p);
lineData.push(cola.vpsc.makeEdgeTo(q, edge.target.innerBounds, 5));
}
//lineData.forEach((v, i) => {
// if (i > 0) {
// var u = lineData[i - 1];
// this._nodes.forEach(function (node) {
// if (node.id === getSourceIndex(d) || node.id === getTargetIndex(d)) return;
// var ints = node.innerBounds.lineIntersections(u.x, u.y, v.x, v.y);
// if (ints.length > 0) {
// debugger;
// }
// })
// }
//})
return lineData;
};
//The link source and target may be just a node index, or they may be references to nodes themselves.
Layout.getSourceIndex = function (e) {
return typeof e.source === 'number' ? e.source : e.source.index;
};
//The link source and target may be just a node index, or they may be references to nodes themselves.
Layout.getTargetIndex = function (e) {
return typeof e.target === 'number' ? e.target : e.target.index;
};
// Get a string ID for a given link.
Layout.linkId = function (e) {
return Layout.getSourceIndex(e) + "-" + Layout.getTargetIndex(e);
};
// The fixed property has three bits:
// Bit 1 can be set externally (e.g., d.fixed = true) and show persist.
// Bit 2 stores the dragging state, from mousedown to mouseup.
// Bit 3 stores the hover state, from mouseover to mouseout.
// Dragend is a special case: it also clears the hover state.
Layout.dragStart = function (d) {
d.fixed |= 2; // set bit 2
d.px = d.x, d.py = d.y; // set velocity to zero
};
Layout.dragEnd = function (d) {
d.fixed &= ~6; // unset bits 2 and 3
//d.fixed = 0;
};
Layout.mouseOver = function (d) {
d.fixed |= 4; // set bit 3
d.px = d.x, d.py = d.y; // set velocity to zero
};
Layout.mouseOut = function (d) {
d.fixed &= ~4; // unset bit 3
};
return Layout;
})();
cola.Layout = Layout;
})(cola || (cola = {}));
///<reference path="../extern/d3.d.ts"/>
///<reference path="layout.ts"/>
var cola;
(function (cola) {
var D3StyleLayoutAdaptor = (function (_super) {
__extends(D3StyleLayoutAdaptor, _super);
function D3StyleLayoutAdaptor() {
_super.call(this);
this.event = d3.dispatch(cola.EventType[cola.EventType.start], cola.EventType[cola.EventType.tick], cola.EventType[cola.EventType.end]);
// bit of trickyness remapping 'this' so we can reference it in the function body.
var d3layout = this;
var drag;
this.drag = function () {
if (!drag) {
var drag = d3.behavior.drag()
.origin(function (d) { return d; })
.on("dragstart.d3adaptor", cola.Layout.dragStart)
.on("drag.d3adaptor", function (d) {
d.px = d3.event.x, d.py = d3.event.y;
d3layout.resume(); // restart annealing
})
.on("dragend.d3adaptor", cola.Layout.dragEnd);
}
if (!arguments.length)
return drag;
// this is the context of the function, i.e. the d3 selection
this //.on("mouseover.adaptor", colaMouseover)
.call(drag);
};
}
D3StyleLayoutAdaptor.prototype.trigger = function (e) {
var d3event = { type: cola.EventType[e.type], alpha: e.alpha, stress: e.stress };
this.event[d3event.type](d3event); // via d3 dispatcher, e.g. event.start(e);
};
// iterate layout using a d3.timer, which queues calls to tick repeatedly until tick returns true
D3StyleLayoutAdaptor.prototype.kick = function () {
var _this = this;
d3.timer(function () { return _super.prototype.tick.call(_this); });
};
// a function for binding to events on the adapter
D3StyleLayoutAdaptor.prototype.on = function (eventType, listener) {
if (typeof eventType === 'string') {
this.event.on(eventType, listener);
}
else {
this.event.on(cola.EventType[eventType], listener);
}
return this;
};
return D3StyleLayoutAdaptor;
})(cola.Layout);
cola.D3StyleLayoutAdaptor = D3StyleLayoutAdaptor;
/**
* provides an interface for use with d3:
* - uses the d3 event system to dispatch layout events such as:
* o "start" (start layout process)
* o "tick" (after each layout iteration)
* o "end" (layout converged and complete).
* - uses the d3 timer to queue layout iterations.
* - sets up d3.behavior.drag to drag nodes
* o use `node.call(<the returned instance of Layout>.drag)` to make nodes draggable
* returns an instance of the cola.Layout itself with which the user
* can interact directly.
*/
function d3adaptor() {
return new D3StyleLayoutAdaptor();
}
cola.d3adaptor = d3adaptor;
})(cola || (cola = {}));
/// <reference path="rectangle.ts"/>
/// <reference path="shortestpaths.ts"/>
/// <reference path="geom.ts"/>
/// <reference path="vpsc.ts"/>
var cola;
(function (cola) {
var NodeWrapper = (function () {
function NodeWrapper(id, rect, children) {
this.id = id;
this.rect = rect;
this.children = children;
this.leaf = typeof children === 'undefined' || children.length === 0;
}
return NodeWrapper;
})();
cola.NodeWrapper = NodeWrapper;
var Vert = (function () {
function Vert(id, x, y, node, line) {
if (node === void 0) { node = null; }
if (line === void 0) { line = null; }
this.id = id;
this.x = x;
this.y = y;
this.node = node;
this.line = line;
}
return Vert;
})();
cola.Vert = Vert;
var LongestCommonSubsequence = (function () {
function LongestCommonSubsequence(s, t) {
this.s = s;
this.t = t;
var mf = LongestCommonSubsequence.findMatch(s, t);
var tr = t.slice(0).reverse();
var mr = LongestCommonSubsequence.findMatch(s, tr);
if (mf.length >= mr.length) {
this.length = mf.length;
this.si = mf.si;
this.ti = mf.ti;
this.reversed = false;
}
else {
this.length = mr.length;
this.si = mr.si;
this.ti = t.length - mr.ti - mr.length;
this.reversed = true;
}
}
LongestCommonSubsequence.findMatch = function (s, t) {
var m = s.length;
var n = t.length;
var match = { length: 0, si: -1, ti: -1 };
var l = new Array(m);
for (var i = 0; i < m; i++) {
l[i] = new Array(n);
for (var j = 0; j < n; j++)
if (s[i] === t[j]) {
var v = l[i][j] = (i === 0 || j === 0) ? 1 : l[i - 1][j - 1] + 1;
if (v > match.length) {
match.length = v;
match.si = i - v + 1;
match.ti = j - v + 1;
}
;
}
else
l[i][j] = 0;
}
return match;
};
LongestCommonSubsequence.prototype.getSequence = function () {
return this.length >= 0 ? this.s.slice(this.si, this.si + this.length) : [];
};
return LongestCommonSubsequence;
})();
cola.LongestCommonSubsequence = LongestCommonSubsequence;
var GridRouter = (function () {
function GridRouter(originalnodes, accessor, groupPadding) {
var _this = this;
if (groupPadding === void 0) { groupPadding = 12; }
this.originalnodes = originalnodes;
this.groupPadding = groupPadding;
this.leaves = null;
this.nodes = originalnodes.map(function (v, i) { return new NodeWrapper(i, accessor.getBounds(v), accessor.getChildren(v)); });
this.leaves = this.nodes.filter(function (v) { return v.leaf; });
this.groups = this.nodes.filter(function (g) { return !g.leaf; });
this.cols = this.getGridLines('x');
this.rows = this.getGridLines('y');
// create parents for each node or group that is a member of another's children
this.groups.forEach(function (v) {
return v.children.forEach(function (c) { return _this.nodes[c].parent = v; });
});
// root claims the remaining orphans
this.root = { children: [] };
this.nodes.forEach(function (v) {
if (typeof v.parent === 'undefined') {
v.parent = _this.root;
_this.root.children.push(v.id);
}
// each node will have grid vertices associated with it,
// some inside the node and some on the boundary
// leaf nodes will have exactly one internal node at the center
// and four boundary nodes
// groups will have potentially many of each
v.ports = [];
});
// nodes ordered by their position in the group hierarchy
this.backToFront = this.nodes.slice(0);
this.backToFront.sort(function (x, y) { return _this.getDepth(x) - _this.getDepth(y); });
// compute boundary rectangles for each group
// has to be done from front to back, i.e. inside groups to outside groups
// such that each can be made large enough to enclose its interior
var frontToBackGroups = this.backToFront.slice(0).reverse().filter(function (g) { return !g.leaf; });
frontToBackGroups.forEach(function (v) {
var r = cola.vpsc.Rectangle.empty();
v.children.forEach(function (c) { return r = r.union(_this.nodes[c].rect); });
v.rect = r.inflate(_this.groupPadding);
});
var colMids = this.midPoints(this.cols.map(function (r) { return r.pos; }));
var rowMids = this.midPoints(this.rows.map(function (r) { return r.pos; }));
// setup extents of lines
var rowx = colMids[0], rowX = colMids[colMids.length - 1];
var coly = rowMids[0], colY = rowMids[rowMids.length - 1];
// horizontal lines
var hlines = this.rows.map(function (r) { return { x1: rowx, x2: rowX, y1: r.pos, y2: r.pos }; })
.concat(rowMids.map(function (m) { return { x1: rowx, x2: rowX, y1: m, y2: m }; }));
// vertical lines
var vlines = this.cols.map(function (c) { return { x1: c.pos, x2: c.pos, y1: coly, y2: colY }; })
.concat(colMids.map(function (m) { return { x1: m, x2: m, y1: coly, y2: colY }; }));
// the full set of lines
var lines = hlines.concat(vlines);
// we record the vertices associated with each line
lines.forEach(function (l) { return l.verts = []; });
// the routing graph
this.verts = [];
this.edges = [];
// create vertices at the crossings of horizontal and vertical grid-lines
hlines.forEach(function (h) {
return vlines.forEach(function (v) {
var p = new Vert(_this.verts.length, v.x1, h.y1);
h.verts.push(p);
v.verts.push(p);
_this.verts.push(p);
// assign vertices to the nodes immediately under them
var i = _this.backToFront.length;
while (i-- > 0) {
var node = _this.backToFront[i], r = node.rect;
var dx = Math.abs(p.x - r.cx()), dy = Math.abs(p.y - r.cy());
if (dx < r.width() / 2 && dy < r.height() / 2) {
p.node = node;
break;
}
}
});
});
lines.forEach(function (l, li) {
// create vertices at the intersections of nodes and lines
_this.nodes.forEach(function (v, i) {
v.rect.lineIntersections(l.x1, l.y1, l.x2, l.y2).forEach(function (intersect, j) {
//console.log(li+','+i+','+j+':'+intersect.x + ',' + intersect.y);
var p = new Vert(_this.verts.length, intersect.x, intersect.y, v, l);
_this.verts.push(p);
l.verts.push(p);
v.ports.push(p);
});
});
// split lines into edges joining vertices
var isHoriz = Math.abs(l.y1 - l.y2) < 0.1;
var delta = function (a, b) { return isHoriz ? b.x - a.x : b.y - a.y; };
l.verts.sort(delta);
for (var i = 1; i < l.verts.length; i++) {
var u = l.verts[i - 1], v = l.verts[i];
if (u.node && u.node === v.node && u.node.leaf)
continue;
_this.edges.push({ source: u.id, target: v.id, length: Math.abs(delta(u, v)) });
}
});
}
GridRouter.prototype.avg = function (a) { return a.reduce(function (x, y) { return x + y; }) / a.length; };
// in the given axis, find sets of leaves overlapping in that axis
// center of each GridLine is average of all nodes in column
GridRouter.prototype.getGridLines = function (axis) {
var columns = [];
var ls = this.leaves.slice(0, this.leaves.length);
while (ls.length > 0) {
// find a column of all leaves overlapping in axis with the first leaf
var overlapping = ls.filter(function (v) { return v.rect['overlap' + axis.toUpperCase()](ls[0].rect); });
var col = {
nodes: overlapping,
pos: this.avg(overlapping.map(function (v) { return v.rect['c' + axis](); }))
};
columns.push(col);
col.nodes.forEach(function (v) { return ls.splice(ls.indexOf(v), 1); });
}
columns.sort(function (a, b) { return a.pos - b.pos; });
return columns;
};
// get the depth of the given node in the group hierarchy
GridRouter.prototype.getDepth = function (v) {
var depth = 0;
while (v.parent !== this.root) {
depth++;
v = v.parent;
}
return depth;
};
// medial axes between node centres and also boundary lines for the grid
GridRouter.prototype.midPoints = function (a) {
var gap = a[1] - a[0];
var mids = [a[0] - gap / 2];
for (var i = 1; i < a.length; i++) {
mids.push((a[i] + a[i - 1]) / 2);
}
mids.push(a[a.length - 1] + gap / 2);
return mids;
};
// find path from v to root including both v and root
GridRouter.prototype.findLineage = function (v) {
var lineage = [v];
do {
v = v.parent;
lineage.push(v);
} while (v !== this.root);
return lineage.reverse();
};
// find path connecting a and b through their lowest common ancestor
GridRouter.prototype.findAncestorPathBetween = function (a, b) {
var aa = this.findLineage(a), ba = this.findLineage(b), i = 0;
while (aa[i] === ba[i])
i++;
// i-1 to include common ancestor only once (as first element)
return { commonAncestor: aa[i - 1], lineages: aa.slice(i).concat(ba.slice(i)) };
};
// when finding a path between two nodes a and b, siblings of a and b on the
// paths from a and b to their least common ancestor are obstacles
GridRouter.prototype.siblingObstacles = function (a, b) {
var _this = this;
var path = this.findAncestorPathBetween(a, b);
var lineageLookup = {};
path.lineages.forEach(function (v) { return lineageLookup[v.id] = {}; });
var obstacles = path.commonAncestor.children.filter(function (v) { return !(v in lineageLookup); });
path.lineages
.filter(function (v) { return v.parent !== path.commonAncestor; })
.forEach(function (v) { return obstacles = obstacles.concat(v.parent.children.filter(function (c) { return c !== v.id; })); });
return obstacles.map(function (v) { return _this.nodes[v]; });
};
// for the given routes, extract all the segments orthogonal to the axis x
// and return all them grouped by x position
GridRouter.getSegmentSets = function (routes, x, y) {
// vsegments is a list of vertical segments sorted by x position
var vsegments = [];
for (var ei = 0; ei < routes.length; ei++) {
var route = routes[ei];
for (var si = 0; si < route.length; si++) {
var s = route[si];
s.edgeid = ei;
s.i = si;
var sdx = s[1][x] - s[0][x];
if (Math.abs(sdx) < 0.1) {
vsegments.push(s);
}
}
}
vsegments.sort(function (a, b) { return a[0][x] - b[0][x]; });
// vsegmentsets is a set of sets of segments grouped by x position
var vsegmentsets = [];
var segmentset = null;
for (var i = 0; i < vsegments.length; i++) {
var s = vsegments[i];
if (!segmentset || Math.abs(s[0][x] - segmentset.pos) > 0.1) {
segmentset = { pos: s[0][x], segments: [] };
vsegmentsets.push(segmentset);
}
segmentset.segments.push(s);
}
return vsegmentsets;
};
// for all segments in this bundle create a vpsc problem such that
// each segment's x position is a variable and separation constraints
// are given by the partial order over the edges to which the segments belong
// for each pair s1,s2 of segments in the open set:
// e1 = edge of s1, e2 = edge of s2
// if leftOf(e1,e2) create constraint s1.x + gap <= s2.x
// else if leftOf(e2,e1) create cons. s2.x + gap <= s1.x
GridRouter.nudgeSegs = function (x, y, routes, segments, leftOf, gap) {
var n = segments.length;
if (n <= 1)
return;
var vs = segments.map(function (s) { return new cola.vpsc.Variable(s[0][x]); });
var cs = [];
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
if (i === j)
continue;
var s1 = segments[i], s2 = segments[j], e1 = s1.edgeid, e2 = s2.edgeid, lind = -1, rind = -1;
// in page coordinates (not cartesian) the notion of 'leftof' is flipped in the horizontal axis from the vertical axis
// that is, when nudging vertical segments, if they increase in the y(conj) direction the segment belonging to the
// 'left' edge actually needs to be nudged to the right
// when nudging horizontal segments, if the segments increase in the x direction
// then the 'left' segment needs to go higher, i.e. to have y pos less than that of the right
if (x == 'x') {
if (leftOf(e1, e2)) {
//console.log('s1: ' + s1[0][x] + ',' + s1[0][y] + '-' + s1[1][x] + ',' + s1[1][y]);
if (s1[0][y] < s1[1][y]) {
lind = j, rind = i;
}
else {
lind = i, rind = j;
}
}
}
else {
if (leftOf(e1, e2)) {
if (s1[0][y] < s1[1][y]) {
lind = i, rind = j;
}
else {
lind = j, rind = i;
}
}
}
if (lind >= 0) {
//console.log(x+' constraint: ' + lind + '<' + rind);
cs.push(new cola.vpsc.Constraint(vs[lind], vs[rind], gap));
}
}
}
var solver = new cola.vpsc.Solver(vs, cs);
solver.solve();
vs.forEach(function (v, i) {
var s = segments[i];
var pos = v.position();
s[0][x] = s[1][x] = pos;
var route = routes[s.edgeid];
if (s.i > 0)
route[s.i - 1][1][x] = pos;
if (s.i < route.length - 1)
route[s.i + 1][0][x] = pos;
});
};
GridRouter.nudgeSegments = function (routes, x, y, leftOf, gap) {
var vsegmentsets = GridRouter.getSegmentSets(routes, x, y);
// scan the grouped (by x) segment sets to find co-linear bundles
for (var i = 0; i < vsegmentsets.length; i++) {
var ss = vsegmentsets[i];
var events = [];
for (var j = 0; j < ss.segments.length; j++) {
var s = ss.segments[j];
events.push({ type: 0, s: s, pos: Math.min(s[0][y], s[1][y]) });
events.push({ type: 1, s: s, pos: Math.max(s[0][y], s[1][y]) });
}
events.sort(function (a, b) { return a.pos - b.pos + a.type - b.type; });
var open = [];
var openCount = 0;
events.forEach(function (e) {
if (e.type === 0) {
open.push(e.s);
openCount++;
}
else {
openCount--;
}
if (openCount == 0) {
GridRouter.nudgeSegs(x, y, routes, open, leftOf, gap);
open = [];
}
});
}
};
// obtain routes for the specified edges, nicely nudged apart
// warning: edge paths may be reversed such that common paths are ordered consistently within bundles!
// @param edges list of edges
// @param nudgeGap how much to space parallel edge segements
// @param source function to retrieve the index of the source node for a given edge
// @param target function to retrieve the index of the target node for a given edge
// @returns an array giving, for each edge, an array of segments, each segment a pair of points in an array
GridRouter.prototype.routeEdges = function (edges, nudgeGap, source, target) {
var _this = this;
var routePaths = edges.map(function (e) { return _this.route(source(e), target(e)); });
var order = cola.GridRouter.orderEdges(routePaths);
var routes = routePaths.map(function (e) { return cola.GridRouter.makeSegments(e); });
cola.GridRouter.nudgeSegments(routes, 'x', 'y', order, nudgeGap);
cola.GridRouter.nudgeSegments(routes, 'y', 'x', order, nudgeGap);
cola.GridRouter.unreverseEdges(routes, routePaths);
return routes;
};
// path may have been reversed by the subsequence processing in orderEdges
// so now we need to restore the original order
GridRouter.unreverseEdges = function (routes, routePaths) {
routes.forEach(function (segments, i) {
var path = routePaths[i];
if (path.reversed) {
segments.reverse(); // reverse order of segments
segments.forEach(function (segment) {
segment.reverse(); // reverse each segment
});
}
});
};
GridRouter.angleBetween2Lines = function (line1, line2) {
var angle1 = Math.atan2(line1[0].y - line1[1].y, line1[0].x - line1[1].x);
var angle2 = Math.atan2(line2[0].y - line2[1].y, line2[0].x - line2[1].x);
var diff = angle1 - angle2;
if (diff > Math.PI || diff < -Math.PI) {
diff = angle2 - angle1;
}
return diff;
};
// does the path a-b-c describe a left turn?
GridRouter.isLeft = function (a, b, c) {
return ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) <= 0;
};
// for the given list of ordered pairs, returns a function that (efficiently) looks-up a specific pair to
// see if it exists in the list
GridRouter.getOrder = function (pairs) {
var outgoing = {};
for (var i = 0; i < pairs.length; i++) {
var p = pairs[i];
if (typeof outgoing[p.l] === 'undefined')
outgoing[p.l] = {};
outgoing[p.l][p.r] = true;
}
return function (l, r) { return typeof outgoing[l] !== 'undefined' && outgoing[l][r]; };
};
// returns an ordering (a lookup function) that determines the correct order to nudge the
// edge paths apart to minimize crossings
GridRouter.orderEdges = function (edges) {
var edgeOrder = [];
for (var i = 0; i < edges.length - 1; i++) {
for (var j = i + 1; j < edges.length; j++) {
var e = edges[i], f = edges[j], lcs = new cola.LongestCommonSubsequence(e, f);
var u, vi, vj;
if (lcs.length === 0)
continue; // no common subpath
if (lcs.reversed) {
// if we found a common subpath but one of the edges runs the wrong way,
// then reverse f.
f.reverse();
f.reversed = true;
lcs = new cola.LongestCommonSubsequence(e, f);
}
if ((lcs.si <= 0 || lcs.ti <= 0) &&
(lcs.si + lcs.length >= e.length || lcs.ti + lcs.length >= f.length)) {
// the paths do not diverge, so make an arbitrary ordering decision
edgeOrder.push({ l: i, r: j });
continue;
}
if (lcs.si + lcs.length >= e.length || lcs.ti + lcs.length >= f.length) {
// if the common subsequence of the
// two edges being considered goes all the way to the
// end of one (or both) of the lines then we have to
// base our ordering decision on the other end of the
// common subsequence
u = e[lcs.si + 1];
vj = e[lcs.si - 1];
vi = f[lcs.ti - 1];
}
else {
u = e[lcs.si + lcs.length - 2];
vi = e[lcs.si + lcs.length];
vj = f[lcs.ti + lcs.length];
}
if (GridRouter.isLeft(u, vi, vj)) {
edgeOrder.push({ l: j, r: i });
}
else {
edgeOrder.push({ l: i, r: j });
}
}
}
//edgeOrder.forEach(function (e) { console.log('l:' + e.l + ',r:' + e.r) });
return cola.GridRouter.getOrder(edgeOrder);
};
// for an orthogonal path described by a sequence of points, create a list of segments
// if consecutive segments would make a straight line they are merged into a single segment
// segments are over cloned points, not the original vertices
GridRouter.makeSegments = function (path) {
function copyPoint(p) {
return { x: p.x, y: p.y };
}
var isStraight = function (a, b, c) { return Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) < 0.001; };
var segments = [];
var a = copyPoint(path[0]);
for (var i = 1; i < path.length; i++) {
var b = copyPoint(path[i]), c = i < path.length - 1 ? path[i + 1] : null;
if (!c || !isStraight(a, b, c)) {
segments.push([a, b]);
a = b;
}
}
return segments;
};
// find a route between node s and node t
// returns an array of indices to verts
GridRouter.prototype.route = function (s, t) {
var _this = this;
var source = this.nodes[s], target = this.nodes[t];
this.obstacles = this.siblingObstacles(source, target);
var obstacleLookup = {};
this.obstacles.forEach(function (o) { return obstacleLookup[o.id] = o; });
this.passableEdges = this.edges.filter(function (e) {
var u = _this.verts[e.source], v = _this.verts[e.target];
return !(u.node && u.node.id in obstacleLookup
|| v.node && v.node.id in obstacleLookup);
});
// add dummy segments linking ports inside source and target
for (var i = 1; i < source.ports.length; i++) {
var u = source.ports[0].id;
var v = source.ports[i].id;
this.passableEdges.push({
source: u,
target: v,
length: 0
});
}
for (var i = 1; i < target.ports.length; i++) {
var u = target.ports[0].id;
var v = target.ports[i].id;
this.passableEdges.push({
source: u,
target: v,
length: 0
});
}
var getSource = function (e) { return e.source; }, getTarget = function (e) { return e.target; }, getLength = function (e) { return e.length; };
var shortestPathCalculator = new cola.shortestpaths.Calculator(this.verts.length, this.passableEdges, getSource, getTarget, getLength);
var bendPenalty = function (u, v, w) {
var a = _this.verts[u], b = _this.verts[v], c = _this.verts[w];
var dx = Math.abs(c.x - a.x), dy = Math.abs(c.y - a.y);
// don't count bends from internal node edges
if (a.node === source && a.node === b.node || b.node === target && b.node === c.node)
return 0;
return dx > 1 && dy > 1 ? 1000 : 0;
};
// get shortest path
var shortestPath = shortestPathCalculator.PathFromNodeToNodeWithPrevCost(source.ports[0].id, target.ports[0].id, bendPenalty);
// shortest path is reversed and does not include the target port
var pathPoints = shortestPath.reverse().map(function (vi) { return _this.verts[vi]; });
pathPoints.push(this.nodes[target.id].ports[0]);
// filter out any extra end points that are inside the source or target (i.e. the dummy segments above)
return pathPoints.filter(function (v, i) {
return !(i < pathPoints.length - 1 && pathPoints[i + 1].node === source && v.node === source
|| i > 0 && v.node === target && pathPoints[i - 1].node === target);
});
};
GridRouter.getRoutePath = function (route, cornerradius, arrowwidth, arrowheight) {
var result = {
routepath: 'M ' + route[0][0].x + ' ' + route[0][0].y + ' ',
arrowpath: ''
};
if (route.length > 1) {
for (var i = 0; i < route.length; i++) {
var li = route[i];
var x = li[1].x, y = li[1].y;
var dx = x - li[0].x;
var dy = y - li[0].y;
if (i < route.length - 1) {
if (Math.abs(dx) > 0) {
x -= dx / Math.abs(dx) * cornerradius;
}
else {
y -= dy / Math.abs(dy) * cornerradius;
}
result.routepath += 'L ' + x + ' ' + y + ' ';
var l = route[i + 1];
var x0 = l[0].x, y0 = l[0].y;
var x1 = l[1].x;
var y1 = l[1].y;
dx = x1 - x0;
dy = y1 - y0;
var angle = GridRouter.angleBetween2Lines(li, l) < 0 ? 1 : 0;
//console.log(cola.GridRouter.angleBetween2Lines(li, l))
var x2, y2;
if (Math.abs(dx) > 0) {
x2 = x0 + dx / Math.abs(dx) * cornerradius;
y2 = y0;
}
else {
x2 = x0;
y2 = y0 + dy / Math.abs(dy) * cornerradius;
}
var cx = Math.abs(x2 - x);
var cy = Math.abs(y2 - y);
result.routepath += 'A ' + cx + ' ' + cy + ' 0 0 ' + angle + ' ' + x2 + ' ' + y2 + ' ';
}
else {
var arrowtip = [x, y];
var arrowcorner1, arrowcorner2;
if (Math.abs(dx) > 0) {
x -= dx / Math.abs(dx) * arrowheight;
arrowcorner1 = [x, y + arrowwidth];
arrowcorner2 = [x, y - arrowwidth];
}
else {
y -= dy / Math.abs(dy) * arrowheight;
arrowcorner1 = [x + arrowwidth, y];
arrowcorner2 = [x - arrowwidth, y];
}
result.routepath += 'L ' + x + ' ' + y + ' ';
if (arrowheight > 0) {
result.arrowpath = 'M ' + arrowtip[0] + ' ' + arrowtip[1] + ' L ' + arrowcorner1[0] + ' ' + arrowcorner1[1]
+ ' L ' + arrowcorner2[0] + ' ' + arrowcorner2[1];
}
}
}
}
else {
var li = route[0];
var x = li[1].x, y = li[1].y;
var dx = x - li[0].x;
var dy = y - li[0].y;
var arrowtip = [x, y];
var arrowcorner1, arrowcorner2;
if (Math.abs(dx) > 0) {
x -= dx / Math.abs(dx) * arrowheight;
arrowcorner1 = [x, y + arrowwidth];
arrowcorner2 = [x, y - arrowwidth];
}
else {
y -= dy / Math.abs(dy) * arrowheight;
arrowcorner1 = [x + arrowwidth, y];
arrowcorner2 = [x - arrowwidth, y];
}
result.routepath += 'L ' + x + ' ' + y + ' ';
if (arrowheight > 0) {
result.arrowpath = 'M ' + arrowtip[0] + ' ' + arrowtip[1] + ' L ' + arrowcorner1[0] + ' ' + arrowcorner1[1]
+ ' L ' + arrowcorner2[0] + ' ' + arrowcorner2[1];
}
}
return result;
};
return GridRouter;
})();
cola.GridRouter = GridRouter;
})(cola || (cola = {}));
/**
* Use cola to do a layout in 3D!! Yay.
* Pretty simple for the moment.
*/
var cola;
(function (cola) {
var Link3D = (function () {
function Link3D(source, target) {
this.source = source;
this.target = target;
}
Link3D.prototype.actualLength = function (x) {
var _this = this;
return Math.sqrt(x.reduce(function (c, v) {
var dx = v[_this.target] - v[_this.source];
return c + dx * dx;
}, 0));
};
return Link3D;
})();
cola.Link3D = Link3D;
var Node3D = (function () {
function Node3D(x, y, z) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
if (z === void 0) { z = 0; }
this.x = x;
this.y = y;
this.z = z;
}
return Node3D;
})();
cola.Node3D = Node3D;
var Layout3D = (function () {
function Layout3D(nodes, links, idealLinkLength) {
var _this = this;
if (idealLinkLength === void 0) { idealLinkLength = 1; }
this.nodes = nodes;
this.links = links;
this.idealLinkLength = idealLinkLength;
this.constraints = null;
this.useJaccardLinkLengths = true;
this.result = new Array(Layout3D.k);
for (var i = 0; i < Layout3D.k; ++i) {
this.result[i] = new Array(nodes.length);
}
nodes.forEach(function (v, i) {
for (var _i = 0, _a = Layout3D.dims; _i < _a.length; _i++) {
var dim = _a[_i];
if (typeof v[dim] == 'undefined')
v[dim] = Math.random();
}
_this.result[0][i] = v.x;
_this.result[1][i] = v.y;
_this.result[2][i] = v.z;
});
}
;
Layout3D.prototype.linkLength = function (l) {
return l.actualLength(this.result);
};
Layout3D.prototype.start = function (iterations) {
var _this = this;
if (iterations === void 0) { iterations = 100; }
var n = this.nodes.length;
var linkAccessor = new LinkAccessor();
if (this.useJaccardLinkLengths)
cola.jaccardLinkLengths(this.links, linkAccessor, 1.5);
this.links.forEach(function (e) { return e.length *= _this.idealLinkLength; });
// Create the distance matrix that Cola needs
var distanceMatrix = (new cola.shortestpaths.Calculator(n, this.links, function (e) { return e.source; }, function (e) { return e.target; }, function (e) { return e.length; })).DistanceMatrix();
var D = cola.Descent.createSquareMatrix(n, function (i, j) { return distanceMatrix[i][j]; });
// G is a square matrix with G[i][j] = 1 iff there exists an edge between node i and node j
// otherwise 2.
var G = cola.Descent.createSquareMatrix(n, function () { return 2; });
this.links.forEach(function (_a) {
var source = _a.source, target = _a.target;
return G[source][target] = G[target][source] = 1;
});
this.descent = new cola.Descent(this.result, D);
this.descent.threshold = 1e-3;
this.descent.G = G;
//let constraints = this.links.map(e=> <any>{
// axis: 'y', left: e.source, right: e.target, gap: e.length*1.5
//});
if (this.constraints)
this.descent.project = new cola.vpsc.Projection(this.nodes, null, null, this.constraints).projectFunctions();
for (var i = 0; i < this.nodes.length; i++) {
var v = this.nodes[i];
if (v.fixed) {
this.descent.locks.add(i, [v.x, v.y, v.z]);
}
}
this.descent.run(iterations);
return this;
};
Layout3D.prototype.tick = function () {
this.descent.locks.clear();
for (var i = 0; i < this.nodes.length; i++) {
var v = this.nodes[i];
if (v.fixed) {
this.descent.locks.add(i, [v.x, v.y, v.z]);
}
}
return this.descent.rungeKutta();
};
Layout3D.dims = ['x', 'y', 'z'];
Layout3D.k = Layout3D.dims.length;
return Layout3D;
})();
cola.Layout3D = Layout3D;
var LinkAccessor = (function () {
function LinkAccessor() {
}
LinkAccessor.prototype.getSourceIndex = function (e) { return e.source; };
LinkAccessor.prototype.getTargetIndex = function (e) { return e.target; };
LinkAccessor.prototype.getLength = function (e) { return e.length; };
LinkAccessor.prototype.setLength = function (e, l) { e.length = l; };
return LinkAccessor;
})();
})(cola || (cola = {}));
/**
* When compiled, this file will build a CommonJS module for WebCola.
*
* Unfortunately, internal and external TypeScript modules do not get
* along well. This method of converting internal modules to external
* modules is a bit of a hack, but is minimally invasive (i.e., no modules
* need to be rewritten as external modules and modules can still span
* multiple files)
*
* When starting a new project from scratch where CommonJS compatibility
* is desired, consider instead preferring external modules to internal
* modules.
*/
///<reference path="./src/d3adaptor.ts"/>
///<reference path="./src/descent.ts"/>
///<reference path="./src/geom.ts"/>
///<reference path="./src/gridrouter.ts"/>
///<reference path="./src/handledisconnected.ts"/>
///<reference path="./src/layout.ts"/>
///<reference path="./src/layout3d.ts"/>
///<reference path="./src/linklengths.ts"/>
///<reference path="./src/powergraph.ts"/>
///<reference path="./src/pqueue.ts"/>
///<reference path="./src/rectangle.ts"/>
///<reference path="./src/shortestpaths.ts"/>
///<reference path="./src/vpsc.ts"/>
///<reference path="./src/rbtree.ts"/>
// Export cola as a CommonJS module. Note that we're bypassing TypeScript's external
// module system here. Because internal modules were written with the browser in mind,
// TypeScript's model is that the current context is the global context (i.e., window.cola
// === cola), so `export = cola` is transpiled as a no-op.
module.exports = cola;
| {
"content_hash": "49b5f08711b1896a04ada4669e13a366",
"timestamp": "",
"source": "github",
"line_count": 4785,
"max_line_length": 334,
"avg_line_length": 44.33814002089864,
"alnum_prop": 0.44929722188180504,
"repo_name": "shusenl/WebCola",
"id": "bfb228ffb8d88023959ed357ef2b8fc49bc22c3d",
"size": "212158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebCola/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7041"
},
{
"name": "HTML",
"bytes": "187330"
},
{
"name": "Handlebars",
"bytes": "755"
},
{
"name": "JavaScript",
"bytes": "599938"
},
{
"name": "TypeScript",
"bytes": "359116"
}
],
"symlink_target": ""
} |
package node
import (
"fmt"
"log"
"github.com/streadway/amqp"
)
// Producer configuration for sending messages via rabbit MQ
type Producer struct {
exch string
key string
uri string
}
// NewProducer creates configuration container *Producer
func NewProducer(uri, key string) *Producer {
exchangeName := "workflow.exchange"
p := &Producer{
exch: exchangeName,
key: key,
uri: uri,
}
return p
}
// Send a payload via rabbit amqp
func (p *Producer) Send(body []byte) error {
connection, err := amqp.Dial(p.uri)
if err != nil {
return fmt.Errorf("Dial: %s", err)
}
defer connection.Close()
channel, err := connection.Channel()
if err != nil {
return fmt.Errorf("Channel: %s", err)
}
if err := channel.Confirm(false); err != nil {
return fmt.Errorf("Channel could not be put into confirm mode: %s", err)
}
confirms := channel.NotifyPublish(make(chan amqp.Confirmation, 1))
defer confirmOne(confirms)
if err = channel.Publish(
p.exch, // publish to an exchange
p.key, // routing to 0 or more queues
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: amqp.Table{},
ContentType: "text/plain",
ContentEncoding: "",
Body: body,
DeliveryMode: amqp.Transient, // 1=non-persistent, 2=persistent
Priority: 0, // 0-9
},
); err != nil {
return fmt.Errorf("Exchange Publish: %s", err)
}
return nil
}
func confirmOne(confirms <-chan amqp.Confirmation) {
if confirmed := <-confirms; confirmed.Ack {
log.Printf("confirmed delivery with delivery tag: %d", confirmed.DeliveryTag)
} else {
log.Printf("failed delivery of delivery tag: %d", confirmed.DeliveryTag)
}
}
| {
"content_hash": "4647ca9ed91cda53c7540d316f6d089d",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 79,
"avg_line_length": 21.556962025316455,
"alnum_prop": 0.6600117439812097,
"repo_name": "jspc/workflow-engine",
"id": "e2bc4015ba429ca1f2a56278c96397d55addbb72",
"size": "1703",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node/producer.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "23852"
}
],
"symlink_target": ""
} |
package at.ac.tuwien.dsg.smartcom.rest;
import at.ac.tuwien.dsg.smartcom.Communication;
import at.ac.tuwien.dsg.smartcom.callback.NotificationCallback;
import at.ac.tuwien.dsg.smartcom.exception.CommunicationException;
import at.ac.tuwien.dsg.smartcom.exception.InvalidRuleException;
import at.ac.tuwien.dsg.smartcom.model.Identifier;
import at.ac.tuwien.dsg.smartcom.model.Message;
import at.ac.tuwien.dsg.smartcom.model.RoutingRule;
import at.ac.tuwien.dsg.smartcom.rest.model.MessageDTO;
import at.ac.tuwien.dsg.smartcom.rest.model.NotificationDTO;
import at.ac.tuwien.dsg.smartcom.rest.model.RoutingRuleDTO;
import at.ac.tuwien.dsg.smartcom.statistic.Statistic;
import at.ac.tuwien.dsg.smartcom.statistic.StatisticBean;
import jersey.repackaged.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Philipp Zeppezauer (philipp.zeppezauer@gmail.com)
* @version 1.0
*/
@Path("SmartCom")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public class CommunicationRESTImpl {
private static final Logger log = LoggerFactory.getLogger(CommunicationRESTImpl.class);
private HttpServer server;
private final URI serverURI;
private ExecutorService executorService;
@Inject
private Communication communication;
@Inject
private StatisticBean statistic;
public CommunicationRESTImpl(Communication communication, StatisticBean statistic) {
this();
this.communication = communication;
this.statistic = statistic;
}
public CommunicationRESTImpl(int port, String serverURIPostfix, Communication communication, StatisticBean statistic) {
this(port, serverURIPostfix);
this.communication = communication;
this.statistic = statistic;
}
public CommunicationRESTImpl() {
this(8080, "");
}
public CommunicationRESTImpl(int port, String serverURIPostfix) {
this.serverURI = URI.create("http://0.0.0.0:" + port + "/" + serverURIPostfix);
}
public void cleanUp() {
server.shutdown();
executorService.shutdown();
try {
if (!executorService.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
log.error("Could not await termination of executor. forcing shutdown", e);
executorService.shutdownNow();
}
}
public void init() {
executorService = Executors.newFixedThreadPool(10, new ThreadFactoryBuilder().setNameFormat("REST-notification-thread-%d").build());
server = GrizzlyHttpServerFactory.createHttpServer(serverURI, new RESTApplication());
try {
server.start();
} catch (IOException e) {
log.error("Could not initialize CommunicationRESTImpl", e);
}
}
@POST
@Path("message")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String send(MessageDTO message) throws CommunicationException {
if (message == null) {
throw new WebApplicationException();
}
Identifier id = communication.send(message.create());
if (id == null) {
return null;
}
return id.getId();
}
@POST
@Path("route")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String addRouting(RoutingRuleDTO rule) throws InvalidRuleException {
if (rule == null) {
throw new WebApplicationException();
}
communication.addRouting(rule.create());
return null;
}
@DELETE
@Path("route/{routeId}")
public RoutingRuleDTO removeRouting(@PathParam("routeId") String routeId) {
if (routeId == null) {
throw new WebApplicationException();
}
RoutingRule routingRule = communication.removeRouting(Identifier.routing(routeId));
if (routingRule != null) {
return new RoutingRuleDTO(routingRule);
}
return null;
}
@GET
@Path("statistic")
@Produces(MediaType.APPLICATION_JSON)
public Statistic statistic() {
return statistic.getStatistic();
}
@POST
@Path("notification")
@Consumes(MediaType.APPLICATION_JSON)
public void registerNotificationCallback(NotificationDTO callback) {
if (!callback.getUrl().startsWith("http://")) {
callback.setUrl("http://"+callback.getUrl());
}
communication.registerNotificationCallback(new NotificationRESTCallback(callback.getUrl()));
}
private class NotificationRESTCallback implements NotificationCallback {
private final Client client;
private final String url;
private NotificationRESTCallback(String url) {
this.url = url;
this.client = ClientBuilder.newBuilder()
.register(JacksonFeature.class)
.property(ClientProperties.CONNECT_TIMEOUT, 1000)
.property(ClientProperties.READ_TIMEOUT, 1000)
.build();
}
@Override
public void notify(final Message message) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
WebTarget target = client.target(url);
Response response = target.request(MediaType.APPLICATION_JSON).post(Entity.json(new MessageDTO(message)), Response.class);
if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
log.error("Could not send message {} to notification callback \nResponse: {}", message, response);
}
} catch (Exception ignored) {
log.debug("Could not notify rest callback", ignored);
}
}
});
}
}
private class RESTApplication extends ResourceConfig {
private RESTApplication() {
register(CommunicationRESTImpl.class);
register(ObjectMapperProvider.class);
register(JacksonFeature.class);
// register(new LoggingFilter(java.util.logging.Logger.getLogger("Jersey"), true));
register(new AbstractBinder() {
@Override
protected void configure() {
bind(communication).to(Communication.class);
bind(executorService).to(ExecutorService.class);
bind(statistic).to(StatisticBean.class);
}
});
}
}
}
| {
"content_hash": "1ad1997b62dff20d4f596cbcf18eb55f",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 146,
"avg_line_length": 34.031531531531535,
"alnum_prop": 0.65638649900728,
"repo_name": "tuwiendsg/SmartCom",
"id": "8970da0ad608122d43aacec0b2973d52533254f3",
"size": "8372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rest/src/main/java/at/ac/tuwien/dsg/smartcom/rest/CommunicationRESTImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1004960"
}
],
"symlink_target": ""
} |
ALTER TABLE "Company" ADD COLUMN "website" TEXT;
| {
"content_hash": "f113fbab05241d4dd5925ee7c0660291",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 52,
"avg_line_length": 53,
"alnum_prop": 0.6981132075471698,
"repo_name": "yangshun/tech-interview-handbook",
"id": "8504ebbc1f491f64257289b50c4f0f72de9d6f21",
"size": "67",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "apps/portal/prisma/migrations/20221107014555_company_website/migration.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7540"
},
{
"name": "HTML",
"bytes": "12283"
},
{
"name": "JavaScript",
"bytes": "104095"
},
{
"name": "Python",
"bytes": "20569"
},
{
"name": "Shell",
"bytes": "297"
},
{
"name": "TypeScript",
"bytes": "1088472"
}
],
"symlink_target": ""
} |
package org.mycontroller.standalone.settings;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.mycontroller.standalone.jobs.SystemExportJob;
import org.mycontroller.standalone.scheduler.SchedulerUtils;
import org.mycontroller.standalone.timer.TimerSimple;
import org.mycontroller.standalone.utils.McUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 0.0.3
*/
@Builder
@ToString(includeFieldNames = true)
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class ExportSettings {
private static final String JOB_NAME = "myController-export-job";
public static final String KEY_EXPORT = "export_data";
public static final String SKEY_ENABLED = "enabled";
public static final String SKEY_PREFIX = "prefix";
public static final String SKEY_INTERVAL = "interval";
public static final String SKEY_RETAIN_MAX = "retainMax";
public static final String SKEY_EXPORT_LOCATION = "exportLocation";
public static final String SKEY_ROW_LIMIT = "rowLimit";
private Boolean enabled;
private String prefix;
private Long interval;
private Integer retainMax;
private String exportLocation;
private Long rowLimit;
public String getExportLocation() {
if (exportLocation == null) {
exportLocation = "../export/";
} else if (!exportLocation.endsWith("/")) {
exportLocation = exportLocation + "/";
}
//Create backup location
if (!FileUtils.getFile(exportLocation).exists()) {
try {
FileUtils.forceMkdir(FileUtils.getFile(exportLocation));
_logger.debug("export location created.");
} catch (IOException e) {
_logger.error("Unable to create export location");
}
}
return exportLocation;
}
public Boolean getEnabled() {
if (enabled == null) {
return false;
}
return enabled;
}
public Long getNextFire() {
if (getEnabled()) {
return SchedulerUtils.nextFireTime(JOB_NAME, null);
}
return null;
}
public static ExportSettings get() {
ExportSettings _settings = ExportSettings.builder()
.enabled(McUtils.getBoolean(getValue(SKEY_ENABLED)))
.prefix(getValue(SKEY_PREFIX))
.interval(McUtils.getLong(getValue(SKEY_INTERVAL)))
.retainMax(McUtils.getInteger(getValue(SKEY_RETAIN_MAX)))
.exportLocation(getValue(SKEY_EXPORT_LOCATION))
.rowLimit(McUtils.getLong(getValue(SKEY_ROW_LIMIT)))
.build();
return _settings;
}
public void save() {
if (enabled != null) {
updateValue(SKEY_ENABLED, enabled);
}
if (prefix != null) {
updateValue(SKEY_PREFIX, prefix.trim());
}
if (interval != null) {
//Should not allow to take backup less than a minute frequency
if (interval < McUtils.ONE_MINUTE) {
interval = McUtils.ONE_MINUTE;
}
updateValue(SKEY_INTERVAL, interval);
}
if (retainMax != null) {
updateValue(SKEY_RETAIN_MAX, retainMax);
}
if (exportLocation != null) {
updateValue(SKEY_EXPORT_LOCATION, exportLocation);
}
if (rowLimit != null) {
updateValue(SKEY_ROW_LIMIT, rowLimit);
}
}
private static String getValue(String subKey) {
return SettingsUtils.getValue(KEY_EXPORT, subKey);
}
private void updateValue(String subKey, Object value) {
SettingsUtils.updateValue(KEY_EXPORT, subKey, value);
}
public static void reloadJob() {
ExportSettings settings = get();
TimerSimple timerSimple = new TimerSimple(
JOB_NAME,//Job Name
settings.getEnabled(),
SystemExportJob.class.getName(),
settings.getInterval(),
-1//Repeat count
);
SchedulerUtils.reloadTimerJob(timerSimple.getTimer());
}
}
| {
"content_hash": "7cb7d13b330474686ffae5ea063f0f76",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 74,
"avg_line_length": 31.467153284671532,
"alnum_prop": 0.6207376478775226,
"repo_name": "mycontroller-org/mycontroller",
"id": "d35d2f0ffaec9c550f2f4f2e8f5f3d537d737202",
"size": "4994",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "modules/core/src/main/java/org/mycontroller/standalone/settings/ExportSettings.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2544030"
}
],
"symlink_target": ""
} |
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - getrf.h</title></head><body bgcolor='white'><pre>
<font color='#009900'>// Copyright (C) 2010 Davis E. King (davis@dlib.net)
</font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license.
</font><font color='#0000FF'>#ifndef</font> DLIB_LAPACk_GETRF_H__
<font color='#0000FF'>#define</font> DLIB_LAPACk_GETRF_H__
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='fortran_id.h.html'>fortran_id.h</a>"
<font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../matrix.h.html'>../matrix.h</a>"
<font color='#0000FF'>namespace</font> dlib
<b>{</b>
<font color='#0000FF'>namespace</font> lapack
<b>{</b>
<font color='#0000FF'>namespace</font> binding
<b>{</b>
<font color='#0000FF'>extern</font> "<font color='#CC0000'>C</font>"
<b>{</b>
<font color='#0000FF'><u>void</u></font> <b><a name='DLIB_FORTRAN_ID'></a>DLIB_FORTRAN_ID</b><font face='Lucida Console'>(</font>dgetrf<font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>integer<font color='#5555FF'>*</font> m, integer <font color='#5555FF'>*</font>n, <font color='#0000FF'><u>double</u></font> <font color='#5555FF'>*</font>a,
integer<font color='#5555FF'>*</font> lda, integer <font color='#5555FF'>*</font>ipiv, integer <font color='#5555FF'>*</font>info<font face='Lucida Console'>)</font>;
<font color='#0000FF'><u>void</u></font> <b><a name='DLIB_FORTRAN_ID'></a>DLIB_FORTRAN_ID</b><font face='Lucida Console'>(</font>sgetrf<font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font>integer<font color='#5555FF'>*</font> m, integer <font color='#5555FF'>*</font>n, <font color='#0000FF'><u>float</u></font> <font color='#5555FF'>*</font>a,
integer<font color='#5555FF'>*</font> lda, integer <font color='#5555FF'>*</font>ipiv, integer <font color='#5555FF'>*</font>info<font face='Lucida Console'>)</font>;
<b>}</b>
<font color='#0000FF'>inline</font> <font color='#0000FF'><u>int</u></font> <b><a name='getrf'></a>getrf</b> <font face='Lucida Console'>(</font>integer m, integer n, <font color='#0000FF'><u>double</u></font> <font color='#5555FF'>*</font>a,
integer lda, integer <font color='#5555FF'>*</font>ipiv<font face='Lucida Console'>)</font>
<b>{</b>
integer info <font color='#5555FF'>=</font> <font color='#979000'>0</font>;
<font color='#BB00BB'>DLIB_FORTRAN_ID</font><font face='Lucida Console'>(</font>dgetrf<font face='Lucida Console'>)</font><font face='Lucida Console'>(</font><font color='#5555FF'>&</font>m, <font color='#5555FF'>&</font>n, a, <font color='#5555FF'>&</font>lda, ipiv, <font color='#5555FF'>&</font>info<font face='Lucida Console'>)</font>;
<font color='#0000FF'>return</font> info;
<b>}</b>
<font color='#0000FF'>inline</font> <font color='#0000FF'><u>int</u></font> <b><a name='getrf'></a>getrf</b> <font face='Lucida Console'>(</font>integer m, integer n, <font color='#0000FF'><u>float</u></font> <font color='#5555FF'>*</font>a,
integer lda, integer <font color='#5555FF'>*</font>ipiv<font face='Lucida Console'>)</font>
<b>{</b>
integer info <font color='#5555FF'>=</font> <font color='#979000'>0</font>;
<font color='#BB00BB'>DLIB_FORTRAN_ID</font><font face='Lucida Console'>(</font>sgetrf<font face='Lucida Console'>)</font><font face='Lucida Console'>(</font><font color='#5555FF'>&</font>m, <font color='#5555FF'>&</font>n, a, <font color='#5555FF'>&</font>lda, ipiv, <font color='#5555FF'>&</font>info<font face='Lucida Console'>)</font>;
<font color='#0000FF'>return</font> info;
<b>}</b>
<b>}</b>
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<font color='#009900'>/* -- LAPACK routine (version 3.1) -- */</font>
<font color='#009900'>/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */</font>
<font color='#009900'>/* November 2006 */</font>
<font color='#009900'>/* .. Scalar Arguments .. */</font>
<font color='#009900'>/* .. */</font>
<font color='#009900'>/* .. Array Arguments .. */</font>
<font color='#009900'>/* .. */</font>
<font color='#009900'>/* Purpose */</font>
<font color='#009900'>/* ======= */</font>
<font color='#009900'>/* DGETRF computes an LU factorization of a general M-by-N matrix A */</font>
<font color='#009900'>/* using partial pivoting with row interchanges. */</font>
<font color='#009900'>/* The factorization has the form */</font>
<font color='#009900'>/* A = P * L * U */</font>
<font color='#009900'>/* where P is a permutation matrix, L is lower triangular with unit */</font>
<font color='#009900'>/* diagonal elements (lower trapezoidal if m > n), and U is upper */</font>
<font color='#009900'>/* triangular (upper trapezoidal if m < n). */</font>
<font color='#009900'>/* This is the right-looking Level 3 BLAS version of the algorithm. */</font>
<font color='#009900'>/* Arguments */</font>
<font color='#009900'>/* ========= */</font>
<font color='#009900'>/* M (input) INTEGER */</font>
<font color='#009900'>/* The number of rows of the matrix A. M >= 0. */</font>
<font color='#009900'>/* N (input) INTEGER */</font>
<font color='#009900'>/* The number of columns of the matrix A. N >= 0. */</font>
<font color='#009900'>/* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */</font>
<font color='#009900'>/* On entry, the M-by-N matrix to be factored. */</font>
<font color='#009900'>/* On exit, the factors L and U from the factorization */</font>
<font color='#009900'>/* A = P*L*U; the unit diagonal elements of L are not stored. */</font>
<font color='#009900'>/* LDA (input) INTEGER */</font>
<font color='#009900'>/* The leading dimension of the array A. LDA >= max(1,M). */</font>
<font color='#009900'>/* IPIV (output) INTEGER array, dimension (min(M,N)) */</font>
<font color='#009900'>/* The pivot indices; for 1 <= i <= min(M,N), row i of the */</font>
<font color='#009900'>/* matrix was interchanged with row IPIV(i). */</font>
<font color='#009900'>/* INFO (output) INTEGER */</font>
<font color='#009900'>/* = 0: successful exit */</font>
<font color='#009900'>/* < 0: if INFO = -i, the i-th argument had an illegal value */</font>
<font color='#009900'>/* > 0: if INFO = i, U(i,i) is exactly zero. The factorization */</font>
<font color='#009900'>/* has been completed, but the factor U is exactly */</font>
<font color='#009900'>/* singular, and division by zero will occur if it is used */</font>
<font color='#009900'>/* to solve a system of equations. */</font>
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>template</font> <font color='#5555FF'><</font>
<font color='#0000FF'>typename</font> T,
<font color='#0000FF'><u>long</u></font> NR1, <font color='#0000FF'><u>long</u></font> NR2,
<font color='#0000FF'><u>long</u></font> NC1, <font color='#0000FF'><u>long</u></font> NC2,
<font color='#0000FF'>typename</font> MM,
<font color='#0000FF'>typename</font> layout
<font color='#5555FF'>></font>
<font color='#0000FF'><u>int</u></font> <b><a name='getrf'></a>getrf</b> <font face='Lucida Console'>(</font>
matrix<font color='#5555FF'><</font>T,NR1,NC1,MM,column_major_layout<font color='#5555FF'>></font><font color='#5555FF'>&</font> a,
matrix<font color='#5555FF'><</font>integer,NR2,NC2,MM,layout<font color='#5555FF'>></font><font color='#5555FF'>&</font> ipiv
<font face='Lucida Console'>)</font>
<b>{</b>
<font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> m <font color='#5555FF'>=</font> a.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>;
<font color='#0000FF'>const</font> <font color='#0000FF'><u>long</u></font> n <font color='#5555FF'>=</font> a.<font color='#BB00BB'>nc</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>;
ipiv.<font color='#BB00BB'>set_size</font><font face='Lucida Console'>(</font>std::<font color='#BB00BB'>min</font><font face='Lucida Console'>(</font>m,n<font face='Lucida Console'>)</font>, <font color='#979000'>1</font><font face='Lucida Console'>)</font>;
<font color='#009900'>// compute the actual decomposition
</font> <font color='#0000FF'>return</font> binding::<font color='#BB00BB'>getrf</font><font face='Lucida Console'>(</font>m, n, <font color='#5555FF'>&</font><font color='#BB00BB'>a</font><font face='Lucida Console'>(</font><font color='#979000'>0</font>,<font color='#979000'>0</font><font face='Lucida Console'>)</font>, a.<font color='#BB00BB'>nr</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>, <font color='#5555FF'>&</font><font color='#BB00BB'>ipiv</font><font face='Lucida Console'>(</font><font color='#979000'>0</font>,<font color='#979000'>0</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>;
<b>}</b>
<font color='#009900'>// ------------------------------------------------------------------------------------
</font>
<b>}</b>
<b>}</b>
<font color='#009900'>// ----------------------------------------------------------------------------------------
</font>
<font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_LAPACk_GETRF_H__
</font>
</pre></body></html> | {
"content_hash": "29eb163f4b5ba25f5d9b01af7b50c93f",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 683,
"avg_line_length": 76.4888888888889,
"alnum_prop": 0.5735037768739105,
"repo_name": "mnolan2/offlineSlSc",
"id": "024ef705d75eb2f1514f041e9f788638f1c94a9e",
"size": "10326",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "dlib-18.7/docs/dlib/matrix/lapack/getrf.h.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8550571"
},
{
"name": "C++",
"bytes": "6179618"
},
{
"name": "CSS",
"bytes": "16435"
},
{
"name": "JavaScript",
"bytes": "80947"
},
{
"name": "Objective-C",
"bytes": "65355"
},
{
"name": "Python",
"bytes": "41577"
},
{
"name": "Shell",
"bytes": "102"
},
{
"name": "XSLT",
"bytes": "18386"
}
],
"symlink_target": ""
} |
module Redisearch #:nodoc
# Configuration methods for Redisearch
module Configurator
include Helpers
extend self
# Do not index words shorter than this length
MIN_WORD_LENGTH = 3
# Words which should not be indexed
STOP_WORDS = ['the', 'of', 'to', 'and', 'a', 'in', 'is', 'it', 'you', 'that']
# Convert punctuation to spaces before indexing
PUNCTUATION_CHARS = ".,;:!?@$%^&*()--<>[]{}\\|/`~'\""
# update the default configuration
# Accepts:
# 1) :min_word_length (Integer)
# 2) :stop_words (Array)
# 3) :punctuation_chars (String)
def update_settings( _options={} )
_options[:stop_words] = _options[:stop_words].to_a if _options[:stop_words].kind_of?( String )
@settings = settings.merge( _options )
end
# return the current configuration settins
def settings
return @settings if @settings
@settings = default_settings
end
# Reset settings to default configuration
def reset_to_defaults!
@settings = default_settings
end
# Default settings
def default_settings
{
:min_word_length => MIN_WORD_LENGTH,
:stop_words => STOP_WORDS,
:punctuation_chars => PUNCTUATION_CHARS
}
end
private
# Set Redisearch settings hash
# * will overwrite any existing settings
def settings=( _new_settings={} )
@settings = _new_settings
end
end
end
| {
"content_hash": "53e7a46e64ac81c41afc3c17f1bc7ff7",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 100,
"avg_line_length": 27.660377358490567,
"alnum_prop": 0.6002728512960437,
"repo_name": "cpjolicoeur/redisearch",
"id": "2511c94e614b0236c16ae4b1c1401995627074fe",
"size": "1466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/redisearch/configurator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "447"
}
],
"symlink_target": ""
} |
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Structure describing the ray tracing opacity micromap features that can be supported by an implementation.
*
* <h5>Description</h5>
*
* <p>If the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT} structure is included in the {@code pNext} chain of the {@link VkPhysicalDeviceFeatures2} structure passed to {@link VK11#vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2}, it is filled in to indicate whether each corresponding feature is supported. {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT} <b>can</b> also be used in the {@code pNext} chain of {@link VkDeviceCreateInfo} to selectively enable these features.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code sType} <b>must</b> be {@link EXTOpacityMicromap#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT}</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkPhysicalDeviceOpacityMicromapFeaturesEXT {
* VkStructureType {@link #sType};
* void * {@link #pNext};
* VkBool32 {@link #micromap};
* VkBool32 {@link #micromapCaptureReplay};
* VkBool32 {@link #micromapHostCommands};
* }</code></pre>
*/
public class VkPhysicalDeviceOpacityMicromapFeaturesEXT extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
STYPE,
PNEXT,
MICROMAP,
MICROMAPCAPTUREREPLAY,
MICROMAPHOSTCOMMANDS;
static {
Layout layout = __struct(
__member(4),
__member(POINTER_SIZE),
__member(4),
__member(4),
__member(4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
STYPE = layout.offsetof(0);
PNEXT = layout.offsetof(1);
MICROMAP = layout.offsetof(2);
MICROMAPCAPTUREREPLAY = layout.offsetof(3);
MICROMAPHOSTCOMMANDS = layout.offsetof(4);
}
/**
* Creates a {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkPhysicalDeviceOpacityMicromapFeaturesEXT(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** the type of this structure. */
@NativeType("VkStructureType")
public int sType() { return nsType(address()); }
/** {@code NULL} or a pointer to a structure extending this structure. */
@NativeType("void *")
public long pNext() { return npNext(address()); }
/** indicates whether the implementation supports the micromap array feature. */
@NativeType("VkBool32")
public boolean micromap() { return nmicromap(address()) != 0; }
/** indicates whether the implementation supports capture and replay of addresses for micromap arrays. */
@NativeType("VkBool32")
public boolean micromapCaptureReplay() { return nmicromapCaptureReplay(address()) != 0; }
/** indicates whether the implementation supports host side micromap array commands. */
@NativeType("VkBool32")
public boolean micromapHostCommands() { return nmicromapHostCommands(address()) != 0; }
/** Sets the specified value to the {@link #sType} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the {@link EXTOpacityMicromap#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT} value to the {@link #sType} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT sType$Default() { return sType(EXTOpacityMicromap.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT); }
/** Sets the specified value to the {@link #pNext} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT pNext(@NativeType("void *") long value) { npNext(address(), value); return this; }
/** Sets the specified value to the {@link #micromap} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT micromap(@NativeType("VkBool32") boolean value) { nmicromap(address(), value ? 1 : 0); return this; }
/** Sets the specified value to the {@link #micromapCaptureReplay} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT micromapCaptureReplay(@NativeType("VkBool32") boolean value) { nmicromapCaptureReplay(address(), value ? 1 : 0); return this; }
/** Sets the specified value to the {@link #micromapHostCommands} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT micromapHostCommands(@NativeType("VkBool32") boolean value) { nmicromapHostCommands(address(), value ? 1 : 0); return this; }
/** Initializes this struct with the specified values. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT set(
int sType,
long pNext,
boolean micromap,
boolean micromapCaptureReplay,
boolean micromapHostCommands
) {
sType(sType);
pNext(pNext);
micromap(micromap);
micromapCaptureReplay(micromapCaptureReplay);
micromapHostCommands(micromapHostCommands);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkPhysicalDeviceOpacityMicromapFeaturesEXT set(VkPhysicalDeviceOpacityMicromapFeaturesEXT src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT malloc() {
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT calloc() {
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance allocated with {@link BufferUtils}. */
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, memAddress(container), container);
}
/** Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance for the specified memory address. */
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT create(long address) {
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT createSafe(long address) {
return address == NULL ? null : wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, address);
}
/**
* Returns a new {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
/**
* Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT malloc(MemoryStack stack) {
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT calloc(MemoryStack stack) {
return wrap(VkPhysicalDeviceOpacityMicromapFeaturesEXT.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #sType}. */
public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.STYPE); }
/** Unsafe version of {@link #pNext}. */
public static long npNext(long struct) { return memGetAddress(struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.PNEXT); }
/** Unsafe version of {@link #micromap}. */
public static int nmicromap(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAP); }
/** Unsafe version of {@link #micromapCaptureReplay}. */
public static int nmicromapCaptureReplay(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAPCAPTUREREPLAY); }
/** Unsafe version of {@link #micromapHostCommands}. */
public static int nmicromapHostCommands(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAPHOSTCOMMANDS); }
/** Unsafe version of {@link #sType(int) sType}. */
public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.STYPE, value); }
/** Unsafe version of {@link #pNext(long) pNext}. */
public static void npNext(long struct, long value) { memPutAddress(struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.PNEXT, value); }
/** Unsafe version of {@link #micromap(boolean) micromap}. */
public static void nmicromap(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAP, value); }
/** Unsafe version of {@link #micromapCaptureReplay(boolean) micromapCaptureReplay}. */
public static void nmicromapCaptureReplay(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAPCAPTUREREPLAY, value); }
/** Unsafe version of {@link #micromapHostCommands(boolean) micromapHostCommands}. */
public static void nmicromapHostCommands(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceOpacityMicromapFeaturesEXT.MICROMAPHOSTCOMMANDS, value); }
// -----------------------------------
/** An array of {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT} structs. */
public static class Buffer extends StructBuffer<VkPhysicalDeviceOpacityMicromapFeaturesEXT, Buffer> implements NativeResource {
private static final VkPhysicalDeviceOpacityMicromapFeaturesEXT ELEMENT_FACTORY = VkPhysicalDeviceOpacityMicromapFeaturesEXT.create(-1L);
/**
* Creates a new {@code VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkPhysicalDeviceOpacityMicromapFeaturesEXT getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#sType} field. */
@NativeType("VkStructureType")
public int sType() { return VkPhysicalDeviceOpacityMicromapFeaturesEXT.nsType(address()); }
/** @return the value of the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#pNext} field. */
@NativeType("void *")
public long pNext() { return VkPhysicalDeviceOpacityMicromapFeaturesEXT.npNext(address()); }
/** @return the value of the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromap} field. */
@NativeType("VkBool32")
public boolean micromap() { return VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromap(address()) != 0; }
/** @return the value of the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromapCaptureReplay} field. */
@NativeType("VkBool32")
public boolean micromapCaptureReplay() { return VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromapCaptureReplay(address()) != 0; }
/** @return the value of the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromapHostCommands} field. */
@NativeType("VkBool32")
public boolean micromapHostCommands() { return VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromapHostCommands(address()) != 0; }
/** Sets the specified value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#sType} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer sType(@NativeType("VkStructureType") int value) { VkPhysicalDeviceOpacityMicromapFeaturesEXT.nsType(address(), value); return this; }
/** Sets the {@link EXTOpacityMicromap#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT} value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#sType} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer sType$Default() { return sType(EXTOpacityMicromap.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_OPACITY_MICROMAP_FEATURES_EXT); }
/** Sets the specified value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#pNext} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer pNext(@NativeType("void *") long value) { VkPhysicalDeviceOpacityMicromapFeaturesEXT.npNext(address(), value); return this; }
/** Sets the specified value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromap} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer micromap(@NativeType("VkBool32") boolean value) { VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromap(address(), value ? 1 : 0); return this; }
/** Sets the specified value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromapCaptureReplay} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer micromapCaptureReplay(@NativeType("VkBool32") boolean value) { VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromapCaptureReplay(address(), value ? 1 : 0); return this; }
/** Sets the specified value to the {@link VkPhysicalDeviceOpacityMicromapFeaturesEXT#micromapHostCommands} field. */
public VkPhysicalDeviceOpacityMicromapFeaturesEXT.Buffer micromapHostCommands(@NativeType("VkBool32") boolean value) { VkPhysicalDeviceOpacityMicromapFeaturesEXT.nmicromapHostCommands(address(), value ? 1 : 0); return this; }
}
} | {
"content_hash": "d084b2ad0bd8bc47bc04d20f758605a6",
"timestamp": "",
"source": "github",
"line_count": 348,
"max_line_length": 494,
"avg_line_length": 54.78448275862069,
"alnum_prop": 0.7213742460005245,
"repo_name": "LWJGL/lwjgl3",
"id": "f4a201f5439a94cdf6d2206b0dfe0b53e5d5bc56",
"size": "19199",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkPhysicalDeviceOpacityMicromapFeaturesEXT.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14340"
},
{
"name": "C",
"bytes": "12213911"
},
{
"name": "C++",
"bytes": "1982042"
},
{
"name": "GLSL",
"bytes": "1703"
},
{
"name": "Java",
"bytes": "76116697"
},
{
"name": "Kotlin",
"bytes": "19700291"
},
{
"name": "Objective-C",
"bytes": "14684"
},
{
"name": "Objective-C++",
"bytes": "2004"
}
],
"symlink_target": ""
} |
package com.xcysoft.framework.core.utils.listUtils;
import java.util.Date;
import com.xcysoft.framework.core.utils.dataUtils.DateMorpherEx;
import com.xcysoft.framework.core.utils.stringUtils.JsonDateValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.PropertyFilter;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
/**
* @JSONUtil.java
* @author huangxin
*/
public class JSONTools {
protected static Logger logger = Logger.getLogger(JSONTools.class);
static {
String[] dateFormats = new String[] { "yyyy-MM-dd HH:mm:ss" };
JSONUtils.getMorpherRegistry().registerMorpher(
new DateMorpherEx(dateFormats));// 注册格式化日期的模式
}
/**
* @return
*/
public static final String getString(JSONObject json, String key) {
String result = "";
Object obj = getObject(json, key);
if (obj != null) {
result = obj.toString();
}
return result;
}
public static final int getInt(JSONObject json, String key) {
int result = 0;
Object obj = getObject(json, key);
if (obj != null) {
result = NumberUtils.toInt(obj.toString(), result);
}
return result;
}
public static final boolean getBoolean(JSONObject json, String key) {
boolean result = false;
Object obj = getObject(json, key);
if (obj != null) {
result = BooleanUtils.toBoolean(obj.toString());
}
return result;
}
public static final Double getDouble(JSONObject json, String key) {
double result = 0;
Object obj = getObject(json, key);
if (obj != null) {
result = NumberUtils.toDouble(obj.toString(), result);
}
return result;
}
public static final JSONObject getJSONObject(JSONObject json, String key) {
JSONObject result = null;
Object obj = getObject(json, key);
if (obj != null && obj instanceof JSONObject) {
result = (JSONObject) obj;
}
return result;
}
public static final JSONArray getJSONArray(JSONObject json, String key) {
JSONArray result = null;
Object obj = getObject(json, key);
if (obj != null && obj instanceof JSONArray) {
result = (JSONArray) obj;
}
return result;
}
public static final Object getObject(JSONObject json, String key) {
Object result = null;
if (json != null && StringUtils.isNotEmpty(key)
&& json.containsKey(key)) {
result = json.get(key);
}
return result;
}
public static final <T> T JSONToBean(JSONObject jsonData, Class<T> clazz) {
return JSONToBean(jsonData, clazz, null);
}
/**
* @return
*/
@SuppressWarnings("unchecked")
public static final <T> T JSONToBean(JSONObject jsonData, Class<T> clazz,
JsonConfig jsonConfig) {
T result = null;
if (jsonData == null || jsonData.size() == 0 || clazz == null) {
return result;
}
if (jsonConfig == null) {
jsonConfig = getJSConfig(null, null, false);
}
try {
result = clazz.newInstance();
result = (T) JSONObject.toBean(jsonData, result, jsonConfig);
} catch (Exception e) {
e.printStackTrace();
logger.error(ExceptionUtils.getFullStackTrace(e));
}
return result;
}
/**
*
* @return
*/
public static final <T> T JSONToBean(JSONObject jsonData, Class<T> clazz,
String[] excludes, String datePattern, Boolean includeNull) {
JsonConfig jsonConfig = getJSConfig(excludes, datePattern, includeNull);
return JSONToBean(jsonData, clazz, jsonConfig);
}
/**
* @return
*/
public static JsonConfig getJSConfig(String[] excludes, String datePattern,
Boolean includeNull) {
JsonConfig result = new JsonConfig();
if (null != excludes)
result.setExcludes(excludes);
result.setIgnoreDefaultExcludes(false);
result.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
result.registerJsonValueProcessor(Date.class,
new JsonDateValueProcessor(datePattern));
if (includeNull != null && includeNull == false) {
// 忽略属性值为null的字段
result.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
// 忽略birthday属性
if (value == null) {
return true;
}
return false;
}
});
result.setJavaPropertyFilter(new PropertyFilter() {
@Override
public boolean apply(Object source, String name, Object value) {
if (value == null || StringUtils.isBlank(value.toString())) {
return true;
}
return false;
}
});
}
return result;
}
public JSONObject strToJSONObject(String str, JSONObject jsonObject) {
JSONObject result = null;
return result;
}
public static JSONObject parseToJSONObject(String str) {
JSONObject result = null;
if (StringUtils.isNotBlank(str) && str.startsWith("{")
&& str.endsWith("}")) {
result = JSONObject.fromObject(str);
}
if (result == null) {
result = new JSONObject();
}
return result;
}
}
| {
"content_hash": "2df878b389c05883fdb5da8da6f085d6",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 76,
"avg_line_length": 25.484848484848484,
"alnum_prop": 0.6965913594926675,
"repo_name": "3203317/ppp",
"id": "d2a9431d6ccde3c9246158ebc3bd6dcb541ebaf6",
"size": "5092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework-core/src/main/java/com/xcysoft/framework/core/utils/listUtils/JSONTools.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "612852"
},
{
"name": "FreeMarker",
"bytes": "5391"
},
{
"name": "HTML",
"bytes": "358222"
},
{
"name": "IDL",
"bytes": "41930"
},
{
"name": "Java",
"bytes": "2006042"
},
{
"name": "JavaScript",
"bytes": "1953116"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace WindowsPhoneDemo
{
public partial class App : Application
{
/// <summary>
/// Bietet einen einfachen Zugriff auf den Stammframe der Phone-Anwendung.
/// </summary>
/// <returns>Der Stammframe der Phone-Anwendung.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Konstruktor für das Application-Objekt.
/// </summary>
public App()
{
// Globaler Handler für nicht abgefangene Ausnahmen.
UnhandledException += Application_UnhandledException;
// Silverlight-Standardinitialisierung
InitializeComponent();
// Phone-spezifische Initialisierung
InitializePhoneApplication();
// Während des Debuggens Profilerstellungsinformationen zur Grafikleistung anzeigen.
if (System.Diagnostics.Debugger.IsAttached)
{
// Zähler für die aktuelle Bildrate anzeigen.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Bereiche der Anwendung hervorheben, die mit jedem Bild neu gezeichnet werden.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Nicht produktiven Visualisierungsmodus für die Analyse aktivieren,
// in dem Bereiche einer Seite angezeigt werden, die mit einer Farbüberlagerung an die GPU übergeben wurden.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Deaktivieren Sie die Leerlauferkennung der Anwendung, indem Sie die UserIdleDetectionMode-Eigenschaft des
// PhoneApplicationService-Objekts der Anwendung auf "Disabled" festlegen.
// Vorsicht: Nur im Debugmodus verwenden. Eine Anwendung mit deaktivierter Benutzerleerlauferkennung wird weiterhin ausgeführt
// und verbraucht auch dann Akkuenergie, wenn der Benutzer das Handy nicht verwendet.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code, der beim Starten der Anwendung ausgeführt werden soll (z. B. über "Start")
// Dieser Code wird beim Reaktivieren der Anwendung nicht ausgeführt
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code, der ausgeführt werden soll, wenn die Anwendung aktiviert wird (in den Vordergrund gebracht wird)
// Dieser Code wird beim ersten Starten der Anwendung nicht ausgeführt
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code, der ausgeführt werden soll, wenn die Anwendung deaktiviert wird (in den Hintergrund gebracht wird)
// Dieser Code wird beim Schließen der Anwendung nicht ausgeführt
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code, der beim Schließen der Anwendung ausgeführt wird (z. B. wenn der Benutzer auf "Zurück" klickt)
// Dieser Code wird beim Deaktivieren der Anwendung nicht ausgeführt
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code, der bei einem Navigationsfehler ausgeführt wird
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// Navigationsfehler. Unterbrechen und Debugger öffnen
System.Diagnostics.Debugger.Break();
}
}
// Code, der bei nicht behandelten Ausnahmen ausgeführt wird
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// Eine nicht behandelte Ausnahme ist aufgetreten. Unterbrechen und Debugger öffnen
System.Diagnostics.Debugger.Break();
}
}
#region Initialisierung der Phone-Anwendung
// Doppelte Initialisierung vermeiden
private bool phoneApplicationInitialized = false;
// Fügen Sie keinen zusätzlichen Code zu dieser Methode hinzu
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Frame erstellen, aber noch nicht als RootVisual festlegen. Dadurch kann der Begrüßungsbildschirm
// aktiv bleiben, bis die Anwendung bereit für das Rendern ist.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Navigationsfehler behandeln
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Sicherstellen, dass keine erneute Initialisierung erfolgt
phoneApplicationInitialized = true;
}
// Fügen Sie keinen zusätzlichen Code zu dieser Methode hinzu
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Visuelle Stammkomponente festlegen, sodass die Anwendung gerendert werden kann
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Dieser Handler wird nicht mehr benötigt und kann entfernt werden
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
} | {
"content_hash": "ee77674b5980fc1886ebffb2b2e7add8",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 138,
"avg_line_length": 40.16901408450704,
"alnum_prop": 0.699859747545582,
"repo_name": "zxingwin/core",
"id": "71f693618c12056aa69dc8f21675f5eac5d8d921",
"size": "5739",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ZXing.Net/ZXing.Net.Original/Source-0.14.0.0/Base/Clients/WindowsPhoneDemo/App.xaml.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "146"
},
{
"name": "C#",
"bytes": "8962990"
},
{
"name": "C++",
"bytes": "8384"
},
{
"name": "CSS",
"bytes": "232"
},
{
"name": "HTML",
"bytes": "937"
},
{
"name": "JavaScript",
"bytes": "7402"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/jobs.proto
package com.google.cloud.dataproc.v1;
/**
* <pre>
* A request to list jobs in a project.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ListJobsRequest}
*/
public final class ListJobsRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.ListJobsRequest)
ListJobsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListJobsRequest.newBuilder() to construct.
private ListJobsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListJobsRequest() {
projectId_ = "";
region_ = "";
pageSize_ = 0;
pageToken_ = "";
clusterName_ = "";
jobStateMatcher_ = 0;
filter_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ListJobsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
projectId_ = s;
break;
}
case 16: {
pageSize_ = input.readInt32();
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
break;
}
case 34: {
java.lang.String s = input.readStringRequireUtf8();
clusterName_ = s;
break;
}
case 40: {
int rawValue = input.readEnum();
jobStateMatcher_ = rawValue;
break;
}
case 50: {
java.lang.String s = input.readStringRequireUtf8();
region_ = s;
break;
}
case 58: {
java.lang.String s = input.readStringRequireUtf8();
filter_ = s;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_ListJobsRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_ListJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ListJobsRequest.class, com.google.cloud.dataproc.v1.ListJobsRequest.Builder.class);
}
/**
* <pre>
* A matcher that specifies categories of job states.
* </pre>
*
* Protobuf enum {@code google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher}
*/
public enum JobStateMatcher
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Match all jobs, regardless of state.
* </pre>
*
* <code>ALL = 0;</code>
*/
ALL(0),
/**
* <pre>
* Only match jobs in non-terminal states: PENDING, RUNNING, or
* CANCEL_PENDING.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
ACTIVE(1),
/**
* <pre>
* Only match jobs in terminal states: CANCELLED, DONE, or ERROR.
* </pre>
*
* <code>NON_ACTIVE = 2;</code>
*/
NON_ACTIVE(2),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Match all jobs, regardless of state.
* </pre>
*
* <code>ALL = 0;</code>
*/
public static final int ALL_VALUE = 0;
/**
* <pre>
* Only match jobs in non-terminal states: PENDING, RUNNING, or
* CANCEL_PENDING.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
public static final int ACTIVE_VALUE = 1;
/**
* <pre>
* Only match jobs in terminal states: CANCELLED, DONE, or ERROR.
* </pre>
*
* <code>NON_ACTIVE = 2;</code>
*/
public static final int NON_ACTIVE_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static JobStateMatcher valueOf(int value) {
return forNumber(value);
}
public static JobStateMatcher forNumber(int value) {
switch (value) {
case 0: return ALL;
case 1: return ACTIVE;
case 2: return NON_ACTIVE;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<JobStateMatcher>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
JobStateMatcher> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<JobStateMatcher>() {
public JobStateMatcher findValueByNumber(int number) {
return JobStateMatcher.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.cloud.dataproc.v1.ListJobsRequest.getDescriptor().getEnumTypes().get(0);
}
private static final JobStateMatcher[] VALUES = values();
public static JobStateMatcher valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private JobStateMatcher(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher)
}
public static final int PROJECT_ID_FIELD_NUMBER = 1;
private volatile java.lang.Object projectId_;
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
projectId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public com.google.protobuf.ByteString
getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REGION_FIELD_NUMBER = 6;
private volatile java.lang.Object region_;
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
}
}
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public com.google.protobuf.ByteString
getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_;
/**
* <pre>
* Optional. The number of results to return in each response.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
private volatile java.lang.Object pageToken_;
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public com.google.protobuf.ByteString
getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CLUSTER_NAME_FIELD_NUMBER = 4;
private volatile java.lang.Object clusterName_;
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public java.lang.String getClusterName() {
java.lang.Object ref = clusterName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
clusterName_ = s;
return s;
}
}
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public com.google.protobuf.ByteString
getClusterNameBytes() {
java.lang.Object ref = clusterName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
clusterName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int JOB_STATE_MATCHER_FIELD_NUMBER = 5;
private int jobStateMatcher_;
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public int getJobStateMatcherValue() {
return jobStateMatcher_;
}
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher getJobStateMatcher() {
com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher result = com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.valueOf(jobStateMatcher_);
return result == null ? com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.UNRECOGNIZED : result;
}
public static final int FILTER_FIELD_NUMBER = 7;
private volatile java.lang.Object filter_;
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public com.google.protobuf.ByteString
getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getProjectIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, projectId_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!getClusterNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, clusterName_);
}
if (jobStateMatcher_ != com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.ALL.getNumber()) {
output.writeEnum(5, jobStateMatcher_);
}
if (!getRegionBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, region_);
}
if (!getFilterBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 7, filter_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getProjectIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, projectId_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!getClusterNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, clusterName_);
}
if (jobStateMatcher_ != com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.ALL.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(5, jobStateMatcher_);
}
if (!getRegionBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, region_);
}
if (!getFilterBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, filter_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dataproc.v1.ListJobsRequest)) {
return super.equals(obj);
}
com.google.cloud.dataproc.v1.ListJobsRequest other = (com.google.cloud.dataproc.v1.ListJobsRequest) obj;
boolean result = true;
result = result && getProjectId()
.equals(other.getProjectId());
result = result && getRegion()
.equals(other.getRegion());
result = result && (getPageSize()
== other.getPageSize());
result = result && getPageToken()
.equals(other.getPageToken());
result = result && getClusterName()
.equals(other.getClusterName());
result = result && jobStateMatcher_ == other.jobStateMatcher_;
result = result && getFilter()
.equals(other.getFilter());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER;
hash = (53 * hash) + getProjectId().hashCode();
hash = (37 * hash) + REGION_FIELD_NUMBER;
hash = (53 * hash) + getRegion().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + CLUSTER_NAME_FIELD_NUMBER;
hash = (53 * hash) + getClusterName().hashCode();
hash = (37 * hash) + JOB_STATE_MATCHER_FIELD_NUMBER;
hash = (53 * hash) + jobStateMatcher_;
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.ListJobsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dataproc.v1.ListJobsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A request to list jobs in a project.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.ListJobsRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.ListJobsRequest)
com.google.cloud.dataproc.v1.ListJobsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_ListJobsRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_ListJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.ListJobsRequest.class, com.google.cloud.dataproc.v1.ListJobsRequest.Builder.class);
}
// Construct using com.google.cloud.dataproc.v1.ListJobsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
projectId_ = "";
region_ = "";
pageSize_ = 0;
pageToken_ = "";
clusterName_ = "";
jobStateMatcher_ = 0;
filter_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.dataproc.v1.JobsProto.internal_static_google_cloud_dataproc_v1_ListJobsRequest_descriptor;
}
public com.google.cloud.dataproc.v1.ListJobsRequest getDefaultInstanceForType() {
return com.google.cloud.dataproc.v1.ListJobsRequest.getDefaultInstance();
}
public com.google.cloud.dataproc.v1.ListJobsRequest build() {
com.google.cloud.dataproc.v1.ListJobsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.cloud.dataproc.v1.ListJobsRequest buildPartial() {
com.google.cloud.dataproc.v1.ListJobsRequest result = new com.google.cloud.dataproc.v1.ListJobsRequest(this);
result.projectId_ = projectId_;
result.region_ = region_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
result.clusterName_ = clusterName_;
result.jobStateMatcher_ = jobStateMatcher_;
result.filter_ = filter_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dataproc.v1.ListJobsRequest) {
return mergeFrom((com.google.cloud.dataproc.v1.ListJobsRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataproc.v1.ListJobsRequest other) {
if (other == com.google.cloud.dataproc.v1.ListJobsRequest.getDefaultInstance()) return this;
if (!other.getProjectId().isEmpty()) {
projectId_ = other.projectId_;
onChanged();
}
if (!other.getRegion().isEmpty()) {
region_ = other.region_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
if (!other.getClusterName().isEmpty()) {
clusterName_ = other.clusterName_;
onChanged();
}
if (other.jobStateMatcher_ != 0) {
setJobStateMatcherValue(other.getJobStateMatcherValue());
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dataproc.v1.ListJobsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.dataproc.v1.ListJobsRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object projectId_ = "";
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
projectId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public com.google.protobuf.ByteString
getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public Builder setProjectId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
projectId_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public Builder clearProjectId() {
projectId_ = getDefaultInstance().getProjectId();
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the Google Cloud Platform project that the job
* belongs to.
* </pre>
*
* <code>string project_id = 1;</code>
*/
public Builder setProjectIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
projectId_ = value;
onChanged();
return this;
}
private java.lang.Object region_ = "";
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public com.google.protobuf.ByteString
getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public Builder setRegion(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
region_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public Builder clearRegion() {
region_ = getDefaultInstance().getRegion();
onChanged();
return this;
}
/**
* <pre>
* Required. The Cloud Dataproc region in which to handle the request.
* </pre>
*
* <code>string region = 6;</code>
*/
public Builder setRegionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
region_ = value;
onChanged();
return this;
}
private int pageSize_ ;
/**
* <pre>
* Optional. The number of results to return in each response.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public int getPageSize() {
return pageSize_;
}
/**
* <pre>
* Optional. The number of results to return in each response.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. The number of results to return in each response.
* </pre>
*
* <code>int32 page_size = 2;</code>
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public com.google.protobuf.ByteString
getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder setPageToken(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
* <pre>
* Optional. The page token, returned by a previous call, to request the
* next page of results.
* </pre>
*
* <code>string page_token = 3;</code>
*/
public Builder setPageTokenBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
private java.lang.Object clusterName_ = "";
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public java.lang.String getClusterName() {
java.lang.Object ref = clusterName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
clusterName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public com.google.protobuf.ByteString
getClusterNameBytes() {
java.lang.Object ref = clusterName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
clusterName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public Builder setClusterName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
clusterName_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public Builder clearClusterName() {
clusterName_ = getDefaultInstance().getClusterName();
onChanged();
return this;
}
/**
* <pre>
* Optional. If set, the returned jobs list includes only jobs that were
* submitted to the named cluster.
* </pre>
*
* <code>string cluster_name = 4;</code>
*/
public Builder setClusterNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
clusterName_ = value;
onChanged();
return this;
}
private int jobStateMatcher_ = 0;
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public int getJobStateMatcherValue() {
return jobStateMatcher_;
}
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public Builder setJobStateMatcherValue(int value) {
jobStateMatcher_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher getJobStateMatcher() {
com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher result = com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.valueOf(jobStateMatcher_);
return result == null ? com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher.UNRECOGNIZED : result;
}
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public Builder setJobStateMatcher(com.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher value) {
if (value == null) {
throw new NullPointerException();
}
jobStateMatcher_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Optional. Specifies enumerated categories of jobs to list.
* (default = match ALL jobs).
* If `filter` is provided, `jobStateMatcher` will be ignored.
* </pre>
*
* <code>.google.cloud.dataproc.v1.ListJobsRequest.JobStateMatcher job_state_matcher = 5;</code>
*/
public Builder clearJobStateMatcher() {
jobStateMatcher_ = 0;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public com.google.protobuf.ByteString
getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public Builder setFilter(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
onChanged();
return this;
}
/**
* <pre>
* Optional. A filter constraining the jobs to list. Filters are
* case-sensitive and have the following syntax:
* [field = value] AND [field [= value]] ...
* where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label
* key. **value** can be `*` to match all values.
* `status.state` can be either `ACTIVE` or `NON_ACTIVE`.
* Only the logical `AND` operator is supported; space-separated items are
* treated as having an implicit `AND` operator.
* Example filter:
* status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* </pre>
*
* <code>string filter = 7;</code>
*/
public Builder setFilterBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.ListJobsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.ListJobsRequest)
private static final com.google.cloud.dataproc.v1.ListJobsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.ListJobsRequest();
}
public static com.google.cloud.dataproc.v1.ListJobsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListJobsRequest>
PARSER = new com.google.protobuf.AbstractParser<ListJobsRequest>() {
public ListJobsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListJobsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListJobsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListJobsRequest> getParserForType() {
return PARSER;
}
public com.google.cloud.dataproc.v1.ListJobsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| {
"content_hash": "1f1fa34bf8aa5974255c078513319615",
"timestamp": "",
"source": "github",
"line_count": 1592,
"max_line_length": 163,
"avg_line_length": 31.29962311557789,
"alnum_prop": 0.6257600995404282,
"repo_name": "pongad/api-client-staging",
"id": "add0a7d48813adf299769e640636c7b1c3bab4ac",
"size": "49829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generated/java/proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ListJobsRequest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "10561078"
},
{
"name": "JavaScript",
"bytes": "890945"
},
{
"name": "PHP",
"bytes": "9761909"
},
{
"name": "Python",
"bytes": "1395608"
},
{
"name": "Shell",
"bytes": "592"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<!-- begin SEO -->
<title>Teaching experience 2 - Binod Aryal</title>
<meta property="og:locale" content="en-US">
<meta property="og:site_name" content="Binod Aryal">
<meta property="og:title" content="Teaching experience 2">
<link rel="canonical" href="https://binodaryal.github.io/teaching/2015-spring-teaching-1">
<meta property="og:url" content="https://binodaryal.github.io/teaching/2015-spring-teaching-1">
<meta property="og:description" content="This is a description of a teaching experience. You can use markdown like any other post.">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2015-01-01T00:00:00-08:00">
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "Person",
"name" : "Binod Aryal",
"url" : "https://binodaryal.github.io",
"sameAs" : null
}
</script>
<!-- end SEO -->
<link href="https://binodaryal.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="Binod Aryal Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';
</script>
<!-- For all browsers -->
<link rel="stylesheet" href="https://binodaryal.github.io/assets/css/main.css">
<meta http-equiv="cleartype" content="on">
<!-- start custom head snippets -->
<link rel="apple-touch-icon" sizes="57x57" href="https://binodaryal.github.io/images/apple-touch-icon-57x57.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="60x60" href="https://binodaryal.github.io/images/apple-touch-icon-60x60.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="72x72" href="https://binodaryal.github.io/images/apple-touch-icon-72x72.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="76x76" href="https://binodaryal.github.io/images/apple-touch-icon-76x76.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="114x114" href="https://binodaryal.github.io/images/apple-touch-icon-114x114.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="120x120" href="https://binodaryal.github.io/images/apple-touch-icon-120x120.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="144x144" href="https://binodaryal.github.io/images/apple-touch-icon-144x144.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="152x152" href="https://binodaryal.github.io/images/apple-touch-icon-152x152.png?v=M44lzPylqQ">
<link rel="apple-touch-icon" sizes="180x180" href="https://binodaryal.github.io/images/apple-touch-icon-180x180.png?v=M44lzPylqQ">
<link rel="icon" type="image/png" href="https://binodaryal.github.io/images/favicon-32x32.png?v=M44lzPylqQ" sizes="32x32">
<link rel="icon" type="image/png" href="https://binodaryal.github.io/images/android-chrome-192x192.png?v=M44lzPylqQ" sizes="192x192">
<link rel="icon" type="image/png" href="https://binodaryal.github.io/images/favicon-96x96.png?v=M44lzPylqQ" sizes="96x96">
<link rel="icon" type="image/png" href="https://binodaryal.github.io/images/favicon-16x16.png?v=M44lzPylqQ" sizes="16x16">
<link rel="manifest" href="https://binodaryal.github.io/images/manifest.json?v=M44lzPylqQ">
<link rel="mask-icon" href="https://binodaryal.github.io/images/safari-pinned-tab.svg?v=M44lzPylqQ" color="#000000">
<link rel="shortcut icon" href="/images/favicon.ico?v=M44lzPylqQ">
<meta name="msapplication-TileColor" content="#000000">
<meta name="msapplication-TileImage" content="https://binodaryal.github.io/images/mstile-144x144.png?v=M44lzPylqQ">
<meta name="msapplication-config" content="https://binodaryal.github.io/images/browserconfig.xml?v=M44lzPylqQ">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="https://binodaryal.github.io/assets/css/academicons.css"/>
<script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "all" } } }); </script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML' async></script>
<!-- end custom head snippets -->
</head>
<body>
<!--[if lt IE 9]>
<div class="notice--danger align-center" style="margin: 0;">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div>
<![endif]-->
<div class="masthead">
<div class="masthead__inner-wrap">
<div class="masthead__menu">
<nav id="site-nav" class="greedy-nav">
<button><div class="navicon"></div></button>
<ul class="visible-links">
<li class="masthead__menu-item masthead__menu-item--lg"><a href="https://binodaryal.github.io/">Binod Aryal</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/year-archive/">Blog Posts</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/talks/">Talks</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/casestudies/">Case Studies</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/portfolio/">Portfolio</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/projects/">Projects</a></li>
<li class="masthead__menu-item"><a href="https://binodaryal.github.io/files/cv.pdf/">CV</a></li>
</ul>
<ul class="hidden-links hidden"></ul>
</nav>
</div>
</div>
</div>
<div id="main" role="main">
<div class="sidebar sticky">
<div itemscope itemtype="http://schema.org/Person">
<div class="author__avatar">
<img src="https://binodaryal.github.io/images/profile.png" class="author__avatar" alt="Binod Aryal">
</div>
<div class="author__content">
<h3 class="author__name">Binod Aryal</h3>
<p class="author__bio">feedback loop from the hell</p>
</div>
<div class="author__urls-wrapper">
<button class="btn btn--inverse">Follow</button>
<ul class="author__urls social-icons">
<li><a href="mailto:binodaryal21@gmail.com"><i class="fas fa-fw fa-envelope" aria-hidden="true"></i> Email</a></li>
<li><a href="https://twitter.com/binodaryal21"><i class="fab fa-fw fa-twitter-square" aria-hidden="true"></i> Twitter</a></li>
<li><a href="https://www.linkedin.com/in/binodaryal"><i class="fab fa-fw fa-linkedin" aria-hidden="true"></i> LinkedIn</a></li>
<li><a href="https://instagram.com/binod.aryal"><i class="fab fa-fw fa-instagram" aria-hidden="true"></i> Instagram</a></li>
<li><a href="https://github.com/BinodAryal"><i class="fab fa-fw fa-github" aria-hidden="true"></i> Github</a></li>
</ul>
</div>
</div>
</div>
<article class="page" itemscope itemtype="http://schema.org/CreativeWork">
<meta itemprop="headline" content="Teaching experience 2">
<meta itemprop="description" content="This is a description of a teaching experience. You can use markdown like any other post.">
<meta itemprop="datePublished" content="January 01, 2015">
<div class="page__inner-wrap">
<header>
<h1 class="page__title" itemprop="headline">Teaching experience 2
</h1>
<p> Workshop, <i>University 1, Department</i>, 2015 </p>
</header>
<section class="page__content" itemprop="text">
<p>This is a description of a teaching experience. You can use markdown like any other post.</p>
<h1 id="heading-1">Heading 1</h1>
<h1 id="heading-2">Heading 2</h1>
<h1 id="heading-3">Heading 3</h1>
</section>
<footer class="page__meta">
</footer>
<section class="page__share">
<h4 class="page__share-title">Share on</h4>
<a href="https://twitter.com/intent/tweet?text=https://binodaryal.github.io/teaching/2015-spring-teaching-1" class="btn btn--twitter" title="Share on Twitter"><i class="fab fa-twitter" aria-hidden="true"></i><span> Twitter</span></a>
<a href="https://www.facebook.com/sharer/sharer.php?u=https://binodaryal.github.io/teaching/2015-spring-teaching-1" class="btn btn--facebook" title="Share on Facebook"><i class="fab fa-facebook" aria-hidden="true"></i><span> Facebook</span></a>
<a href="https://www.linkedin.com/shareArticle?mini=true&url=https://binodaryal.github.io/teaching/2015-spring-teaching-1" class="btn btn--linkedin" title="Share on LinkedIn"><i class="fab fa-linkedin" aria-hidden="true"></i><span> LinkedIn</span></a>
</section>
<nav class="pagination">
<a href="https://binodaryal.github.io/teaching/2014-spring-teaching-1" class="pagination--pager" title="Teaching experience 1
">Previous</a>
<a href="#" class="pagination--pager disabled">Next</a>
</nav>
</div>
</article>
</div>
<div class="page__footer">
<footer>
<!-- start custom footer snippets -->
<!-- <a href="/sitemap/">Sitemap</a> -->
<!-- end custom footer snippets -->
<!--
<div class="page__footer-follow">
<ul class="social-icons">
<li><strong>Follow:</strong></li>
<li><a href="http://github.com/BinodAryal"><i class="fab fa-github" aria-hidden="true"></i> GitHub</a></li>
<li><a href="https://binodaryal.github.io/feed.xml"><i class="fa fa-fw fa-rss-square" aria-hidden="true"></i> Feed</a></li>
</ul>
</div>
-->
<div class="page__footer-copyright">© 2020 Binod Aryal. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll.</a> <a>Made with <i class="fa fa-heart" aria-hidden="true" style="color:#be1931"></i> in Kathmandu</a> </div>
</footer>
</div>
<script src="https://binodaryal.github.io/assets/js/main.min.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-61160653-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| {
"content_hash": "a8f0c5991336097eef356f0f84a6e5da",
"timestamp": "",
"source": "github",
"line_count": 389,
"max_line_length": 253,
"avg_line_length": 28.63496143958869,
"alnum_prop": 0.6280635604632373,
"repo_name": "BinodAryal/binodaryal.github.io",
"id": "42c0337d722aad5f90bd36595d60dc87bf1427d9",
"size": "11141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/teaching/2015-spring-teaching-1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17802"
},
{
"name": "HTML",
"bytes": "550189"
},
{
"name": "JavaScript",
"bytes": "208537"
},
{
"name": "Jupyter Notebook",
"bytes": "79120"
},
{
"name": "Python",
"bytes": "30186"
},
{
"name": "Ruby",
"bytes": "720"
},
{
"name": "SCSS",
"bytes": "65568"
}
],
"symlink_target": ""
} |
title: inQuiere
date: 18/09/2020
---
Comparte con tu clase de Escuela Sabática, o con tu grupo de estudio de la Biblia, algunas ideas del versículo que has memorizado y del estudio de la Biblia de esta semana, así como cualquier otro dato, observaciones y preguntas.
Plantéate con el resto del grupo las siguientes reflexiones y cómo aplicarlas en la vida real.
`¿Qué te viene a la mente cuando escuchas el término «abnegación»?`
`¿Cuál es la diferencia entre la humildad y la abnegación?`
`¿En qué sentido difieren el discipulado popular y el discipulado bíblico?`
`¿En qué se diferencia la humildad espiritual de la humildad cultural?`
`¿Cuáles serían las consecuencias para el universo si Dios hubiera empleado su divinidad guiándose por motivos egoístas?`
`¿Cómo se puede reconocer la negación del yo en el ámbito de las iglesias locales?`
`¿Con cuál de los tres llamamientos al discipulado te identificas?`
`¿Cuál de los tres llamados das la impresión de evitar?`
`¿En qué sentido la abnegación parece coincidir con el discipulado?`
| {
"content_hash": "34337244c85985f89aaef28e04224fdb",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 229,
"avg_line_length": 42.08,
"alnum_prop": 0.7804182509505704,
"repo_name": "imasaru/sabbath-school-lessons",
"id": "70c126afba75aa4d657a058e58f4aba1c3409a40",
"size": "1092",
"binary": false,
"copies": "2",
"ref": "refs/heads/stage",
"path": "src/es/2020-03-cq/12/07.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "160533"
},
{
"name": "HTML",
"bytes": "20725"
},
{
"name": "JavaScript",
"bytes": "54661"
}
],
"symlink_target": ""
} |
#include "SkCachingPixelRef.h"
#include "SkBitmapCache.h"
#include "SkRect.h"
bool SkCachingPixelRef::Install(SkImageGenerator* generator,
SkBitmap* dst) {
SkImageInfo info;
SkASSERT(dst != NULL);
if ((NULL == generator)
|| !(generator->getInfo(&info))
|| !dst->setInfo(info)) {
SkDELETE(generator);
return false;
}
SkAutoTUnref<SkCachingPixelRef> ref(SkNEW_ARGS(SkCachingPixelRef,
(info, generator, dst->rowBytes())));
dst->setPixelRef(ref);
return true;
}
SkCachingPixelRef::SkCachingPixelRef(const SkImageInfo& info,
SkImageGenerator* generator,
size_t rowBytes)
: INHERITED(info)
, fImageGenerator(generator)
, fErrorInDecoding(false)
, fRowBytes(rowBytes) {
SkASSERT(fImageGenerator != NULL);
}
SkCachingPixelRef::~SkCachingPixelRef() {
SkDELETE(fImageGenerator);
// Assert always unlock before unref.
}
bool SkCachingPixelRef::onNewLockPixels(LockRec* rec) {
if (fErrorInDecoding) {
return false; // don't try again.
}
const SkImageInfo& info = this->info();
if (!SkBitmapCache::Find(
this->getGenerationID(), info.bounds(), &fLockedBitmap)) {
// Cache has been purged, must re-decode.
if (!fLockedBitmap.tryAllocPixels(info, fRowBytes)) {
fErrorInDecoding = true;
return false;
}
const SkImageGenerator::Result result = fImageGenerator->getPixels(info,
fLockedBitmap.getPixels(), fRowBytes);
switch (result) {
case SkImageGenerator::kIncompleteInput:
case SkImageGenerator::kSuccess:
break;
default:
fErrorInDecoding = true;
return false;
}
fLockedBitmap.setImmutable();
SkBitmapCache::Add(
this->getGenerationID(), info.bounds(), fLockedBitmap);
}
// Now bitmap should contain a concrete PixelRef of the decoded image.
void* pixels = fLockedBitmap.getPixels();
SkASSERT(pixels != NULL);
rec->fPixels = pixels;
rec->fColorTable = NULL;
rec->fRowBytes = fLockedBitmap.rowBytes();
return true;
}
void SkCachingPixelRef::onUnlockPixels() {
fLockedBitmap.reset();
}
| {
"content_hash": "7568c02ee7f3a103605614dbb233030d",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 80,
"avg_line_length": 31.513157894736842,
"alnum_prop": 0.5966597077244259,
"repo_name": "scroggo/skia",
"id": "570fc6fbd78a5d75edc69d56a6bb85a673e4c375",
"size": "2538",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/lazy/SkCachingPixelRef.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "10339"
},
{
"name": "C",
"bytes": "579203"
},
{
"name": "C++",
"bytes": "25772025"
},
{
"name": "CSS",
"bytes": "2042"
},
{
"name": "Go",
"bytes": "677"
},
{
"name": "HTML",
"bytes": "24562"
},
{
"name": "Java",
"bytes": "24340"
},
{
"name": "JavaScript",
"bytes": "7593"
},
{
"name": "Lua",
"bytes": "25531"
},
{
"name": "Makefile",
"bytes": "8694"
},
{
"name": "Objective-C",
"bytes": "22720"
},
{
"name": "Objective-C++",
"bytes": "107323"
},
{
"name": "Python",
"bytes": "321701"
},
{
"name": "Shell",
"bytes": "41399"
}
],
"symlink_target": ""
} |
<?php
$piereg = get_option( 'pie_register_2' );
if(isset($_POST['notice']) && $_POST['notice'] ){
echo '<div id="message" class="updated fade"><p><strong>' . $_POST['notice'] . '.</strong></p></div>';
}
?>
<script type="text/javascript" src="<?php echo plugins_url("ckeditor/ckeditor.js",dirname(__FILE__));?>"></script>
<div id="container" class="pieregister-admin">
<div class="right_section">
<div class="notifications">
<h2><?php _e("Notifications : Registration Form",'piereg');?></h2>
<form method="post" action="">
<ul>
<li>
<div class="fields">
<h2><?php _e("Notifications to Administrator",'piereg');?></h2>
<input name="enable_admin_notifications" <?php echo ($piereg['enable_admin_notifications']=="1")?'checked="checked"':''?> type="checkbox" class="checkbox" value="1" />
<?php _e("Enable email notification to administrators",'piereg');?>
<p><?php _e("Enter a message below to receive a notification email when users submit this form.",'piereg');?></p>
</div>
</li>
<li>
<div class="fields">
<label><?php _e("Send To Email*",'piereg');?></label>
<input name="admin_sendto_email" value="<?php echo $piereg['admin_sendto_email']?>" type="text" class="input_fields" />
</div>
</li>
<li>
<div class="fields">
<label><?php _e("From Name",'piereg');?></label>
<input name="admin_from_name" value="<?php echo $piereg['admin_from_name']?>" type="text" class="input_fields2" />
</div>
</li>
<li>
<div class="fields">
<label><?php _e("From Email",'piereg');?></label>
<input name="admin_from_email" value="<?php echo $piereg['admin_from_email']?>" type="text" class="input_fields2" />
</div>
</li>
<li>
<div class="fields">
<label><?php _e("Reply To",'piereg');?></label>
<input name="admin_to_email" value="<?php echo $piereg['admin_to_email']?>" type="text" class="input_fields2" />
</div>
</li>
<li>
<div class="fields">
<label><?php _e("BCC",'piereg');?></label>
<input name="admin_bcc_email" value="<?php echo $piereg['admin_bcc_email']?>" type="text" class="input_fields" />
</div>
</li>
<li>
<div class="fields">
<label><?php _e("Subject",'piereg');?></label>
<input name="admin_subject_email" value="<?php echo $piereg['admin_subject_email']?>" type="text" class="input_fields" />
</div>
</li>
<li>
<div class="fields">
<label style="width:auto;margin-right:20px;"><?php _e("Send HTML Format",'piereg');?></label>
<div class="radio_fields">
<input type="radio" id="admin_message_email_formate_yes" name="admin_message_email_formate" value="1" <?php echo ($piereg['admin_message_email_formate'] == "1")? ' checked="checked" ' : '' ?>>
<label for="admin_message_email_formate_yes" style="float:none;"><?php _e("Yes",'piereg');?></label>
<input type="radio" id="admin_message_email_formate_no" name="admin_message_email_formate" value="0" <?php echo ($piereg['admin_message_email_formate'] == "0")? ' checked="checked" ' : '' ?>>
<label for="admin_message_email_formate_no" style="float:none;"><?php _e("No",'piereg');?></label>
</div>
</div>
</li>
<li>
<div class="fields">
<label><?php _e("Message",'piereg');?></label>
<p><strong><?php _e("Replacement Keys","piereg"); ?>:</strong>
<?php
$fields = maybe_unserialize(get_option("pie_fields"));
$replacement_fields = '';
if(sizeof($fields ) > 0)
{
foreach($fields as $pie_fields)
{
switch($pie_fields['type']) :
case 'default' :
case 'form' :
case 'submit' :
case 'username' :
case 'email' :
case 'password' :
case 'name' :
case 'pagebreak' :
case 'sectionbreak' :
case 'hidden' :
case 'captcha' :
case 'math_captcha' :
continue 2;
break;
endswitch;
if($pie_fields['type'] == "invitation")
$meta_key = "invitation_code";
else
$meta_key = "pie_".$pie_fields['type']."_".$pie_fields['id'];
$replacement_fields .= '<option value="%'.$meta_key.'%">'.ucwords($pie_fields['label']).'</option>';
}
}
?>
<select name="replacement_keys" id="replacement_keys" style="font-size:14px;">
<option value="select"><?php _e("Select",'piereg') ?></option>
<optgroup label="<?php _e("Default Fields",'piereg') ?>">
<option value="%user_login%"><?php _e("User Name",'piereg') ?></option>
<option value="%user_email%"><?php _e("User E-mail",'piereg') ?></option>
<option value="%firstname%"><?php _e("User First Name",'piereg') ?></option>
<option value="%lastname%"><?php _e("User Last Name",'piereg') ?></option>
<option value="%user_url%"><?php _e("User URL",'piereg') ?></option>
<option value="%user_aim%"><?php _e("User AIM",'piereg') ?></option>
<option value="%user_yim%"><?php _e("User YIM",'piereg') ?></option>
<option value="%user_jabber%"><?php _e("User Jabber",'piereg') ?></option>
<option value="%user_biographical_nfo%"><?php _e("User Biographical Info",'piereg') ?></option>
<option value="%user_registration_date%"><?php _e("User Registration Date",'piereg') ?></option>
</optgroup>
<optgroup label="<?php _e("Custom Fields",'piereg') ?>">
<?php echo $replacement_fields; ?>
</optgroup>
<optgroup label="<?php _e("Other",'piereg') ?>">
<option value="%blogname%"><?php _e("Blog Name",'piereg') ?></option>
<option value="%siteurl%"><?php _e("Site URL",'piereg') ?></option>
<option value="%blogname_url%"><?php _e("Blog Name With Site URL",'piereg') ?></option>
<option value="%user_ip%"><?php _e("User IP",'piereg') ?></option>
<!--<option value="%activationurl%"><?php _e("User Activation URL",'piereg') ?></option>-->
</optgroup>
</select>
</p>
<textarea name="admin_message_email" id="piereg_text_editor"><?php echo $piereg['admin_message_email']?></textarea>
<script type="text/javascript">
var piereg = jQuery.noConflict();
CKEDITOR.replace('piereg_text_editor',{removeButtons: 'About'});
piereg(document).ready(function(){
piereg("#replacement_keys").change(function(){
CKEDITOR.instances.piereg_text_editor.insertHtml(piereg(this).val().trim());
piereg(this).val('select');
});
});
</script>
<div class="piereg_clear"></div>
</div>
</li>
<li>
<div class="fields">
<input name="action" value="pie_reg_update" type="hidden" />
<input type="hidden" name="admin_email_notification_page" value="1" />
<p class="submit"><input style="background: #464646;color: #ffffff;border: 0;cursor: pointer;padding: 5px 0px 5px 0px;margin-top: 15px;min-width: 113px;" class="submit_btn" name="Submit" value="<?php _e('Save Changes','piereg');?>" type="submit" /></p>
</div>
</li>
</ul>
</form>
</div>
</div>
</div>
| {
"content_hash": "f1a6ce15c32210bcfa186920807419f9",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 269,
"avg_line_length": 50.6219512195122,
"alnum_prop": 0.48879788002890867,
"repo_name": "fathur/denimhouse",
"id": "289a0940996b0fdaf6ba2028ad2833571e3e94f1",
"size": "8302",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "wp-content/plugins/pie-register/menus/PieRegAdminNotification.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1943679"
},
{
"name": "JavaScript",
"bytes": "3000002"
},
{
"name": "PHP",
"bytes": "12551478"
}
],
"symlink_target": ""
} |
package com.ja.smarkdown.jekyll;
import java.util.List;
import lombok.experimental.ExtensionMethod;
import org.apache.commons.lang3.StringUtils;
import com.ja.smarkdown.processing.AbstractContentDataProcessor;
import com.ja.smarkdown.processing.LineContext;
import com.ja.smarkdown.processing.MetaData;
@ExtensionMethod(StringUtils.class)
public class JekyllContentDataProcessor extends AbstractContentDataProcessor {
@Override
public void start(MetaData metaData, StringBuilder out) {
super.start(metaData, out);
List<Object> title = metaData.get("jekyll.title");
if (!title.isEmpty()) {
out.append("#").append(title.get(0));
List<Object> category = metaData.get("jekyll.category");
if (!category.isEmpty()) {
out.append(String.format(
" <span class=\"label label-info\">%s</span> ", category.get(0)));
}
out.append('\n');
}
List<Object> tags = metaData.get("jekyll.tags");
if (!tags.isEmpty()) {
for (Object tag : tags) {
out.append(String.format(
"<span class=\"label label-primary\">%s</span> ", tag));
}
out.append('\n');
}
}
@Override
public void processLine(String line, LineContext ctx) {
if (line.startsWith("{%") && line.contains("endhighlight")
&& line.endsWith("%}")) {
ctx.remove();
ctx.insertAfter("```\n");
} else if (line.startsWith("{%") && line.contains("highlight")
&& line.endsWith("%}")) {
ctx.remove();
String lang = line.substringBetween("highlight", "%}")
.trimToEmpty();
ctx.insertAfter(String.format("```%s", lang));
}
}
}
| {
"content_hash": "9194dcf8cff64d7a00b12b0c4981c7e5",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 78,
"avg_line_length": 29.32075471698113,
"alnum_prop": 0.6724581724581724,
"repo_name": "scheuchzer/smarkdown",
"id": "f2acdb1af0f7f28c73baffd288a4d240d47d4101",
"size": "1554",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "smarkdown-jekyll/src/main/java/com/ja/smarkdown/jekyll/JekyllContentDataProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "134443"
},
{
"name": "HTML",
"bytes": "57043"
},
{
"name": "Java",
"bytes": "209598"
},
{
"name": "JavaScript",
"bytes": "257920"
},
{
"name": "Shell",
"bytes": "1526"
}
],
"symlink_target": ""
} |
package org.apache.commons.chain2.base;
import java.util.Map;
import org.apache.commons.chain2.Command;
import org.apache.commons.chain2.Processing;
/**
* <p>Override any context attribute stored under the <code>key</code> with <code>value</code>.</p>
*
* @param <K> the type of keys maintained by the context associated with this catalog
* @param <V> the type of mapped values
* @param <C> Type of the context associated with this command
*
*/
public class OverrideCommand<K, V, C extends Map<K, V>> implements Command<K, V, C> {
// -------------------------------------------------------------- Properties
private K key = null;
private V value = null;
/**
* <p>Return the context attribute key for the attribute to override.</p>
* @return The context attribute key.
*/
public K getKey() {
return key;
}
/**
* <p>Set the context attribute key for the attribute to override.</p>
*
* @param key The new key
*/
public void setKey(K key) {
this.key = key;
}
/**
* <p>Return the value that should override context attribute with key <code>key</code>.</p>
* @return The value.
*/
public V getValue() {
return value;
}
/**
* <p>Set the value that should override context attribute with key <code>key</code>.</p>
*
* @param value The new value
*/
public void setValue(V value) {
this.value = value;
}
// ---------------------------------------------------------- Filter Methods
/**
* <p>Override the attribute specified by <code>key</code> with <code>value</code>.</p>
*
* @param context {@link org.apache.commons.chain2.Context} in which we are operating
*
* @return {@link Processing#CONTINUE} so that {@link Processing} will continue.
* @throws org.apache.commons.chain2.ChainException if and error occurs.
*/
public Processing execute(C context) {
if (context.containsKey(getKey())) {
context.put(getKey(), getValue());
}
return Processing.CONTINUE;
}
}
| {
"content_hash": "5290ad2f108662d0980af538685cc193",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 99,
"avg_line_length": 27.907894736842106,
"alnum_prop": 0.5827439886845828,
"repo_name": "apache/commons-chain",
"id": "31b46e4cd2911d37731321274d87237b84a8d6d0",
"size": "2922",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "base/src/main/java/org/apache/commons/chain2/base/OverrideCommand.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "15147"
},
{
"name": "Java",
"bytes": "655989"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
module.exports = function (params) {
let requestObj = ``;
return requestObj;
} | {
"content_hash": "111831870425880371a1fc8f94cbcce9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 36,
"avg_line_length": 21.5,
"alnum_prop": 0.6511627906976745,
"repo_name": "joshua1/ajCity",
"id": "e3ab6b171bbfa95b4c88aecbba1cd79265d6fd07",
"size": "86",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/backendModules/sabre_objects/soap/itinRead.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "68833"
},
{
"name": "HTML",
"bytes": "147"
},
{
"name": "JavaScript",
"bytes": "625388"
},
{
"name": "Vue",
"bytes": "97400"
}
],
"symlink_target": ""
} |
<?php
// Copyright (c) 2012 - 2014 Pulse Storm LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//in progress, use at your own risk
if (!defined('DS')) define('DS','/');
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
date_default_timezone_set('America/Los_Angeles');
require_once 'magento-tar-to-connect/Archive/Helper/File.php';
require_once 'magento-tar-to-connect/Archive/Interface.php';
require_once 'magento-tar-to-connect/Archive/Abstract.php';
require_once 'magento-tar-to-connect/Archive/Tar.php';
require_once 'magento-tar-to-connect/Exception.php';
/**
* Still a lot of Magento users stuck on systems with 5.2, no no namespaces
* @todo but we're using anonymous functions below, so this won't work with
* 5.2 -- do we want this as a class, or a single file namespaced module?
*/
class Pulsestorm_MagentoTarToConnect
{
static public $verbose=true;
//from http://php.net/glob
// Does not support flag GLOB_BRACE
static public function globRecursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, self::globRecursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
static public function input($string)
{
self::output($string);
self::output('] ','');
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fclose($handle);
return $line;
}
static public function output($string, $newline="\n")
{
if(!self::$verbose)
{
return;
}
echo $string,$newline;
}
static public function error($string)
{
self::output("ERROR: " . $string);
self::output("Execution halted at " . __FILE__ . '::' . __LINE__);
exit;
}
static public function createPackageXmlAddNode($xml, $full_dir, $base_dir=false)
{
$parts = explode("/",str_replace($base_dir.'/','',$full_dir));
$single_file = array_pop($parts);
$node = $xml;
foreach($parts as $part)
{
$nodes = $node->xpath("dir[@name='".$part."']");
if(count($nodes) > 0)
{
$node = array_pop($nodes);
}
else
{
$node = $node->addChild('dir');
$node->addAttribute('name', $part);
}
}
$node = $node->addChild('file');
$node->addAttribute('name',$single_file);
$node->addAttribute('hash',md5_file($full_dir));
}
static public function createPackageXml($files, $base_dir, $config)
{
$xml = simplexml_load_string('<package/>');
$xml->name = $config['extension_name'];
$xml->version = $config['extension_version'];
$xml->stability = $config['stability'];
$xml->license = $config['license'];
$xml->channel = $config['channel'];
$xml->extends = '';
$xml->summary = $config['summary'];
$xml->description = $config['description'];
$xml->notes = $config['notes'];
$authors = $xml->addChild('authors');
foreach (self::getAuthorData($config) as $oneAuthor) {
$author = $authors->addChild('author');
$author->name = $oneAuthor['author_name'];
$author->user = $oneAuthor['author_user'];
$author->email = $oneAuthor['author_email'];
}
$xml->date = date('Y-m-d');
$xml->time = date('G:i:s');
$xml->compatible = '';
$dependencies = $xml->addChild('dependencies');
$required = $dependencies->addChild('required');
$php = $required->addChild('php');
$php->min = $config['php_min']; //'5.2.0';
$php->max = $config['php_max']; //'6.0.0';
// add php extension dependencies
if (is_array($config['extensions'])) {
foreach ($config['extensions'] as $extinfo) {
$extension = $required->addChild('extension');
if (is_array($extinfo)) {
$extension->name = $extinfo['name'];
$extension->min = isset($extinfo['min']) ? $extinfo['min'] : "";
$extension->max = isset($extinfo['max']) ? $extinfo['max'] : "";
} else {
$extension->name = $extinfo;
$extension->min = "";
$extension->max = "";
}
}
}
$node = $xml->addChild('contents');
$node = $node->addChild('target');
$node->addAttribute('name', 'mage');
// $files = $this->recursiveGlob($temp_dir);
// $files = array_unique($files);
$temp_dir = false;
foreach($files as $file)
{
//$this->addFileNode($node,$temp_dir,$file);
self::createPackageXmlAddNode($node, $file, $base_dir);
}
//file_put_contents($temp_dir . '/package.xml', $xml->asXml());
return $xml->asXml();
}
static public function getTempDir()
{
$name = tempnam(sys_get_temp_dir(),'tmp');
unlink($name);
$name = $name;
mkdir($name,0777,true);
return $name;
}
static public function validateConfig($config)
{
$keys = array('base_dir','archive_files','path_output',
);
foreach($keys as $key)
{
if(!array_key_exists($key, $config))
{
self::error("Config file missing key [$key]");
}
}
if($config['author_email'] == 'foo@example.com')
{
$email = self::input("Email Address is configured with foo@example.com. Enter a new address");
if(trim($email) != '')
{
$config['author_email'] = trim($email);
}
}
if(!array_key_exists('extensions', $config))
{
$config['extensions'] = null;
}
return $config;
}
static public function loadConfig($config_name=false)
{
if(!$config_name)
{
$config_name = basename(__FILE__,'php') . 'config.php';
}
if(!file_exists($config_name))
{
self::error("Could not find $config_name. Create this file, or pass in an alternate");
}
$config = include $config_name;
$config = self::validateConfig($config);
return $config;
}
static public function getModuleVersion($files)
{
$configs = array();
foreach($files as $file)
{
if(basename($file) == 'config.xml')
{
$configs[] = $file;
}
}
foreach($configs as $file)
{
$xml = simplexml_load_file($file);
$version_strings = $xml->xpath('//version');
foreach($version_strings as $version)
{
$version = (string) $version;
if(!empty($version))
{
return (string)$version;
}
}
}
foreach($configs as $file)
{
$xml = simplexml_load_file($file);
$modules = $xml->xpath('//modules');
foreach($modules[0] as $module)
{
$version = (string)$module->version;
if(!empty($version))
{
return $version;
}
}
}
}
static public function checkModuleVersionVsPackageVersion($files, $extension_version)
{
$configs = array();
foreach($files as $file)
{
if(basename($file) == 'config.xml')
{
$configs[] = $file;
}
}
foreach($configs as $file)
{
$xml = simplexml_load_file($file);
$version_strings = $xml->xpath('//version');
foreach($version_strings as $version)
{
if($version != $extension_version)
{
self::error(
"Extension Version [$extension_version] does not match " .
"module version [$version] found in a config.xml file. Add " .
"'skip_version_compare' => true to configuration to skip this check."
);
}
}
}
}
static public function buildExtensionFromConfig($config)
{
ob_start();
# extract and validate config values
$base_dir = $config['base_dir']; //'/Users/alanstorm/Documents/github/Pulsestorm/var/build';
if($base_dir['0'] !== '/')
{
$base_dir = getcwd() . '/' . $base_dir;
}
$archive_files = $config['archive_files']; //'Pulsestorm_Modulelist.tar';
$path_output = $config['path_output']; //'/Users/alanstorm/Desktop/working';
$archive_connect = $config['extension_name'] . '-' . $config['extension_version'] . '.tgz';
###--------------------------------------------------
# make sure the archive we're creating exists
if(!file_exists($base_dir . '/' . $archive_files))
{
self::error('Can\'t find specified archive, bailing' . "\n[" . $base_dir . '/' . $archive_files.']');
exit;
}
###--------------------------------------------------
# create a temporary directory, move to temporary
$temp_dir = self::getTempDir();
chdir($temp_dir);
###--------------------------------------------------
# copy and extract archive
shell_exec('cp ' . $base_dir . '/' . $archive_files . ' ' . $temp_dir);
if(preg_match('/\.zip$/', $archive_files)) {
shell_exec('unzip -o ' . $temp_dir . '/' . $archive_files);
} else {
shell_exec('tar -xvf ' . $temp_dir . '/' . $archive_files);
}
shell_exec('rm ' . $temp_dir . '/' . $archive_files);
###--------------------------------------------------
# get a lsit of all the files without directories
$all = self::globRecursive($temp_dir . '/*');
$dirs = self::globRecursive($temp_dir .'/*',GLOB_ONLYDIR);
$files = array_diff($all, $dirs);
###--------------------------------------------------
# now that we've extracted the files, yoink the version number from the config
# this only works is auto_detect_version is true. Also, may not return what
# you expect if your connect extension includes multiple Magento modules
if(isset($config['auto_detect_version']) && $config['auto_detect_version'] == true)
{
$config['extension_version'] = self::getModuleVersion($files);
$archive_connect = $config['extension_name'] . '-' . $config['extension_version'] . '.tgz';
}
###--------------------------------------------------
# checks that your Magento Connect extension version matches the version of your
# modules file. Probably redundant if auto_detect_version is true
if(!$config['skip_version_compare'])
{
self::checkModuleVersionVsPackageVersion($files, $config['extension_version']);
}
###--------------------------------------------------
# creates the base extension package.xml file
$xml = self::createPackageXml($files,$temp_dir,$config);
file_put_contents($temp_dir . '/package.xml',$xml);
self::output($temp_dir);
###--------------------------------------------------
# create the base output folder if it doesn't exist
if(!is_dir($path_output))
{
mkdir($path_output, 0777, true);
}
###--------------------------------------------------
# use Magento architve to tar up the files
$archiver = new Mage_Archive_Tar;
$archiver->pack($temp_dir,$path_output.'/'.$archive_files,true);
###--------------------------------------------------
# zip up the archive
shell_exec('gzip ' . $path_output . '/' . $archive_files);
shell_exec('mv ' . $path_output . '/' . $archive_files.'.gz '.$path_output.'/' . $archive_connect);
###--------------------------------------------------
# Creating extension xml for connect using the extension name
self::createExtensionXml($files, $config, $temp_dir, $path_output);
###--------------------------------------------------
# Report on what we did
self::output('');
self::output('Build Complete');
self::output('--------------------------------------------------');
self::output( "Built tgz in $path_output\n");
self::output(
"Built XML for Connect Manager in" . "\n\n" .
" $path_output/var/connect " . "\n\n" .
"place in `/path/to/magento/var/connect to load extension in Connect Manager");
###--------------------------------------------------
return ob_get_clean();
}
static public function main($argv)
{
$this_script = array_shift($argv);
$config_file = array_shift($argv);
$config = self::loadConfig($config_file);
self::output(
self::buildExtensionFromConfig($config)
);
}
/**
* extrapolate the target module using the file absolute path
* @param string $filePath
* @return string
*/
static public function extractTarget($filePath)
{
foreach (self::getTargetMap() as $tMap) {
$pattern = '#' . $tMap['path'] . '#';
if (preg_match($pattern, $filePath)) {
return $tMap['target'];
}
}
return 'mage';
}
/**
* get target map
* @return array
*/
static public function getTargetMap()
{
return array(
array('path' => 'app/etc', 'target' => 'mageetc'),
array('path' => 'app/code/local', 'target' => 'magelocal'),
array('path' => 'app/code/community', 'target' => 'magecommunity'),
array('path' => 'app/code/core', 'target' => 'magecore'),
array('path' => 'app/design', 'target' => 'magedesign'),
array('path' => 'lib', 'target' => 'magelib'),
array('path' => 'app/locale', 'target' => 'magelocale'),
array('path' => 'media/', 'target' => 'magemedia'),
array('path' => 'skin/', 'target' => 'mageskin'),
array('path' => 'http://', 'target' => 'mageweb'),
array('path' => 'https://', 'target' => 'mageweb'),
array('path' => 'Test/', 'target' => 'magetest'),
);
}
static public function createExtensionXml($files, $config, $tempDir, $path_output)
{
$extensionPath = $tempDir . DIRECTORY_SEPARATOR . 'var/connect/';
if (!is_dir($extensionPath)) {
mkdir($extensionPath, 0777, true);
}
$extensionFileName = $extensionPath . $config['extension_name'] . '.xml';
file_put_contents($extensionFileName, self::buildExtensionXml($files, $config));
shell_exec('cp -Rf ' . $tempDir . DIRECTORY_SEPARATOR . 'var '. $path_output);
}
static public function buildExtensionXml($files, $config)
{
$xml = simplexml_load_string('<_/>');
$build_data = self::getBuildData($xml, $files, $config);
foreach ($build_data as $key => $value) {
if (is_array($value) && is_callable($key)) {
call_user_func_array($key, $value);
} else {
self::addChildNode($xml, $key, $value);
}
}
return $xml->asXml();
}
/**
* Get an array of data to build the extension xml. The array of data will contains the key necessary
* to build each node and key that are actual callback functions to be called to build sub-section of the xml.
* @param SimpleXMLElement $xml
* @param array $files
* @param array $config
* @return array
*/
static public function getBuildData(SimpleXMLElement $xml, array $files, array $config)
{
return array(
'form_key' => isset($config['form_key']) ? $config['form_key'] : uniqid(),
'_create' => isset($config['_create']) ? $config['_create'] : '',
'name' => $config['extension_name'],
'channel'=> $config['channel'],
'Pulsestorm_MagentoTarToConnect::buildVersionIdsNode' => array($xml),
'summary' => $config['summary'],
'description' => $config['description'],
'license' => $config['license'],
'license_uri' => isset($config['license_uri']) ? $config['license_uri'] : '',
'version' => $config['extension_version'],
'stability' => $config['stability'],
'notes' => $config['notes'],
'Pulsestorm_MagentoTarToConnect::buildAuthorsNode' => array($xml, $config),
'Pulsestorm_MagentoTarToConnect::buildPhpDependsNode' => array($xml, $config),
'Pulsestorm_MagentoTarToConnect::buildContentsNode' => array($xml, $files)
);
}
/**
* Remove a passed in file absolute path and return the relative path to the Magento application file context.
* @param string $file
* @return string
*/
static public function extractRelativePath($file)
{
$pattern = '/app\/etc\/|app\/code\/community\/|app\/code\/local\/|app\/design\/|lib\/|app\/locale\/|skin\/|js\//';
$relativePath = self::splitFilePath($file, $pattern);
if ($file !== $relativePath) {
return $relativePath;
}
$shellDir = 'shell';
$relativePath = self::splitFilePath($file, '/' . $shellDir . '\//');
return ($file !== $relativePath) ? $shellDir . DIRECTORY_SEPARATOR . $relativePath : $file;
}
/**
* Split a file path using the passed in pattern and file absolute path and return
* the relative path to the file.
* @param string $file
* @param string $pattern
* @return string The relative path to file
*/
static public function splitFilePath($file, $pattern)
{
$splitPath = preg_split($pattern, $file, -1);
return (count($splitPath) > 1) ? $splitPath[1] : $file;
}
/**
* Build 'contents' node including all its child nodes.
* @param SimpleXMLElement $xml
* @param array $files
* @return void
*/
static public function buildContentsNode(SimpleXMLElement $xml, array $files)
{
$node = self::addChildNode($xml, 'contents', '');
$call_backs = array(
'target' => 'Pulsestorm_MagentoTarToConnect::extractTarget',
'path' => 'Pulsestorm_MagentoTarToConnect::extractRelativePath',
'type' => 'file',
'include'=> '',
'ignore' => ''
);
$parent_nodes = array_reduce(array_keys($call_backs), function ($item, $key) use ($node) {
$item[$key] = Pulsestorm_MagentoTarToConnect::addChildNode($node, $key, '');
return $item;
});
// Adding empty node, this is a workaround for the Magento connect bug.
// When no empty nodes are added the first file is removed from the package extension.
foreach ($parent_nodes as $child_key => $child_node) {
self::addChildNode($child_node, $child_key, '');
}
foreach ($files as $file) {
foreach ($parent_nodes as $key => $child_node) {
$call_back = $call_backs[$key];
$value = ($call_back === 'file') ? $call_back : (is_callable($call_back) ? call_user_func_array($call_back, array($file)) : $call_back);
self::addChildNode($child_node, $key, $value);
}
}
}
/**
* Add a 'depends_php_min' node and a 'depends_php_max' to the passed in SimpleXMLElement class instance object.
* @param SimpleXMLElement $xml
* @param array $config
* @return void
*/
static public function buildPhpDependsNode(SimpleXMLElement $xml, array $config)
{
$data = array('depends_php_min' => 'php_min', 'depends_php_max' => 'php_max');
foreach ($data as $key => $cfg_key) {
self::addChildNode($xml, $key, $config[$cfg_key]);
}
}
/**
* Get author data, which is a combination of author data and additional authors data from the configuration.
* @param array $config
* @return array
*/
static public function getAuthorData(array $config)
{
$authorList[0] = array(
'author_name' => $config['author_name'],
'author_user' => $config['author_user'],
'author_email' => $config['author_email'],
);
if (array_key_exists('additional_authors', $config)) {
$authorList = array_merge($authorList, $config['additional_authors']);
}
return $authorList;
}
/**
* Get a specific author information by key.
* @param array $authorList
* @param string $key
* @return array
*/
static public function getAuthorInfoByKey(array $authorList, $key)
{
return array_map(function($author) use ($key) { return $author[$key]; }, $authorList);
}
/**
* Build 'authors' node including all its child nodes.
* @param SimpleXMLElement $xml
* @param array $config
* @return void
*/
static public function buildAuthorsNode(SimpleXMLElement $xml, array $config)
{
$meta = array('name' => 'author_name', 'user' => 'author_user', 'email' => 'author_email');
$authorList = self::getAuthorData($config);
$authors = self::addChildNode($xml, 'authors', '');
foreach ($meta as $key => $cfg_key) {
$parentNode = self::addChildNode($authors, $key, '');
foreach (self::getAuthorInfoByKey($authorList, $cfg_key) as $value) {
self::addChildNode($parentNode, $key, $value);
}
}
}
/**
* Build 'version_ids' node including all its child nodes.
* @param SimpleXMLElement $xml
* @return void
*/
static public function buildVersionIdsNode(SimpleXMLElement $xml)
{
$key = 'version_ids';
$parentNode = self::addChildNode($xml, $key, '');
foreach (array(2, 1) as $version) {
self::addChildNode($parentNode, $key, $version);
}
}
/**
* Add child node to a passed in SimpleXMLElement class instance object.
* @param SimpleXMLElement $context
* @param string $name
* @param string $value
* @return SimpleXMLElement
*/
static public function addChildNode(SimpleXMLElement $context, $name, $value='')
{
$child = $context->addChild($name);
if (trim($value)) {
$child->{0} = $value;
}
return $child;
}
}
if(isset($argv))
{
Pulsestorm_MagentoTarToConnect::main($argv);
}
| {
"content_hash": "b182fb3e808a46672007c2a76cd3a147",
"timestamp": "",
"source": "github",
"line_count": 642,
"max_line_length": 463,
"avg_line_length": 39.073208722741434,
"alnum_prop": 0.508710384692047,
"repo_name": "expressly/magento",
"id": "f3ed5cfee994ed7b798b0e5990552e5826a2833d",
"size": "25085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/magento-tar-to-connect.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "139293"
},
{
"name": "Shell",
"bytes": "3135"
}
],
"symlink_target": ""
} |
<div class="row">
<!--<div class="col-xs-4">
<h3>Apps: {{ currentPage }}</h3>
</div>-->
<div class="col-xs-4">
<label for="search">Search:</label>
<input ng-model="search" id="search" class="form-control" placeholder="Search">
</div>
<div class="col-xs-4">
<label for="search">Items per page:</label>
<input type="number" min="1" max="100" class="form-control" ng-model="pageSize">
</div>
</div>
<table class="row-border hover table mopsitable ng-cloak" class="table table-striped table-bordered">
<thead>
<tr>
<!-- <th></th>-->
<th>ID</th>
<th>Tasks/Instances</th>
<th>Memory</th>
<th>CPU</th>
<th>Image</th>
<th></th>
</tr>
</thead>
<tbody>
<tr dir-paginate="app in apps.apps |filter:search| itemsPerPage: pageSize">
<td>{{app.id}}</td>
<td>{{app.tasksRunning}}/{{app.instances}}</td>
<td>{{app.mem}}</td>
<td>{{app.cpus}}</td>
<td>{{app.container.docker.image}}</td>
<td>
<a class="btn btn-primary" ui-sref="appDetails({id:app.id})">Details</a>
<a class="btn btn-danger" ng-click="appKill(app.id)">Kill!</a>
</td>
</tr>
</tbody>
</table>
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="partials/dirPagination.tpl.html" ]></dir-pagination-controls>
| {
"content_hash": "bcc09c4f9f2dfde3d153441d94698d8a",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 172,
"avg_line_length": 32.833333333333336,
"alnum_prop": 0.5852066715010877,
"repo_name": "mmbash/mops.io",
"id": "bc8d3e8845aac026230e256d44bfb8521bf4afa5",
"size": "1379",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/partials/debug.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1322"
},
{
"name": "HTML",
"bytes": "16015"
},
{
"name": "JavaScript",
"bytes": "153976"
}
],
"symlink_target": ""
} |
all:
make theme.css
make theme.js
theme.css: src/3-style.css
cat src/*.css > theme.css
theme.js: src/main.coffee
browserify -t coffeeify src/main.coffee > theme.js
| {
"content_hash": "f70457ef81ef83ca842a8b8c345dc689",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 51,
"avg_line_length": 18.88888888888889,
"alnum_prop": 0.7235294117647059,
"repo_name": "websitesfortrello/classless",
"id": "4677fecf8fd883e33dffe0f73f8b6b32bfcf4005",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "themes/ghostwriter/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "409693"
},
{
"name": "CoffeeScript",
"bytes": "6121"
},
{
"name": "HTML",
"bytes": "77963"
},
{
"name": "JavaScript",
"bytes": "763837"
},
{
"name": "Makefile",
"bytes": "3074"
},
{
"name": "Shell",
"bytes": "784"
}
],
"symlink_target": ""
} |
package cfvbaibai.cardfantasy.engine.skill;
import java.util.ArrayList;
import java.util.List;
import cfvbaibai.cardfantasy.GameUI;
import cfvbaibai.cardfantasy.data.Skill;
import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.CardStatusType;
import cfvbaibai.cardfantasy.engine.HeroDieSignal;
import cfvbaibai.cardfantasy.engine.OnAttackBlockingResult;
import cfvbaibai.cardfantasy.engine.Player;
import cfvbaibai.cardfantasy.engine.SkillResolver;
public final class Destroy {
public static void apply(SkillResolver resolver, Skill cardSkill, CardInfo attacker, Player defenderHero,
int victimCount) throws HeroDieSignal {
List<CardInfo> victims = resolver.getStage().getRandomizer().pickRandom(
defenderHero.getField().toList(), victimCount, true, null);
apply(resolver, cardSkill, attacker, victims,true);
}
public static void apply(SkillResolver resolver, Skill cardSkill, CardInfo attacker, CardInfo defender) throws HeroDieSignal {
List<CardInfo> victims = new ArrayList<CardInfo>();
victims.add(defender);
apply(resolver, cardSkill, attacker, victims,false);
}
private static void apply(SkillResolver resolver, Skill cardSkill, CardInfo attacker, List<CardInfo> victims,boolean activeSkillFlag) throws HeroDieSignal {
GameUI ui = resolver.getStage().getUI();
ui.useSkill(attacker, victims, cardSkill, true);
for (CardInfo victim : victims) {
OnAttackBlockingResult result = resolver.resolveAttackBlockingSkills(attacker, victim, cardSkill, 1);
if (!result.isAttackable()) {
continue;
}
if(activeSkillFlag)
{
int magicEchoSkillResult = resolver.resolveMagicEchoSkill(attacker, victim, cardSkill);
if (magicEchoSkillResult==1||magicEchoSkillResult==2) {
if(attacker.isDead())
{
if (magicEchoSkillResult == 1) {
continue;
}
}
else{
OnAttackBlockingResult result2 = resolver.resolveAttackBlockingSkills(victim, attacker, cardSkill, 1);
if (!result2.isAttackable()) {
if (magicEchoSkillResult == 1) {
continue;
}
}
else{
ui.killCard(victim, attacker, cardSkill);
attacker.removeStatus(CardStatusType.不屈);
resolver.killCard(victim, attacker, cardSkill);
}
}
if (magicEchoSkillResult == 1) {
continue;
}
}
}
ui.killCard(attacker, victim, cardSkill);
victim.removeStatus(CardStatusType.不屈);
resolver.killCard(attacker, victim, cardSkill);
}
}
}
| {
"content_hash": "be0dc7c10254c0c55d7f3cd518651c12",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 160,
"avg_line_length": 44.4,
"alnum_prop": 0.5871943371943372,
"repo_name": "cfvbaibai/CardFantasy",
"id": "f9aef673377bbb9e964e57b5036b6f8169bac134",
"size": "3116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workspace/CardFantasyCore/src/cfvbaibai/cardfantasy/engine/skill/Destroy.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "23030"
},
{
"name": "Java",
"bytes": "2336952"
},
{
"name": "JavaScript",
"bytes": "152792"
},
{
"name": "XSLT",
"bytes": "4030"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.ipc;
import java.io.IOException;
import java.net.InetAddress;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.io.ByteBufferPool;
import org.apache.hadoop.hbase.ipc.RpcServer.CallCleanup;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.BlockingService;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.Descriptors.MethodDescriptor;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.Message;
import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.RequestHeader;
import org.apache.htrace.TraceInfo;
/**
* Datastructure that holds all necessary to a method invocation and then afterward, carries the
* result.
*/
@InterfaceAudience.Private
class SimpleServerCall extends ServerCall<SimpleServerRpcConnection> {
final SimpleRpcServerResponder responder;
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NULL_ON_SOME_PATH",
justification = "Can't figure why this complaint is happening... see below")
SimpleServerCall(int id, final BlockingService service, final MethodDescriptor md,
RequestHeader header, Message param, CellScanner cellScanner,
SimpleServerRpcConnection connection, long size, TraceInfo tinfo,
final InetAddress remoteAddress, long receiveTime, int timeout, ByteBufferPool reservoir,
CellBlockBuilder cellBlockBuilder, CallCleanup reqCleanup, SimpleRpcServerResponder responder) {
super(id, service, md, header, param, cellScanner, connection, size, tinfo, remoteAddress,
receiveTime, timeout, reservoir, cellBlockBuilder, reqCleanup);
this.responder = responder;
}
/**
* Call is done. Execution happened and we returned results to client. It is now safe to cleanup.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "IS2_INCONSISTENT_SYNC",
justification = "Presume the lock on processing request held by caller is protection enough")
@Override
public void done() {
super.done();
this.getConnection().decRpcCount(); // Say that we're done with this call.
}
@Override
public synchronized void sendResponseIfReady() throws IOException {
// set param null to reduce memory pressure
this.param = null;
this.responder.doRespond(getConnection(), this);
}
SimpleServerRpcConnection getConnection() {
return this.connection;
}
}
| {
"content_hash": "d7015682cdfe9395277d193b1428c009",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 102,
"avg_line_length": 41.186440677966104,
"alnum_prop": 0.7744855967078189,
"repo_name": "vincentpoon/hbase",
"id": "5a26c05b46519a53f55e0867d86dc36bf4900836",
"size": "3236",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/SimpleServerCall.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25288"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "36698"
},
{
"name": "Groovy",
"bytes": "12570"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "31964465"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Python",
"bytes": "88324"
},
{
"name": "Ruby",
"bytes": "548003"
},
{
"name": "Scala",
"bytes": "442819"
},
{
"name": "Shell",
"bytes": "182224"
},
{
"name": "Thrift",
"bytes": "41524"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
package org.apache.beam.sdk.transforms;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.coders.CoderRegistry;
import org.apache.beam.sdk.coders.CustomCoder;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.transforms.Combine.AccumulatingCombineFn;
import org.apache.beam.sdk.transforms.Combine.AccumulatingCombineFn.Accumulator;
import org.apache.beam.sdk.transforms.Combine.PerKey;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.util.NameUtils;
import org.apache.beam.sdk.util.NameUtils.NameOverride;
import org.apache.beam.sdk.util.common.ElementByteSizeObserver;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
/**
* {@code PTransform}s for finding the largest (or smallest) set
* of elements in a {@code PCollection}, or the largest (or smallest)
* set of values associated with each key in a {@code PCollection} of
* {@code KV}s.
*/
public class Top {
private Top() {
// do not instantiate
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<T>} and returns a {@code PCollection<List<T>>} with a
* single element containing the largest {@code count} elements of the input
* {@code PCollection<T>}, in decreasing order, sorted using the
* given {@code Comparator<T>}. The {@code Comparator<T>} must also
* be {@code Serializable}.
*
* <p>If {@code count} {@code >} the number of elements in the
* input {@code PCollection}, then all the elements of the input
* {@code PCollection} will be in the resulting
* {@code List}, albeit in sorted order.
*
* <p>All the elements of the result's {@code List}
* must fit into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<Student> students = ...;
* PCollection<List<Student>> top10Students =
* students.apply(Top.of(10, new CompareStudentsByAvgGrade()));
* } </pre>
*
* <p>By default, the {@code Coder} of the output {@code PCollection}
* is a {@code ListCoder} of the {@code Coder} of the elements of
* the input {@code PCollection}.
*
* <p>If the input {@code PCollection} is windowed into {@link GlobalWindows},
* an empty {@code List<T>} in the {@link GlobalWindow} will be output if the input
* {@code PCollection} is empty. To use this with inputs with other windowing,
* either {@link Combine.Globally#withoutDefaults withoutDefaults} or
* {@link Combine.Globally#asSingletonView asSingletonView} must be called.
*
* <p>See also {@link #smallest} and {@link #largest}, which sort
* {@code Comparable} elements using their natural ordering.
*
* <p>See also {@link #perKey}, {@link #smallestPerKey}, and
* {@link #largestPerKey}, which take a {@code PCollection} of
* {@code KV}s and return the top values associated with each key.
*/
public static <T, ComparatorT extends Comparator<T> & Serializable>
Combine.Globally<T, List<T>> of(int count, ComparatorT compareFn) {
return Combine.globally(new TopCombineFn<>(count, compareFn));
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<T>} and returns a {@code PCollection<List<T>>} with a
* single element containing the smallest {@code count} elements of the input
* {@code PCollection<T>}, in increasing order, sorted according to
* their natural order.
*
* <p>If {@code count} {@code >} the number of elements in the
* input {@code PCollection}, then all the elements of the input
* {@code PCollection} will be in the resulting {@code PCollection}'s
* {@code List}, albeit in sorted order.
*
* <p>All the elements of the result {@code List}
* must fit into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<Integer> values = ...;
* PCollection<List<Integer>> smallest10Values = values.apply(Top.smallest(10));
* } </pre>
*
* <p>By default, the {@code Coder} of the output {@code PCollection}
* is a {@code ListCoder} of the {@code Coder} of the elements of
* the input {@code PCollection}.
*
* <p>If the input {@code PCollection} is windowed into {@link GlobalWindows},
* an empty {@code List<T>} in the {@link GlobalWindow} will be output if the input
* {@code PCollection} is empty. To use this with inputs with other windowing,
* either {@link Combine.Globally#withoutDefaults withoutDefaults} or
* {@link Combine.Globally#asSingletonView asSingletonView} must be called.
*
* <p>See also {@link #largest}.
*
* <p>See also {@link #of}, which sorts using a user-specified
* {@code Comparator} function.
*
* <p>See also {@link #perKey}, {@link #smallestPerKey}, and
* {@link #largestPerKey}, which take a {@code PCollection} of
* {@code KV}s and return the top values associated with each key.
*/
public static <T extends Comparable<T>> Combine.Globally<T, List<T>> smallest(int count) {
return Combine.globally(new TopCombineFn<>(count, new Smallest<T>()));
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<T>} and returns a {@code PCollection<List<T>>} with a
* single element containing the largest {@code count} elements of the input
* {@code PCollection<T>}, in decreasing order, sorted according to
* their natural order.
*
* <p>If {@code count} {@code >} the number of elements in the
* input {@code PCollection}, then all the elements of the input
* {@code PCollection} will be in the resulting {@code PCollection}'s
* {@code List}, albeit in sorted order.
*
* <p>All the elements of the result's {@code List}
* must fit into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<Integer> values = ...;
* PCollection<List<Integer>> largest10Values = values.apply(Top.largest(10));
* } </pre>
*
* <p>By default, the {@code Coder} of the output {@code PCollection}
* is a {@code ListCoder} of the {@code Coder} of the elements of
* the input {@code PCollection}.
*
* <p>If the input {@code PCollection} is windowed into {@link GlobalWindows},
* an empty {@code List<T>} in the {@link GlobalWindow} will be output if the input
* {@code PCollection} is empty. To use this with inputs with other windowing,
* either {@link Combine.Globally#withoutDefaults withoutDefaults} or
* {@link Combine.Globally#asSingletonView asSingletonView} must be called.
*
* <p>See also {@link #smallest}.
*
* <p>See also {@link #of}, which sorts using a user-specified
* {@code Comparator} function.
*
* <p>See also {@link #perKey}, {@link #smallestPerKey}, and
* {@link #largestPerKey}, which take a {@code PCollection} of
* {@code KV}s and return the top values associated with each key.
*/
public static <T extends Comparable<T>> Combine.Globally<T, List<T>> largest(int count) {
return Combine.globally(new TopCombineFn<>(count, new Largest<T>()));
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<KV<K, V>>} and returns a
* {@code PCollection<KV<K, List<V>>>} that contains an output
* element mapping each distinct key in the input
* {@code PCollection} to the largest {@code count} values
* associated with that key in the input
* {@code PCollection<KV<K, V>>}, in decreasing order, sorted using
* the given {@code Comparator<V>}. The
* {@code Comparator<V>} must also be {@code Serializable}.
*
* <p>If there are fewer than {@code count} values associated with
* a particular key, then all those values will be in the result
* mapping for that key, albeit in sorted order.
*
* <p>All the values associated with a single key must fit into the
* memory of a single machine, but there can be many more
* {@code KV}s in the resulting {@code PCollection} than can fit
* into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<KV<School, Student>> studentsBySchool = ...;
* PCollection<KV<School, List<Student>>> top10StudentsBySchool =
* studentsBySchool.apply(
* Top.perKey(10, new CompareStudentsByAvgGrade()));
* } </pre>
*
* <p>By default, the {@code Coder} of the keys of the output
* {@code PCollection} is the same as that of the keys of the input
* {@code PCollection}, and the {@code Coder} of the values of the
* output {@code PCollection} is a {@code ListCoder} of the
* {@code Coder} of the values of the input {@code PCollection}.
*
* <p>See also {@link #smallestPerKey} and {@link #largestPerKey}, which
* sort {@code Comparable<V>} values using their natural
* ordering.
*
* <p>See also {@link #of}, {@link #smallest}, and {@link #largest}, which
* take a {@code PCollection} and return the top elements.
*/
public static <K, V, ComparatorT extends Comparator<V> & Serializable>
PTransform<PCollection<KV<K, V>>, PCollection<KV<K, List<V>>>>
perKey(int count, ComparatorT compareFn) {
return Combine.perKey(new TopCombineFn<>(count, compareFn));
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<KV<K, V>>} and returns a
* {@code PCollection<KV<K, List<V>>>} that contains an output
* element mapping each distinct key in the input
* {@code PCollection} to the smallest {@code count} values
* associated with that key in the input
* {@code PCollection<KV<K, V>>}, in increasing order, sorted
* according to their natural order.
*
* <p>If there are fewer than {@code count} values associated with
* a particular key, then all those values will be in the result
* mapping for that key, albeit in sorted order.
*
* <p>All the values associated with a single key must fit into the
* memory of a single machine, but there can be many more
* {@code KV}s in the resulting {@code PCollection} than can fit
* into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<KV<String, Integer>> keyedValues = ...;
* PCollection<KV<String, List<Integer>>> smallest10ValuesPerKey =
* keyedValues.apply(Top.smallestPerKey(10));
* } </pre>
*
* <p>By default, the {@code Coder} of the keys of the output
* {@code PCollection} is the same as that of the keys of the input
* {@code PCollection}, and the {@code Coder} of the values of the
* output {@code PCollection} is a {@code ListCoder} of the
* {@code Coder} of the values of the input {@code PCollection}.
*
* <p>See also {@link #largestPerKey}.
*
* <p>See also {@link #perKey}, which sorts values using a user-specified
* {@code Comparator} function.
*
* <p>See also {@link #of}, {@link #smallest}, and {@link #largest}, which
* take a {@code PCollection} and return the top elements.
*/
public static <K, V extends Comparable<V>>
PTransform<PCollection<KV<K, V>>, PCollection<KV<K, List<V>>>>
smallestPerKey(int count) {
return Combine.perKey(new TopCombineFn<>(count, new Smallest<V>()));
}
/**
* Returns a {@code PTransform} that takes an input
* {@code PCollection<KV<K, V>>} and returns a
* {@code PCollection<KV<K, List<V>>>} that contains an output
* element mapping each distinct key in the input
* {@code PCollection} to the largest {@code count} values
* associated with that key in the input
* {@code PCollection<KV<K, V>>}, in decreasing order, sorted
* according to their natural order.
*
* <p>If there are fewer than {@code count} values associated with
* a particular key, then all those values will be in the result
* mapping for that key, albeit in sorted order.
*
* <p>All the values associated with a single key must fit into the
* memory of a single machine, but there can be many more
* {@code KV}s in the resulting {@code PCollection} than can fit
* into the memory of a single machine.
*
* <p>Example of use:
* <pre> {@code
* PCollection<KV<String, Integer>> keyedValues = ...;
* PCollection<KV<String, List<Integer>>> largest10ValuesPerKey =
* keyedValues.apply(Top.largestPerKey(10));
* } </pre>
*
* <p>By default, the {@code Coder} of the keys of the output
* {@code PCollection} is the same as that of the keys of the input
* {@code PCollection}, and the {@code Coder} of the values of the
* output {@code PCollection} is a {@code ListCoder} of the
* {@code Coder} of the values of the input {@code PCollection}.
*
* <p>See also {@link #smallestPerKey}.
*
* <p>See also {@link #perKey}, which sorts values using a user-specified
* {@code Comparator} function.
*
* <p>See also {@link #of}, {@link #smallest}, and {@link #largest}, which
* take a {@code PCollection} and return the top elements.
*/
public static <K, V extends Comparable<V>>
PerKey<K, V, List<V>>
largestPerKey(int count) {
return Combine.perKey(new TopCombineFn<>(count, new Largest<V>()));
}
/**
* A {@code Serializable} {@code Comparator} that that uses the compared elements' natural
* ordering.
*/
public static class Largest<T extends Comparable<? super T>>
implements Comparator<T>, Serializable {
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
/**
* {@code Serializable} {@code Comparator} that that uses the reverse of the compared elements'
* natural ordering.
*/
public static class Smallest<T extends Comparable<? super T>>
implements Comparator<T>, Serializable {
@Override
public int compare(T a, T b) {
return b.compareTo(a);
}
}
////////////////////////////////////////////////////////////////////////////
/**
* {@code CombineFn} for {@code Top} transforms that combines a
* bunch of {@code T}s into a single {@code count}-long
* {@code List<T>}, using {@code compareFn} to choose the largest
* {@code T}s.
*
* @param <T> type of element being compared
*/
public static class TopCombineFn<T, ComparatorT extends Comparator<T> & Serializable>
extends AccumulatingCombineFn<T, BoundedHeap<T, ComparatorT>, List<T>>
implements NameOverride {
private final int count;
private final ComparatorT compareFn;
public TopCombineFn(int count, ComparatorT compareFn) {
checkArgument(count >= 0, "count must be >= 0 (not %s)", count);
this.count = count;
this.compareFn = compareFn;
}
@Override
public String getNameOverride() {
return String.format("Top(%s)", NameUtils.approximateSimpleName(compareFn));
}
@Override
public BoundedHeap<T, ComparatorT> createAccumulator() {
return new BoundedHeap<>(count, compareFn, new ArrayList<T>());
}
@Override
public Coder<BoundedHeap<T, ComparatorT>> getAccumulatorCoder(
CoderRegistry registry, Coder<T> inputCoder) {
return new BoundedHeapCoder<>(count, compareFn, inputCoder);
}
@Override
public void populateDisplayData(DisplayData.Builder builder) {
super.populateDisplayData(builder);
builder
.add(DisplayData.item("count", count)
.withLabel("Top Count"))
.add(DisplayData.item("comparer", compareFn.getClass())
.withLabel("Record Comparer"));
}
@Override
public String getIncompatibleGlobalWindowErrorMessage() {
return "Default values are not supported in Top.[of, smallest, largest]() if the output "
+ "PCollection is not windowed by GlobalWindows. Instead, use "
+ "Top.[of, smallest, largest]().withoutDefaults() to output an empty PCollection if the"
+ " input PCollection is empty, or Top.[of, smallest, largest]().asSingletonView() to "
+ "get a PCollection containing the empty list if the input PCollection is empty.";
}
}
/**
* A heap that stores only a finite number of top elements according to its provided
* {@code Comparator}. Implemented as an {@link Accumulator} to facilitate implementation of
* {@link Top}.
*
* <p>This class is <i>not</i> safe for multithreaded use, except read-only.
*/
static class BoundedHeap<T, ComparatorT extends Comparator<T> & Serializable>
implements Accumulator<T, BoundedHeap<T, ComparatorT>, List<T>> {
/**
* A queue with smallest at the head, for quick adds.
*
* <p>Only one of asList and asQueue may be non-null.
*/
private PriorityQueue<T> asQueue;
/**
* A list in with largest first, the form of extractOutput().
*
* <p>Only one of asList and asQueue may be non-null.
*/
private List<T> asList;
/** The user-provided Comparator. */
private final ComparatorT compareFn;
/** The maximum size of the heap. */
private final int maximumSize;
/**
* Creates a new heap with the provided size, comparator, and initial elements.
*/
private BoundedHeap(int maximumSize, ComparatorT compareFn, List<T> asList) {
this.maximumSize = maximumSize;
this.asList = asList;
this.compareFn = compareFn;
}
@Override
public void addInput(T value) {
maybeAddInput(value);
}
/**
* Adds {@code value} to this heap if it is larger than any of the current elements.
* Returns {@code true} if {@code value} was added.
*/
private boolean maybeAddInput(T value) {
if (maximumSize == 0) {
// Don't add anything.
return false;
}
// If asQueue == null, then this is the first add after the latest call to the
// constructor or asList().
if (asQueue == null) {
asQueue = new PriorityQueue<>(maximumSize, compareFn);
for (T item : asList) {
asQueue.add(item);
}
asList = null;
}
if (asQueue.size() < maximumSize) {
asQueue.add(value);
return true;
} else if (compareFn.compare(value, asQueue.peek()) > 0) {
asQueue.poll();
asQueue.add(value);
return true;
} else {
return false;
}
}
@Override
public void mergeAccumulator(BoundedHeap<T, ComparatorT> accumulator) {
for (T value : accumulator.asList()) {
if (!maybeAddInput(value)) {
// If this element of accumulator does not make the top N, neither
// will the rest, which are all smaller.
break;
}
}
}
@Override
public List<T> extractOutput() {
return asList();
}
/**
* Returns the contents of this Heap as a List sorted largest-to-smallest.
*/
private List<T> asList() {
if (asList == null) {
List<T> smallestFirstList = Lists.newArrayListWithCapacity(asQueue.size());
while (!asQueue.isEmpty()) {
smallestFirstList.add(asQueue.poll());
}
asList = Lists.reverse(smallestFirstList);
asQueue = null;
}
return asList;
}
}
/**
* A {@link Coder} for {@link BoundedHeap}, using Java serialization via {@link CustomCoder}.
*/
private static class BoundedHeapCoder<T, ComparatorT extends Comparator<T> & Serializable>
extends CustomCoder<BoundedHeap<T, ComparatorT>> {
private final Coder<List<T>> listCoder;
private final ComparatorT compareFn;
private final int maximumSize;
public BoundedHeapCoder(int maximumSize, ComparatorT compareFn, Coder<T> elementCoder) {
listCoder = ListCoder.of(elementCoder);
this.compareFn = compareFn;
this.maximumSize = maximumSize;
}
@Override
public void encode(
BoundedHeap<T, ComparatorT> value, OutputStream outStream)
throws CoderException, IOException {
listCoder.encode(value.asList(), outStream);
}
@Override
public BoundedHeap<T, ComparatorT> decode(InputStream inStream)
throws CoderException, IOException {
return new BoundedHeap<>(maximumSize, compareFn, listCoder.decode(inStream));
}
@Override
public void verifyDeterministic() throws NonDeterministicException {
verifyDeterministic(this, "HeapCoder requires a deterministic list coder", listCoder);
}
@Override
public boolean isRegisterByteSizeObserverCheap(
BoundedHeap<T, ComparatorT> value) {
return listCoder.isRegisterByteSizeObserverCheap(value.asList());
}
@Override
public void registerByteSizeObserver(
BoundedHeap<T, ComparatorT> value, ElementByteSizeObserver observer)
throws Exception {
listCoder.registerByteSizeObserver(value.asList(), observer);
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof BoundedHeapCoder)) {
return false;
}
BoundedHeapCoder<?, ?> that = (BoundedHeapCoder<?, ?>) other;
return Objects.equals(this.compareFn, that.compareFn)
&& Objects.equals(this.listCoder, that.listCoder)
&& this.maximumSize == that.maximumSize;
}
@Override
public int hashCode() {
return Objects.hash(compareFn, listCoder, maximumSize);
}
}
}
| {
"content_hash": "bb26aaa2e55128217e4999f811545485",
"timestamp": "",
"source": "github",
"line_count": 574,
"max_line_length": 99,
"avg_line_length": 37.9808362369338,
"alnum_prop": 0.6618962432915921,
"repo_name": "dhalperi/incubator-beam",
"id": "99ec49bb8ef835160f639b676ba03d37fcdc8d51",
"size": "22606",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/Top.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "22449"
},
{
"name": "Java",
"bytes": "9735468"
},
{
"name": "Protocol Buffer",
"bytes": "1407"
},
{
"name": "Shell",
"bytes": "10104"
}
],
"symlink_target": ""
} |
package io.spikex.notifier.internal;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.ItemEvent;
import com.hazelcast.core.ItemListener;
import com.hazelcast.core.MapEvent;
import com.hazelcast.core.MemberAttributeEvent;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import static io.spikex.core.helper.Events.EVENT_FIELD_ID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.json.JsonObject;
/**
*
* @author cli
*/
public final class HzEventListener implements MembershipListener, EntryListener<String, JsonObject>, ItemListener<JsonObject> {
private final Logger m_logger = LoggerFactory.getLogger(HzEventListener.class);
@Override
public void entryAdded(final EntryEvent<String, JsonObject> event) {
m_logger.debug("Member: {} {} - entry added: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getKey());
}
@Override
public void entryUpdated(final EntryEvent<String, JsonObject> event) {
m_logger.debug("Member: {} {} - entry updated: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getKey());
}
@Override
public void entryRemoved(final EntryEvent<String, JsonObject> event) {
m_logger.debug("Member: {} {} - entries removed: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getKey());
}
@Override
public void entryEvicted(final EntryEvent<String, JsonObject> event) {
m_logger.debug("Member: {} {} - entries evicted: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getKey());
}
@Override
public void mapCleared(final MapEvent event) {
m_logger.debug("Member: {} {} - cleared entries: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getNumberOfEntriesAffected());
}
@Override
public void mapEvicted(final MapEvent event) {
m_logger.debug("Member: {} {} - evicted entries: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getNumberOfEntriesAffected());
}
@Override
public void itemAdded(final ItemEvent<JsonObject> event) {
m_logger.debug("Member: {} {} - item added: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getItem().getValue(EVENT_FIELD_ID));
}
@Override
public void itemRemoved(final ItemEvent<JsonObject> event) {
m_logger.debug("Member: {} {} - item removed: {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid(),
event.getItem().getValue(EVENT_FIELD_ID));
}
@Override
public void memberAdded(final MembershipEvent event) {
m_logger.debug("Member added: {} {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid());
}
@Override
public void memberRemoved(final MembershipEvent event) {
m_logger.debug("Member removed: {} {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid());
}
@Override
public void memberAttributeChanged(final MemberAttributeEvent event) {
m_logger.debug("Member attribute changed: {} {}",
event.getMember().getSocketAddress(),
event.getMember().getUuid());
}
}
| {
"content_hash": "70ed70e0cbda6107bd5ff617ba7bb9fc",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 127,
"avg_line_length": 34.91743119266055,
"alnum_prop": 0.6127167630057804,
"repo_name": "clidev/spike.x",
"id": "9f3b8a626ab4633ab617540a4ac33247f911e1ae",
"size": "4410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spikex-notifier/src/main/java/io/spikex/notifier/internal/HzEventListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5688"
},
{
"name": "C",
"bytes": "153198"
},
{
"name": "CSS",
"bytes": "41716"
},
{
"name": "Groovy",
"bytes": "7767"
},
{
"name": "HTML",
"bytes": "211606"
},
{
"name": "Java",
"bytes": "2343902"
},
{
"name": "Shell",
"bytes": "12608"
}
],
"symlink_target": ""
} |
get_metadata() {
local url="http://metadata.google.internal/computeMetadata/v1/${1}"
ret=0
curl "${url}" \
--silent --fail --show-error \
--header "Metadata-Flavor: Google" || ret=$?
if [[ "${ret}" != 0 ]]; then
echo "Failed fetching ${url}" >&2
return "${ret}"
fi
}
get_os_info() {
get_metadata "instance/guest-attributes/guestInventory/${1}"
}
get_attribute() {
get_metadata "instance/attributes/${1}"
}
################################################################################
############################## Utility functions ###############################
# Tests if the first argument is contained in the array in the second argument.
# Usage `is_contained "element" "${array[@]}"`
is_contained() {
local e;
local match="$1"
shift
for e in "$@"; do
if [[ "${e}" == "${match}" ]]; then
return 0
fi
done
return 1
}
# Retrieves the specified token to control the self-hosted runner.
function get_token() {
local method=$1
local runner_scope=$2
local token_proxy_url="$(get_attribute github-token-proxy-url)"
local cloud_run_id_token=$(get_metadata "instance/service-accounts/default/identity?audience=${token_proxy_url}")
curl --silent --fail --show-error --location \
"${token_proxy_url}/${method}" \
--header "Authorization: Bearer ${cloud_run_id_token}" \
--data-binary "{\"scope\": \"${runner_scope}\"}" \
| jq -r ".token"
}
################################################################################
| {
"content_hash": "efcbcc7735fd46c9d07dd76f0ea860a7",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 115,
"avg_line_length": 28.41509433962264,
"alnum_prop": 0.5358565737051793,
"repo_name": "iree-org/iree",
"id": "e30e195ba0ff1307255d9232aecd0f6f1ebbd085",
"size": "1967",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "build_tools/github_actions/runner/config/functions.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "23010"
},
{
"name": "Batchfile",
"bytes": "353"
},
{
"name": "C",
"bytes": "3830546"
},
{
"name": "C++",
"bytes": "8161374"
},
{
"name": "CMake",
"bytes": "899403"
},
{
"name": "Dockerfile",
"bytes": "28245"
},
{
"name": "GLSL",
"bytes": "2629"
},
{
"name": "HTML",
"bytes": "31018"
},
{
"name": "Java",
"bytes": "31697"
},
{
"name": "JavaScript",
"bytes": "18714"
},
{
"name": "MLIR",
"bytes": "5606822"
},
{
"name": "NASL",
"bytes": "3852"
},
{
"name": "PowerShell",
"bytes": "7893"
},
{
"name": "Python",
"bytes": "1143963"
},
{
"name": "Shell",
"bytes": "248374"
},
{
"name": "Starlark",
"bytes": "600260"
}
],
"symlink_target": ""
} |
<component name="DependencyValidationManager">
<scope name="FlowAbs" pattern="src[Spectaculum-Effect-FlowAbs]:*..*" />
</component> | {
"content_hash": "0b785394ecbb905704360fb7f7065544",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 73,
"avg_line_length": 44.333333333333336,
"alnum_prop": 0.7443609022556391,
"repo_name": "protyposis/Spectaculum",
"id": "5db24f28550b7268ae5998dcab65d6f677349226",
"size": "133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/scopes/FlowAbs.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "598"
},
{
"name": "GLSL",
"bytes": "43877"
},
{
"name": "HTML",
"bytes": "6418"
},
{
"name": "Java",
"bytes": "381813"
}
],
"symlink_target": ""
} |
package restorers
import (
"k8s.io/apimachinery/pkg/runtime"
api "github.com/heptio/ark/pkg/apis/ark/v1"
"github.com/heptio/ark/pkg/util/collections"
)
type namespaceRestorer struct{}
var _ ResourceRestorer = &namespaceRestorer{}
func NewNamespaceRestorer() ResourceRestorer {
return &namespaceRestorer{}
}
func (nsr *namespaceRestorer) Handles(obj runtime.Unstructured, restore *api.Restore) bool {
nsName, err := collections.GetString(obj.UnstructuredContent(), "metadata.name")
if err != nil {
return false
}
return collections.NewIncludesExcludes().
Includes(restore.Spec.IncludedNamespaces...).
Excludes(restore.Spec.ExcludedNamespaces...).
ShouldInclude(nsName)
}
func (nsr *namespaceRestorer) Prepare(obj runtime.Unstructured, restore *api.Restore, backup *api.Backup) (runtime.Unstructured, error, error) {
updated, err := resetMetadataAndStatus(obj, true)
if err != nil {
return nil, nil, err
}
metadata, err := collections.GetMap(obj.UnstructuredContent(), "metadata")
if err != nil {
return nil, nil, err
}
currentName, err := collections.GetString(obj.UnstructuredContent(), "metadata.name")
if err != nil {
return nil, nil, err
}
if newName, mapped := restore.Spec.NamespaceMapping[currentName]; mapped {
metadata["name"] = newName
}
return updated, nil, nil
}
func (nsr *namespaceRestorer) Wait() bool {
return false
}
func (nsr *namespaceRestorer) Ready(obj runtime.Unstructured) bool {
return true
}
| {
"content_hash": "26a58925011b3d3548dadd8c1397f1dc",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 144,
"avg_line_length": 24.098360655737704,
"alnum_prop": 0.7360544217687075,
"repo_name": "dgoodwin/online-archivist",
"id": "f9bb7f8d5247bee6856662388166d57a42592273",
"size": "2027",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/heptio/ark/pkg/restore/restorers/namespace_restorer.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "47020"
},
{
"name": "Makefile",
"bytes": "2078"
},
{
"name": "Python",
"bytes": "3032"
},
{
"name": "Shell",
"bytes": "1095"
}
],
"symlink_target": ""
} |
<div ng-controller="KbnTimeVisController" class="time-vis">
<h3 ng-show="config.title">{{config.title}}</h3>
<carousel interval="0">
<slide ng-if="vis.params.enable_quick" active="activeSlide.quick">
<h4 style="margin-top: 0px; margin-bottom: 2px;">
<strong><i aria-hidden="true" class="fa fa-clock-o"></i> Quick</strong>
</h4>
<div>
<select ng-model="selectedQuick" ng-options="option.display for option in quickLists" ng-change="setQuick(selectedQuick)">
</select>
</div>
</slide>
<slide ng-if="vis.params.enable_relative" active="activeSlide.relative">
<h4 style="margin-top: 0px; margin-bottom: 2px;">
<strong><i aria-hidden="true" class="fa fa-clock-o"></i> Relative</strong>
</h4>
<form ng-submit="setRelative()" class="form-inline">
<div style="display: inline-block;">
<label style="float:left;">
From:
<span ng-show="relative.preview">{{relative.preview}}</span>
<span ng-hide="relative.preview"><i>Invalid Expression</i></span>
</label>
<br>
<div class="form-group">
<input
required
ng-model="relative.count"
ng-change="formatRelative()"
greater-than="-1"
type="number"
class="form-control">
</div>
<div class="form-group">
<select
ng-model="relative.unit"
ng-options="opt.value as opt.text for opt in relativeOptions"
ng-change="formatRelative()"
class="form-control col-xs-2">
</select>
</div>
<br>
<div class="small">
<label style="float:left;">
<input
ng-model="relative.round"
ng-checked="relative.round"
ng-change="formatRelative()"
type="checkbox">
round to the {{units[relative.unit]}}
</label>
</div>
</div>
<div style="display: inline-block;">
<label style="float:left;">
To: Now
</label>
<br>
<div class="form-group">
<input type="text" disabled class="form-control" value="Now">
</div>
</div>
<div style="display: inline-block;">
<label> </label>
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary" ng-disabled="!relative.preview">
Go
</button>
</div>
</div>
</form>
</slide>
<slide ng-if="vis.params.enable_absolut" active="activeSlide.absolute">
<h4 style="margin-top: 0px; margin-bottom: 2px;">
<strong><i aria-hidden="true" class="fa fa-clock-o"></i> Absolute</strong>
</h4>
<form ng-submit="setAbsolute()">
<div style="display: inline-block;">
<label class="small" style="float:left;">From: <span ng-show="!time.absolute_from"><i>Invalid Date</i></span>
</label>
<input type="text" required class="form-control" input-datetime="{{format}}" ng-model="time.absolute_from">
</div>
<div style="display: inline-block;">
<label class="small" style="float:left;">To: <span ng-show="!time.absolute_to"><i>Invalid Date</i></span>
</label>
<input type="text" required class="form-control" input-datetime="{{format}}" ng-model="time.absolute_to">
</div>
<div style="display: inline-block;">
<button class="btn btn-primary" style="margin-bottom: 60px;" ng-disabled="time.absolute_from > time.absolute_to || !time.absolute_from || !time.absolute_to" type="submit">
Go
</button>
<span class="small" ng-show="time.absolute_from > time.absolute_to"><strong>From</strong> must occur before <strong>To</strong></span>
</div>
</form>
</slide>
<slide ng-if="vis.params.enable_animation">
<h4 style="margin-top: 0px; margin-bottom: 2px;">
<strong><i aria-hidden="true" class="fa fa-clock-o"></i> Time Animation</strong>
<pretty-duration class="ng-isolate-scope" to="time.to" from="time.from"></pretty-duration>
</h4>
<p>
{{animationTitle}}
</p>
<timeslider start="getStartTime()" end="getEndTime()" ticks="10" on-change="filterByTime" playback="kibanaPlayback" on-clear="removeTimeFilter" style="margin-left: 43px; margin-right: 43px;"></timeslider>
<div class="small" style="display: inline-block;">
<label style="float:left;">
round to the nearest
</label>
<select
ng-model="slider.roundUnit"
ng-options="opt.value as opt.text for opt in sliderRoundOptions"
ng-change="snapToNearest()"
style="margin-left: .4em;">
</select>
</div>
</slide>
</carousel>
</div>
| {
"content_hash": "9cf7a34528287a4495270387817568dd",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 212,
"avg_line_length": 40.4031007751938,
"alnum_prop": 0.5266692248656946,
"repo_name": "nreese/kibana-time-plugin",
"id": "fefc04af937497f86dd4e35f609fd820d718aec6",
"size": "5212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/time.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17329"
},
{
"name": "HTML",
"bytes": "6227"
},
{
"name": "JavaScript",
"bytes": "11334"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="appcompat-v7-25.3.1">
<CLASSES>
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.3.1/res" />
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.3.1/jars/classes.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://G:/AndroidSDK/extras/android/m2repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "d8cf2822d1500ca129d44c79e5731e9b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 142,
"avg_line_length": 47.75,
"alnum_prop": 0.6823734729493892,
"repo_name": "benxhinGH/Desktopet",
"id": "85f27929b6391f2854c993fe783bfdbd0604bf4b",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/appcompat_v7_25_3_1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1127"
}
],
"symlink_target": ""
} |
package eventsocket
import (
"errors"
"time"
log "github.com/dronemill/eventsocket/Godeps/_workspace/src/github.com/Sirupsen/logrus"
)
type Server struct {
Config struct {
listenAddr string
}
HttpServer *httpServer
}
// return a new, registered instance of the eventsocket server
func NewServer(listenAddr string) (server *Server, err error) {
// ensure that we have a listenAddr
if listenAddr == "" {
err = errors.New("Empty listenAddr")
log.Error("Empty listenAddr")
return
}
// instantiate new server
server = new(Server)
server.Config.listenAddr = listenAddr
registerServer(server)
return
}
func registerServer(server *Server) {
log.WithField("listenAddr", server.Config.listenAddr).Info("Registering new server")
server.HttpServer = &httpServer{}
server.HttpServer.route()
}
func (server *Server) Start() error {
log.WithField("listenAddr", server.Config.listenAddr).Info("Starting server")
go h.run()
if err := server.HttpServer.listen(server.Config.listenAddr); err != nil {
return err
}
return server.HttpServer.serve()
}
func (server *Server) Stop() error {
log.WithField("listenAddr", server.Config.listenAddr).Info("Stopping server")
return (*server.HttpServer.listener).Close()
}
// maximum message size allowed from peer
func (server *Server) SetDefaultMaxMessageSize(limit int64) {
log.WithField("listenAddr", server.Config.listenAddr).
WithField("size", limit).
Info("Setting default MaxMessageSize")
defaultMaxMessageSize = limit
}
// set the default read deadline from the peer
func (server *Server) SetDefaultReadDeadline(t time.Duration) {
log.WithField("listenAddr", server.Config.listenAddr).
WithField("duration", t.Seconds()).
Info("Setting Default ReadDeadline")
defaultReadDeadline = t
}
| {
"content_hash": "17dbb35953c202de29036f7fb0f1ab8c",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 88,
"avg_line_length": 24.63888888888889,
"alnum_prop": 0.7435174746335964,
"repo_name": "dronemill/eventsocket",
"id": "1a4afc6ea50b93c2d2b2182481f06ee9edd507a1",
"size": "1774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "27711"
},
{
"name": "HTML",
"bytes": "5569"
},
{
"name": "Shell",
"bytes": "526"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><component abstract="" loc="51:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc" nicename="BusyWaitCounterC" qname="BusyWaitCounterC">
<documentation loc="36:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc">
<short>
BusyWaitCounterC uses a Counter to implement the BusyWait interface
(block until a specified amount of time elapses).</short>
<long>
BusyWaitCounterC uses a Counter to implement the BusyWait interface
(block until a specified amount of time elapses). See TEP102 for more
details.
<p>See TEP102 for more details.
@param precision_tag A type indicating the precision of the BusyWait
interface.
@param size_type An integer type representing time values for the
BusyWait interface.
@author Cory Sharp <cssharp@eecs.berkeley.edu>
</long>
</documentation>
<parameters>
<typedef loc="51:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc" name="precision_tag" ref="0x2b6106bfb800">
<component-ref nicename="BusyWaitCounterC" qname="BusyWaitCounterC"/>
<type-var alignment="U:" size="U:"><typedef-ref name="precision_tag" ref="0x2b6106bfb800" scoped=""/></type-var>
</typedef>
<typedef loc="51:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc" name="size_type" ref="0x2b6106c52020">
<component-ref nicename="BusyWaitCounterC" qname="BusyWaitCounterC"/>
<type-var alignment="U:" size="U:"><typedef-ref name="size_type" ref="0x2b6106c52020" scoped=""/></type-var>
</typedef>
</parameters>
<module/>
<specification><interface loc="53:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc" name="BusyWait" provided="1" ref="0x2b6106c52810">
<component-ref nicename="BusyWaitCounterC" qname="BusyWaitCounterC"/>
<type-interface alignment="I:2" size="I:2"><interface-ref name="BusyWait" ref="0x2b6106c52810" scoped=""/></type-interface>
<instance>
<interfacedef-ref nicename="BusyWait" qname="BusyWait"/>
<arguments>
<type-var alignment="U:" size="U:"><typedef-ref name="precision_tag" ref="0x2b6106bfb800" scoped=""/></type-var>
<type-var alignment="U:" size="U:"><typedef-ref name="size_type" ref="0x2b6106c52020" scoped=""/></type-var>
</arguments>
</instance>
<interface-functions>
<function-ref name="wait" ref="0x2b6106c516a0" scoped=""/>
</interface-functions>
</interface><interface loc="54:/opt/tinyos-release-tinyos-2_1_2//tos/lib/timer/BusyWaitCounterC.nc" name="Counter" provided="0" ref="0x2b6106c50020">
<component-ref nicename="BusyWaitCounterC" qname="BusyWaitCounterC"/>
<type-interface alignment="I:2" size="I:2"><interface-ref name="Counter" ref="0x2b6106c50020" scoped=""/></type-interface>
<instance>
<interfacedef-ref nicename="Counter" qname="Counter"/>
<arguments>
<type-var alignment="U:" size="U:"><typedef-ref name="precision_tag" ref="0x2b6106bfb800" scoped=""/></type-var>
<type-var alignment="U:" size="U:"><typedef-ref name="size_type" ref="0x2b6106c52020" scoped=""/></type-var>
</arguments>
</instance>
<interface-functions>
<function-ref name="get" ref="0x2b6106c50e30" scoped=""/>
<function-ref name="clearOverflow" ref="0x2b6106c4f800" scoped=""/>
<function-ref name="isOverflowPending" ref="0x2b6106c4f340" scoped=""/>
<function-ref name="overflow" ref="0x2b6106c4fcc0" scoped=""/>
</interface-functions>
</interface></specification><referenced/></component> | {
"content_hash": "f6a7decef015a438a275414299dee6bc",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 175,
"avg_line_length": 60.131147540983605,
"alnum_prop": 0.6796619411123228,
"repo_name": "TinySDN/TinySDN_v0.2",
"id": "2a2c08714fe92dd6d47839188f4e056b8e8112a2",
"size": "3668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "StringNetworkTest/SensorNodeExample/doc/nesdoc/telosb/components/BusyWaitCounterC.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "19251"
},
{
"name": "CSS",
"bytes": "2044"
},
{
"name": "HTML",
"bytes": "888180"
},
{
"name": "Makefile",
"bytes": "2007"
},
{
"name": "Objective-C",
"bytes": "10648"
},
{
"name": "Shell",
"bytes": "1292"
},
{
"name": "nesC",
"bytes": "149368"
}
],
"symlink_target": ""
} |
#include "OgreStableHeaders.h"
#include "OgreCompositorChain.h"
#include "OgreCompositionTechnique.h"
#include "OgreCompositorInstance.h"
#include "OgreCompositionTargetPass.h"
#include "OgreCompositionPass.h"
#include "OgreCamera.h"
#include "OgreRenderTarget.h"
#include "OgreLogManager.h"
#include "OgreCompositorManager.h"
#include "OgreSceneManager.h"
#include "OgreRenderQueueInvocation.h"
#include "OgreMaterialManager.h"
namespace Ogre {
CompositorChain::CompositorChain(Viewport *vp):
mViewport(vp),
mOriginalScene(0),
mDirty(true),
mAnyCompositorsEnabled(false)
{
assert(vp);
mOldClearEveryFrameBuffers = vp->getClearBuffers();
vp->addListener(this);
createOriginalScene();
vp->getTarget()->addListener(this);
}
//-----------------------------------------------------------------------
CompositorChain::~CompositorChain()
{
destroyResources();
}
//-----------------------------------------------------------------------
void CompositorChain::destroyResources(void)
{
clearCompiledState();
if (mViewport)
{
mViewport->getTarget()->removeListener(this);
mViewport->removeListener(this);
removeAllCompositors();
destroyOriginalScene();
mViewport = 0;
}
}
//-----------------------------------------------------------------------
void CompositorChain::createOriginalScene()
{
/// Create "default" compositor
/** Compositor that is used to implicitly represent the original
render in the chain. This is an identity compositor with only an output pass:
compositor Ogre/Scene
{
technique
{
target_output
{
pass clear
{
/// Clear frame
}
pass render_scene
{
visibility_mask FFFFFFFF
render_queues SKIES_EARLY SKIES_LATE
}
}
}
};
*/
// If two viewports use the same scheme but differ in settings like visibility masks, shadows, etc we don't
// want compositors to share their technique. Otherwise both compositors will have to recompile every time they
// render. Thus we generate a unique compositor per viewport.
String compName("Ogre/Scene/");
compName += StringConverter::toString((intptr_t)mViewport);
mOriginalSceneScheme = mViewport->getMaterialScheme();
CompositorPtr scene = CompositorManager::getSingleton().getByName(compName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
if (scene.isNull())
{
scene = CompositorManager::getSingleton().create(compName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
CompositionTechnique *t = scene->createTechnique();
t->setSchemeName(StringUtil::BLANK);
CompositionTargetPass *tp = t->getOutputTargetPass();
tp->setVisibilityMask(0xFFFFFFFF);
{
CompositionPass *pass = tp->createPass();
pass->setType(CompositionPass::PT_CLEAR);
}
{
CompositionPass *pass = tp->createPass();
pass->setType(CompositionPass::PT_RENDERSCENE);
/// Render everything, including skies
pass->setFirstRenderQueue(RENDER_QUEUE_BACKGROUND);
pass->setLastRenderQueue(RENDER_QUEUE_SKIES_LATE);
}
/// Create base "original scene" compositor
scene = CompositorManager::getSingleton().load(compName,
ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME);
}
mOriginalScene = OGRE_NEW CompositorInstance(scene->getSupportedTechnique(), this);
}
//-----------------------------------------------------------------------
void CompositorChain::destroyOriginalScene()
{
/// Destroy "original scene" compositor instance
if (mOriginalScene)
{
OGRE_DELETE mOriginalScene;
mOriginalScene = 0;
}
}
//-----------------------------------------------------------------------
CompositorInstance* CompositorChain::addCompositor(CompositorPtr filter, size_t addPosition, const String& scheme)
{
filter->touch();
CompositionTechnique *tech = filter->getSupportedTechnique(scheme);
if(!tech)
{
/// Warn user
LogManager::getSingleton().logMessage(
"CompositorChain: Compositor " + filter->getName() + " has no supported techniques.", LML_CRITICAL
);
return 0;
}
CompositorInstance *t = OGRE_NEW CompositorInstance(tech, this);
if(addPosition == LAST)
addPosition = mInstances.size();
else
assert(addPosition <= mInstances.size() && "Index out of bounds.");
mInstances.insert(mInstances.begin()+addPosition, t);
mDirty = true;
mAnyCompositorsEnabled = true;
return t;
}
//-----------------------------------------------------------------------
void CompositorChain::removeCompositor(size_t index)
{
assert (index < mInstances.size() && "Index out of bounds.");
Instances::iterator i = mInstances.begin() + index;
OGRE_DELETE *i;
mInstances.erase(i);
mDirty = true;
}
//-----------------------------------------------------------------------
size_t CompositorChain::getNumCompositors()
{
return mInstances.size();
}
//-----------------------------------------------------------------------
void CompositorChain::removeAllCompositors()
{
Instances::iterator i, iend;
iend = mInstances.end();
for (i = mInstances.begin(); i != iend; ++i)
{
OGRE_DELETE *i;
}
mInstances.clear();
mDirty = true;
}
//-----------------------------------------------------------------------
void CompositorChain::_removeInstance(CompositorInstance *i)
{
mInstances.erase(std::find(mInstances.begin(), mInstances.end(), i));
OGRE_DELETE i;
}
//-----------------------------------------------------------------------
void CompositorChain::_queuedOperation(CompositorInstance::RenderSystemOperation* op)
{
mRenderSystemOperations.push_back(op);
}
//-----------------------------------------------------------------------
CompositorInstance *CompositorChain::getCompositor(size_t index)
{
assert (index < mInstances.size() && "Index out of bounds.");
return mInstances[index];
}
//-----------------------------------------------------------------------
CompositorInstance *CompositorChain::getCompositor(const String& name)
{
for (Instances::iterator it = mInstances.begin(); it != mInstances.end(); ++it)
{
if ((*it)->getCompositor()->getName() == name)
{
return *it;
}
}
return 0;
}
//-----------------------------------------------------------------------
CompositorChain::InstanceIterator CompositorChain::getCompositors()
{
return InstanceIterator(mInstances.begin(), mInstances.end());
}
//-----------------------------------------------------------------------
void CompositorChain::setCompositorEnabled(size_t position, bool state)
{
CompositorInstance* inst = getCompositor(position);
if (!state && inst->getEnabled())
{
// If we're disabling a 'middle' compositor in a chain, we have to be
// careful about textures which might have been shared by non-adjacent
// instances which have now become adjacent.
CompositorInstance* nextInstance = getNextInstance(inst, true);
if (nextInstance)
{
CompositionTechnique::TargetPassIterator tpit = nextInstance->getTechnique()->getTargetPassIterator();
while(tpit.hasMoreElements())
{
CompositionTargetPass* tp = tpit.getNext();
if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS)
{
if (nextInstance->getTechnique()->getTextureDefinition(tp->getOutputName())->pooled)
{
// recreate
nextInstance->freeResources(false, true);
nextInstance->createResources(false);
}
}
}
}
}
inst->setEnabled(state);
}
//-----------------------------------------------------------------------
void CompositorChain::preRenderTargetUpdate(const RenderTargetEvent& evt)
{
/// Compile if state is dirty
if(mDirty)
_compile();
// Do nothing if no compositors enabled
if (!mAnyCompositorsEnabled)
{
return;
}
/// Update dependent render targets; this is done in the preRenderTarget
/// and not the preViewportUpdate for a reason: at this time, the
/// target Rendertarget will not yet have been set as current.
/// ( RenderSystem::setViewport(...) ) if it would have been, the rendering
/// order would be screwed up and problems would arise with copying rendertextures.
Camera *cam = mViewport->getCamera();
if (cam)
{
cam->getSceneManager()->_setActiveCompositorChain(this);
}
/// Iterate over compiled state
CompositorInstance::CompiledState::iterator i;
for(i=mCompiledState.begin(); i!=mCompiledState.end(); ++i)
{
/// Skip if this is a target that should only be initialised initially
if(i->onlyInitial && i->hasBeenRendered)
continue;
i->hasBeenRendered = true;
/// Setup and render
preTargetOperation(*i, i->target->getViewport(0), cam);
i->target->update();
postTargetOperation(*i, i->target->getViewport(0), cam);
}
}
//-----------------------------------------------------------------------
void CompositorChain::postRenderTargetUpdate(const RenderTargetEvent& evt)
{
Camera *cam = mViewport->getCamera();
if (cam)
{
cam->getSceneManager()->_setActiveCompositorChain(0);
}
}
//-----------------------------------------------------------------------
void CompositorChain::preViewportUpdate(const RenderTargetViewportEvent& evt)
{
// Only set up if there is at least one compositor enabled, and it's this viewport
if(evt.source != mViewport || !mAnyCompositorsEnabled)
return;
// set original scene details from viewport
CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0);
CompositionTargetPass* passParent = pass->getParent();
if (pass->getClearBuffers() != mViewport->getClearBuffers() ||
pass->getClearColour() != mViewport->getBackgroundColour() ||
pass->getClearDepth() != mViewport->getDepthClear() ||
passParent->getVisibilityMask() != mViewport->getVisibilityMask() ||
passParent->getMaterialScheme() != mViewport->getMaterialScheme() ||
passParent->getShadowsEnabled() != mViewport->getShadowsEnabled())
{
// recompile if viewport settings are different
pass->setClearBuffers(mViewport->getClearBuffers());
pass->setClearColour(mViewport->getBackgroundColour());
pass->setClearDepth(mViewport->getDepthClear());
passParent->setVisibilityMask(mViewport->getVisibilityMask());
passParent->setMaterialScheme(mViewport->getMaterialScheme());
passParent->setShadowsEnabled(mViewport->getShadowsEnabled());
_compile();
}
Camera *cam = mViewport->getCamera();
if (cam)
{
/// Prepare for output operation
preTargetOperation(mOutputOperation, mViewport, cam);
}
}
//-----------------------------------------------------------------------
void CompositorChain::preTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam)
{
if (cam)
{
SceneManager *sm = cam->getSceneManager();
/// Set up render target listener
mOurListener.setOperation(&op, sm, sm->getDestinationRenderSystem());
mOurListener.notifyViewport(vp);
/// Register it
sm->addRenderQueueListener(&mOurListener);
/// Set visiblity mask
mOldVisibilityMask = sm->getVisibilityMask();
sm->setVisibilityMask(op.visibilityMask);
/// Set whether we find visibles
mOldFindVisibleObjects = sm->getFindVisibleObjects();
sm->setFindVisibleObjects(op.findVisibleObjects);
/// Set LOD bias level
mOldLodBias = cam->getLodBias();
cam->setLodBias(cam->getLodBias() * op.lodBias);
}
/// Set material scheme
mOldMaterialScheme = vp->getMaterialScheme();
vp->setMaterialScheme(op.materialScheme);
/// Set shadows enabled
mOldShadowsEnabled = vp->getShadowsEnabled();
vp->setShadowsEnabled(op.shadowsEnabled);
/// XXX TODO
//vp->setClearEveryFrame( true );
//vp->setOverlaysEnabled( false );
//vp->setBackgroundColour( op.clearColour );
}
//-----------------------------------------------------------------------
void CompositorChain::postTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam)
{
if (cam)
{
SceneManager *sm = cam->getSceneManager();
/// Unregister our listener
sm->removeRenderQueueListener(&mOurListener);
/// Restore default scene and camera settings
sm->setVisibilityMask(mOldVisibilityMask);
sm->setFindVisibleObjects(mOldFindVisibleObjects);
cam->setLodBias(mOldLodBias);
}
vp->setMaterialScheme(mOldMaterialScheme);
vp->setShadowsEnabled(mOldShadowsEnabled);
}
//-----------------------------------------------------------------------
void CompositorChain::postViewportUpdate(const RenderTargetViewportEvent& evt)
{
// Only tidy up if there is at least one compositor enabled, and it's this viewport
if(evt.source != mViewport || !mAnyCompositorsEnabled)
return;
Camera *cam = mViewport->getCamera();
postTargetOperation(mOutputOperation, mViewport, cam);
}
//-----------------------------------------------------------------------
void CompositorChain::viewportCameraChanged(Viewport* viewport)
{
Camera* camera = viewport->getCamera();
size_t count = mInstances.size();
for (size_t i = 0; i < count; ++i)
{
mInstances[i]->notifyCameraChanged(camera);
}
}
//-----------------------------------------------------------------------
void CompositorChain::viewportDimensionsChanged(Viewport* viewport)
{
size_t count = mInstances.size();
for (size_t i = 0; i < count; ++i)
{
mInstances[i]->notifyResized();
}
}
//-----------------------------------------------------------------------
void CompositorChain::viewportDestroyed(Viewport* viewport)
{
// this chain is now orphaned. tell compositor manager to delete it.
CompositorManager::getSingleton().removeCompositorChain(viewport);
}
//-----------------------------------------------------------------------
void CompositorChain::clearCompiledState()
{
for (RenderSystemOperations::iterator i = mRenderSystemOperations.begin();
i != mRenderSystemOperations.end(); ++i)
{
OGRE_DELETE *i;
}
mRenderSystemOperations.clear();
/// Clear compiled state
mCompiledState.clear();
mOutputOperation = CompositorInstance::TargetOperation(0);
}
//-----------------------------------------------------------------------
void CompositorChain::_compile()
{
// remove original scene if it has the wrong material scheme
if( mOriginalSceneScheme != mViewport->getMaterialScheme() )
{
destroyOriginalScene();
createOriginalScene();
}
clearCompiledState();
bool compositorsEnabled = false;
// force default scheme so materials for compositor quads will determined correctly
MaterialManager& matMgr = MaterialManager::getSingleton();
String prevMaterialScheme = matMgr.getActiveScheme();
matMgr.setActiveScheme(MaterialManager::DEFAULT_SCHEME_NAME);
/// Set previous CompositorInstance for each compositor in the list
CompositorInstance *lastComposition = mOriginalScene;
mOriginalScene->mPreviousInstance = 0;
CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0);
pass->setClearBuffers(mViewport->getClearBuffers());
pass->setClearColour(mViewport->getBackgroundColour());
pass->setClearDepth(mViewport->getDepthClear());
for(Instances::iterator i=mInstances.begin(); i!=mInstances.end(); ++i)
{
if((*i)->getEnabled())
{
compositorsEnabled = true;
(*i)->mPreviousInstance = lastComposition;
lastComposition = (*i);
}
}
/// Compile misc targets
lastComposition->_compileTargetOperations(mCompiledState);
/// Final target viewport (0)
mOutputOperation.renderSystemOperations.clear();
lastComposition->_compileOutputOperation(mOutputOperation);
// Deal with viewport settings
if (compositorsEnabled != mAnyCompositorsEnabled)
{
mAnyCompositorsEnabled = compositorsEnabled;
if (mAnyCompositorsEnabled)
{
// Save old viewport clearing options
mOldClearEveryFrameBuffers = mViewport->getClearBuffers();
// Don't clear anything every frame since we have our own clear ops
mViewport->setClearEveryFrame(false);
}
else
{
// Reset clearing options
mViewport->setClearEveryFrame(mOldClearEveryFrameBuffers > 0,
mOldClearEveryFrameBuffers);
}
}
// restore material scheme
matMgr.setActiveScheme(prevMaterialScheme);
mDirty = false;
}
//-----------------------------------------------------------------------
void CompositorChain::_markDirty()
{
mDirty = true;
}
//-----------------------------------------------------------------------
Viewport *CompositorChain::getViewport()
{
return mViewport;
}
//-----------------------------------------------------------------------
void CompositorChain::RQListener::renderQueueStarted(uint8 id,
const String& invocation, bool& skipThisQueue)
{
// Skip when not matching viewport
// shadows update is nested within main viewport update
if (mSceneManager->getCurrentViewport() != mViewport)
return;
flushUpTo(id);
/// If no one wants to render this queue, skip it
/// Don't skip the OVERLAY queue because that's handled separately
if(!mOperation->renderQueues.test(id) && id!=RENDER_QUEUE_OVERLAY)
{
skipThisQueue = true;
}
}
//-----------------------------------------------------------------------
void CompositorChain::RQListener::renderQueueEnded(uint8 id,
const String& invocation, bool& repeatThisQueue)
{
}
//-----------------------------------------------------------------------
void CompositorChain::RQListener::setOperation(CompositorInstance::TargetOperation *op,SceneManager *sm,RenderSystem *rs)
{
mOperation = op;
mSceneManager = sm;
mRenderSystem = rs;
currentOp = op->renderSystemOperations.begin();
lastOp = op->renderSystemOperations.end();
}
//-----------------------------------------------------------------------
void CompositorChain::RQListener::flushUpTo(uint8 id)
{
/// Process all RenderSystemOperations up to and including render queue id.
/// Including, because the operations for RenderQueueGroup x should be executed
/// at the beginning of the RenderQueueGroup render for x.
while(currentOp != lastOp && currentOp->first <= id)
{
currentOp->second->execute(mSceneManager, mRenderSystem);
++currentOp;
}
}
//-----------------------------------------------------------------------
CompositorInstance* CompositorChain::getPreviousInstance(CompositorInstance* curr, bool activeOnly)
{
bool found = false;
for(Instances::reverse_iterator i=mInstances.rbegin(); i!=mInstances.rend(); ++i)
{
if (found)
{
if ((*i)->getEnabled() || !activeOnly)
return *i;
}
else if(*i == curr)
{
found = true;
}
}
return 0;
}
//---------------------------------------------------------------------
CompositorInstance* CompositorChain::getNextInstance(CompositorInstance* curr, bool activeOnly)
{
bool found = false;
for(Instances::iterator i=mInstances.begin(); i!=mInstances.end(); ++i)
{
if (found)
{
if ((*i)->getEnabled() || !activeOnly)
return *i;
}
else if(*i == curr)
{
found = true;
}
}
return 0;
}
//---------------------------------------------------------------------
}
| {
"content_hash": "2b8cfd172fa8e805ba25bd43b97f4379",
"timestamp": "",
"source": "github",
"line_count": 590,
"max_line_length": 129,
"avg_line_length": 32.110169491525426,
"alnum_prop": 0.6255476378991819,
"repo_name": "nezticle/ogre",
"id": "3d0a1ff4dcc6fd716dc87bf1104a8944260c9a13",
"size": "20308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OgreMain/src/OgreCompositorChain.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3380206"
},
{
"name": "C++",
"bytes": "18636914"
},
{
"name": "Objective-C",
"bytes": "439195"
},
{
"name": "Python",
"bytes": "453322"
},
{
"name": "Shell",
"bytes": "10147"
},
{
"name": "Visual Basic",
"bytes": "1095"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d64b59f5673579b0ed44a6623d395197",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "ec1cc04c16559bb9303ad166188d535a9d50db82",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Tiliaceae/Belotia/Belotia greviaefolia/Belotia greviaefolia lessertiana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/** Required classes. **/
require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php";
if (!class_exists("ApiError", false)) {
/**
* The API error base class that provides details about an error that occurred
* while processing a service request.
*
* <p>The OGNL field path is provided for parsers to identify the request data
* element that may have caused the error.</p>
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ApiError";
/**
* @access public
* @var string
*/
public $fieldPath;
/**
* @access public
* @var string
*/
public $trigger;
/**
* @access public
* @var string
*/
public $errorString;
/**
* @access public
* @var string
*/
public $ApiErrorType;
private $_parameterMap = array(
"ApiError.Type" => "ApiErrorType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("ApiVersionError", false)) {
/**
* Errors related to the usage of API versions.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ApiVersionError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ApiVersionError";
/**
* @access public
* @var tnsApiVersionErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("ApplicationException", false)) {
/**
* Base class for exceptions.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ApplicationException {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ApplicationException";
/**
* @access public
* @var string
*/
public $message;
/**
* @access public
* @var string
*/
public $ApplicationExceptionType;
private $_parameterMap = array(
"ApplicationException.Type" => "ApplicationExceptionType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($message = null, $ApplicationExceptionType = null) {
$this->message = $message;
$this->ApplicationExceptionType = $ApplicationExceptionType;
}
}
}
if (!class_exists("Authentication", false)) {
/**
* A representation of the authentication protocols that can be used.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class Authentication {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "Authentication";
/**
* @access public
* @var string
*/
public $AuthenticationType;
private $_parameterMap = array(
"Authentication.Type" => "AuthenticationType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($AuthenticationType = null) {
$this->AuthenticationType = $AuthenticationType;
}
}
}
if (!class_exists("AuthenticationError", false)) {
/**
* An error for an exception that occurred when authenticating.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class AuthenticationError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "AuthenticationError";
/**
* @access public
* @var tnsAuthenticationErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("CommonError", false)) {
/**
* A place for common errors that can be used across services.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CommonError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CommonError";
/**
* @access public
* @var tnsCommonErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("CustomTargetingError", false)) {
/**
* Lists all errors related to {@link CustomTargetingKey} and
* {@link CustomTargetingValue} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingError";
/**
* @access public
* @var tnsCustomTargetingErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("CustomTargetingKeyAction", false)) {
/**
* Represents the actions that can be performed on {@link CustomTargetingKey}
* objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingKeyAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingKeyAction";
/**
* @access public
* @var string
*/
public $CustomTargetingKeyActionType;
private $_parameterMap = array(
"CustomTargetingKeyAction.Type" => "CustomTargetingKeyActionType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($CustomTargetingKeyActionType = null) {
$this->CustomTargetingKeyActionType = $CustomTargetingKeyActionType;
}
}
}
if (!class_exists("CustomTargetingKey", false)) {
/**
* {@code CustomTargetingKey} represents a key used for custom targeting.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingKey {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingKey";
/**
* @access public
* @var integer
*/
public $id;
/**
* @access public
* @var string
*/
public $name;
/**
* @access public
* @var string
*/
public $displayName;
/**
* @access public
* @var tnsCustomTargetingKeyType
*/
public $type;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($id = null, $name = null, $displayName = null, $type = null) {
$this->id = $id;
$this->name = $name;
$this->displayName = $displayName;
$this->type = $type;
}
}
}
if (!class_exists("CustomTargetingKeyPage", false)) {
/**
* Captures a page of {@link CustomTargetingKey} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingKeyPage {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingKeyPage";
/**
* @access public
* @var integer
*/
public $totalResultSetSize;
/**
* @access public
* @var integer
*/
public $startIndex;
/**
* @access public
* @var CustomTargetingKey[]
*/
public $results;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($totalResultSetSize = null, $startIndex = null, $results = null) {
$this->totalResultSetSize = $totalResultSetSize;
$this->startIndex = $startIndex;
$this->results = $results;
}
}
}
if (!class_exists("CustomTargetingValueAction", false)) {
/**
* Represents the actions that can be performed on {@link CustomTargetingValue}
* objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingValueAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingValueAction";
/**
* @access public
* @var string
*/
public $CustomTargetingValueActionType;
private $_parameterMap = array(
"CustomTargetingValueAction.Type" => "CustomTargetingValueActionType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($CustomTargetingValueActionType = null) {
$this->CustomTargetingValueActionType = $CustomTargetingValueActionType;
}
}
}
if (!class_exists("CustomTargetingValue", false)) {
/**
* {@code CustomTargetingValue} represents a value used for custom targeting.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingValue {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingValue";
/**
* @access public
* @var integer
*/
public $customTargetingKeyId;
/**
* @access public
* @var integer
*/
public $id;
/**
* @access public
* @var string
*/
public $name;
/**
* @access public
* @var string
*/
public $displayName;
/**
* @access public
* @var tnsCustomTargetingValueMatchType
*/
public $matchType;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($customTargetingKeyId = null, $id = null, $name = null, $displayName = null, $matchType = null) {
$this->customTargetingKeyId = $customTargetingKeyId;
$this->id = $id;
$this->name = $name;
$this->displayName = $displayName;
$this->matchType = $matchType;
}
}
}
if (!class_exists("CustomTargetingValuePage", false)) {
/**
* Captures a page of {@link CustomTargetingValue} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingValuePage {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingValuePage";
/**
* @access public
* @var integer
*/
public $totalResultSetSize;
/**
* @access public
* @var integer
*/
public $startIndex;
/**
* @access public
* @var CustomTargetingValue[]
*/
public $results;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($totalResultSetSize = null, $startIndex = null, $results = null) {
$this->totalResultSetSize = $totalResultSetSize;
$this->startIndex = $startIndex;
$this->results = $results;
}
}
}
if (!class_exists("Date", false)) {
/**
* Represents a date.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class Date {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "Date";
/**
* @access public
* @var integer
*/
public $year;
/**
* @access public
* @var integer
*/
public $month;
/**
* @access public
* @var integer
*/
public $day;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($year = null, $month = null, $day = null) {
$this->year = $year;
$this->month = $month;
$this->day = $day;
}
}
}
if (!class_exists("DfpDateTime", false)) {
/**
* Represents a date combined with the time of day.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DfpDateTime {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "DateTime";
/**
* @access public
* @var Date
*/
public $date;
/**
* @access public
* @var integer
*/
public $hour;
/**
* @access public
* @var integer
*/
public $minute;
/**
* @access public
* @var integer
*/
public $second;
/**
* @access public
* @var string
*/
public $timeZoneID;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) {
$this->date = $date;
$this->hour = $hour;
$this->minute = $minute;
$this->second = $second;
$this->timeZoneID = $timeZoneID;
}
}
}
if (!class_exists("DeleteCustomTargetingKeys", false)) {
/**
* Represents the delete action that can be performed on
* {@link CustomTargetingKey} objects. Deleting a key will not delete the
* {@link CustomTargetingValue} objects associated with it. Also, if a custom
* targeting key that has been deleted is recreated, any previous custom
* targeting values associated with it that were not deleted will continue to
* exist.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DeleteCustomTargetingKeys extends CustomTargetingKeyAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "DeleteCustomTargetingKeys";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($CustomTargetingKeyActionType = null) {
parent::__construct();
$this->CustomTargetingKeyActionType = $CustomTargetingKeyActionType;
}
}
}
if (!class_exists("DeleteCustomTargetingValues", false)) {
/**
* Represents the delete action that can be performed on
* {@link CustomTargetingValue} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DeleteCustomTargetingValues extends CustomTargetingValueAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "DeleteCustomTargetingValues";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($CustomTargetingValueActionType = null) {
parent::__construct();
$this->CustomTargetingValueActionType = $CustomTargetingValueActionType;
}
}
}
if (!class_exists("FeatureError", false)) {
/**
* Errors related to feature management. If you attempt using a feature that is not available to
* the current network you'll receive a FeatureError with the missing feature as the trigger.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class FeatureError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "FeatureError";
/**
* @access public
* @var tnsFeatureErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("InternalApiError", false)) {
/**
* Indicates that a server-side error has occured. {@code InternalApiError}s
* are generally not the result of an invalid request or message sent by the
* client.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class InternalApiError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "InternalApiError";
/**
* @access public
* @var tnsInternalApiErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("NotNullError", false)) {
/**
* Caused by supplying a null value for an attribute that cannot be null.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class NotNullError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "NotNullError";
/**
* @access public
* @var tnsNotNullErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("NullError", false)) {
/**
* Errors associated with violation of a NOT NULL check.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class NullError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "NullError";
/**
* @access public
* @var tnsNullErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("DfpOAuth", false)) {
/**
* The credentials for the {@code OAuth} authentication protocol.
*
* See {@link http://oauth.net/}.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DfpOAuth extends Authentication {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "OAuth";
/**
* @access public
* @var string
*/
public $parameters;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($parameters = null, $AuthenticationType = null) {
parent::__construct();
$this->parameters = $parameters;
$this->AuthenticationType = $AuthenticationType;
}
}
}
if (!class_exists("ParseError", false)) {
/**
* Lists errors related to parsing.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ParseError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ParseError";
/**
* @access public
* @var tnsParseErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("PermissionError", false)) {
/**
* Errors related to incorrect permission.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PermissionError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PermissionError";
/**
* @access public
* @var tnsPermissionErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("PublisherQueryLanguageContextError", false)) {
/**
* An error that occurs while executing a PQL query contained in
* a {@link Statement} object.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PublisherQueryLanguageContextError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PublisherQueryLanguageContextError";
/**
* @access public
* @var tnsPublisherQueryLanguageContextErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("PublisherQueryLanguageSyntaxError", false)) {
/**
* An error that occurs while parsing a PQL query contained in a
* {@link Statement} object.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PublisherQueryLanguageSyntaxError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PublisherQueryLanguageSyntaxError";
/**
* @access public
* @var tnsPublisherQueryLanguageSyntaxErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("QuotaError", false)) {
/**
* Describes a client-side error on which a user is attempting
* to perform an action to which they have no quota remaining.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class QuotaError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "QuotaError";
/**
* @access public
* @var tnsQuotaErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("RequiredError", false)) {
/**
* Errors due to missing required field.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class RequiredError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "RequiredError";
/**
* @access public
* @var tnsRequiredErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("ServerError", false)) {
/**
* Errors related to the server.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ServerError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ServerError";
/**
* @access public
* @var tnsServerErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("SoapRequestHeader", false)) {
/**
* Represents the SOAP request header used by API requests.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class SoapRequestHeader {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "SoapRequestHeader";
/**
* @access public
* @var string
*/
public $networkCode;
/**
* @access public
* @var string
*/
public $applicationName;
/**
* @access public
* @var Authentication
*/
public $authentication;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($networkCode = null, $applicationName = null, $authentication = null) {
$this->networkCode = $networkCode;
$this->applicationName = $applicationName;
$this->authentication = $authentication;
}
}
}
if (!class_exists("SoapResponseHeader", false)) {
/**
* Represents the SOAP request header used by API responses.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class SoapResponseHeader {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "SoapResponseHeader";
/**
* @access public
* @var string
*/
public $requestId;
/**
* @access public
* @var integer
*/
public $responseTime;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($requestId = null, $responseTime = null) {
$this->requestId = $requestId;
$this->responseTime = $responseTime;
}
}
}
if (!class_exists("Statement", false)) {
/**
* Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a
* PQL query. Statements are typically used to retrieve objects of a predefined
* domain type, which makes SELECT clause unnecessary.
* <p>
* An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id
* LIMIT 30"}.
* </p>
* <p>
* Statements support bind variables. These are substitutes for literals
* and can be thought of as input parameters to a PQL query.
* </p>
* <p>
* An example of such a query might be {@code "WHERE id = :idValue"}.
* </p>
* <p>
* Statements also support use of the LIKE keyword. This provides partial and
* wildcard string matching.
* </p>
* <p>
* An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}.
* </p>
* If using an API version newer than V201010, the value for the variable
* idValue must then be set with an object of type {@link Value} and is one of
* {@link NumberValue}, {@link TextValue} or {@link BooleanValue}.
* <p>
* If using an API version older than or equal to V201010, the value for the
* variable idValue must then be set with an object of type {@link Param} and is
* one of {@link DoubleParam}, {@link LongParam} or {@link StringParam}.
* </p>
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class Statement {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "Statement";
/**
* @access public
* @var string
*/
public $query;
/**
* @access public
* @var String_ValueMapEntry[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($query = null, $values = null) {
$this->query = $query;
$this->values = $values;
}
}
}
if (!class_exists("StatementError", false)) {
/**
* An error that occurs while parsing {@link Statement} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class StatementError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "StatementError";
/**
* @access public
* @var tnsStatementErrorReason
*/
public $reason;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->reason = $reason;
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("String_ValueMapEntry", false)) {
/**
* This represents an entry in a map with a key of type String
* and value of type Value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class String_ValueMapEntry {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "String_ValueMapEntry";
/**
* @access public
* @var string
*/
public $key;
/**
* @access public
* @var Value
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($key = null, $value = null) {
$this->key = $key;
$this->value = $value;
}
}
}
if (!class_exists("TypeError", false)) {
/**
* An error for a field which is an invalid type.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class TypeError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "TypeError";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("UniqueError", false)) {
/**
* An error for a field which must satisfy a uniqueness constraint
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UniqueError extends ApiError {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "UniqueError";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) {
parent::__construct();
$this->fieldPath = $fieldPath;
$this->trigger = $trigger;
$this->errorString = $errorString;
$this->ApiErrorType = $ApiErrorType;
}
}
}
if (!class_exists("UpdateResult", false)) {
/**
* Represents the result of performing an action on objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UpdateResult {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "UpdateResult";
/**
* @access public
* @var integer
*/
public $numChanges;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($numChanges = null) {
$this->numChanges = $numChanges;
}
}
}
if (!class_exists("Value", false)) {
/**
* {@code Value} represents a value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "Value";
/**
* @access public
* @var string
*/
public $ValueType;
private $_parameterMap = array(
"Value.Type" => "ValueType",
);
/**
* Provided for setting non-php-standard named variables
* @param $var Variable name to set
* @param $value Value to set
*/
public function __set($var, $value) {
$this->{$this->_parameterMap[$var]} = $value;
}
/**
* Provided for getting non-php-standard named variables
* @param $var Variable name to get
* @return mixed Variable value
*/
public function __get($var) {
if (!isset($this->_parameterMap[$var])) {
return null;
}
return $this->{$this->_parameterMap[$var]};
}
/**
* Provided for getting non-php-standard named variables
* @return array parameter map
*/
protected function getParameterMap() {
return $this->_parameterMap;
}
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($ValueType = null) {
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("ApiVersionErrorReason", false)) {
/**
* Indicates that the operation is not allowed in the version the request
* was made in.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ApiVersionErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ApiVersionError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("AuthenticationErrorReason", false)) {
/**
* The SOAP message contains a request header with an ambiguous definition
* of the authentication header fields. This means either the {@code
* authToken} and {@code oAuthToken} fields were both null or both were
* specified. Exactly one value should be specified with each request.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class AuthenticationErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "AuthenticationError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CommonErrorReason", false)) {
/**
* Describes reasons for common errors
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CommonErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CommonError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CustomTargetingErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CustomTargetingKeyType", false)) {
/**
* Specifies the types for {@code CustomTargetingKey} objects.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingKeyType {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingKey.Type";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CustomTargetingValueMatchType", false)) {
/**
* Represents the ways in which {@link CustomTargetingValue#name} strings will
* be matched with ad requests.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingValueMatchType {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "CustomTargetingValue.MatchType";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("FeatureErrorReason", false)) {
/**
* A feature is being used that is not enabled on the current network.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class FeatureErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "FeatureError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("InternalApiErrorReason", false)) {
/**
* The single reason for the internal API error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class InternalApiErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "InternalApiError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("NotNullErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class NotNullErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "NotNullError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("NullErrorReason", false)) {
/**
* The reasons for the validation error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class NullErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "NullError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ParseErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ParseErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ParseError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PermissionErrorReason", false)) {
/**
* Describes reasons for permission errors.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PermissionErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PermissionError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PublisherQueryLanguageContextErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PublisherQueryLanguageContextError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PublisherQueryLanguageSyntaxErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("QuotaErrorReason", false)) {
/**
* The number of requests made per second is too high and has exceeded the
* allowable limit. The recommended approach to handle this error is to wait
* about 5 seconds and then retry the request. Note that this does not
* guarantee the request will succeed. If it fails again, try increasing the
* wait time.
* <p>
* Another way to mitigate this error is to limit requests to 2 per second.
* Once again this does not guarantee that every request will succeed, but
* may help reduce the number of times you receive this error.
* </p>
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class QuotaErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "QuotaError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("RequiredErrorReason", false)) {
/**
* The reasons for the target error.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class RequiredErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "RequiredError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("ServerErrorReason", false)) {
/**
* Describes reasons for server errors
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ServerErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ServerError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("StatementErrorReason", false)) {
/**
* A bind variable has not been bound to a value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class StatementErrorReason {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "StatementError.Reason";
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct() {
}
}
}
if (!class_exists("CreateCustomTargetingKeys", false)) {
/**
* Creates new {@link CustomTargetingKey} objects.
*
* The following fields are required:
* <ul>
* <li>{@link CustomTargetingKey#name}</li>
* <li>{@link CustomTargetingKey#type}</li>
* </ul>
*
* @param keys the custom targeting keys to update
* @return the updated custom targeting keys
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CreateCustomTargetingKeys {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKey[]
*/
public $keys;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($keys = null) {
$this->keys = $keys;
}
}
}
if (!class_exists("CreateCustomTargetingKeysResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CreateCustomTargetingKeysResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKey[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("CreateCustomTargetingValues", false)) {
/**
* Creates new {@link CustomTargetingValue} objects.
*
* The following fields are required:
* <ul>
* <li>{@link CustomTargetingValue#customTargetingKeyId}</li>
* <li>{@link CustomTargetingValue#name}</li>
* </ul>
*
* @param values the custom targeting values to update
* @return the updated custom targeting keys
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CreateCustomTargetingValues {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValue[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($values = null) {
$this->values = $values;
}
}
}
if (!class_exists("CreateCustomTargetingValuesResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CreateCustomTargetingValuesResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValue[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("GetCustomTargetingKeysByStatement", false)) {
/**
* Gets a {@link CustomTargetingKeyPage} of {@link CustomTargetingKey} objects
* that satisfy the given {@link Statement#query}. The following fields are
* supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link CustomTargetingKey#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link CustomTargetingKey#name}</td>
* </tr>
* <tr>
* <td>{@code displayName}</td>
* <td>{@link CustomTargetingKey#displayName}</td>
* </tr>
* <tr>
* <td>{@code type}</td>
* <td>{@link CustomTargetingKey#type}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting keys
* @return the custom targeting keys that match the given filter
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class GetCustomTargetingKeysByStatement {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($filterStatement = null) {
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("GetCustomTargetingKeysByStatementResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class GetCustomTargetingKeysByStatementResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKeyPage
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("GetCustomTargetingValuesByStatement", false)) {
/**
* Gets a {@link CustomTargetingValuePage} of {@link CustomTargetingValue}
* objects that satisfy the given {@link Statement#query}.
* <p>
* The {@code WHERE} clause in the {@link Statement#query} must always contain
* {@link CustomTargetingValue#customTargetingKeyId} as one of its columns in
* a way that it is AND'ed with the rest of the query. So, if you want to
* retrieve values for a known set of key ids, valid {@link Statement#query}
* would look like:
* </p>
* <ol>
* <li>
* "WHERE customTargetingKeyId IN ('17','18','19')" retrieves all values that
* are associated with keys having ids 17, 18, 19.
* </li>
* <li>
* "WHERE customTargetingKeyId = '17' AND name = 'red'" retrieves values that
* are associated with keys having id 17 and value name is 'red'.
* </li>
* </ol>
* </p>
* <p>
* The following fields are supported for filtering:
* </p>
* <table>
* <tr>
* <th scope="col">PQL Property</th>
* <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link CustomTargetingValue#id}</td>
* </tr>
* <tr>
* <td>{@code customTargetingKeyId}</td>
* <td>{@link CustomTargetingValue#customTargetingKeyId}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link CustomTargetingValue#name}</td>
* </tr>
* <tr>
* <td>{@code displayName}</td>
* <td>{@link CustomTargetingValue#displayName}</td>
* </tr>
* <tr>
* <td>{@code matchType}</td>
* <td>{@link CustomTargetingValue#matchType}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting values
* @return the custom targeting values that match the given filter
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class GetCustomTargetingValuesByStatement {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($filterStatement = null) {
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("GetCustomTargetingValuesByStatementResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class GetCustomTargetingValuesByStatementResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValuePage
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("PerformCustomTargetingKeyAction", false)) {
/**
* Performs actions on {@link CustomTargetingKey} objects that match the given
* {@link Statement#query}.
*
* @param customTargetingKeyAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting keys
* @return the result of the action performed
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PerformCustomTargetingKeyAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKeyAction
*/
public $customTargetingKeyAction;
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($customTargetingKeyAction = null, $filterStatement = null) {
$this->customTargetingKeyAction = $customTargetingKeyAction;
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("PerformCustomTargetingKeyActionResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PerformCustomTargetingKeyActionResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var UpdateResult
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("PerformCustomTargetingValueAction", false)) {
/**
* Performs actions on {@link CustomTargetingValue} objects that match the
* given {@link Statement#query}.
*
* @param customTargetingValueAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of ad units
* @return the result of the action performed
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PerformCustomTargetingValueAction {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValueAction
*/
public $customTargetingValueAction;
/**
* @access public
* @var Statement
*/
public $filterStatement;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($customTargetingValueAction = null, $filterStatement = null) {
$this->customTargetingValueAction = $customTargetingValueAction;
$this->filterStatement = $filterStatement;
}
}
}
if (!class_exists("PerformCustomTargetingValueActionResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class PerformCustomTargetingValueActionResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var UpdateResult
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("UpdateCustomTargetingKeys", false)) {
/**
* Updates the specified {@link CustomTargetingKey} objects.
*
* @param keys the custom targeting keys to update
* @return the updated custom targeting keys
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UpdateCustomTargetingKeys {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKey[]
*/
public $keys;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($keys = null) {
$this->keys = $keys;
}
}
}
if (!class_exists("UpdateCustomTargetingKeysResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UpdateCustomTargetingKeysResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingKey[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("UpdateCustomTargetingValues", false)) {
/**
* Updates the specified {@link CustomTargetingValue} objects.
*
* @param values the custom targeting values to update
* @return the updated custom targeting values
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UpdateCustomTargetingValues {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValue[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($values = null) {
$this->values = $values;
}
}
}
if (!class_exists("UpdateCustomTargetingValuesResponse", false)) {
/**
*
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class UpdateCustomTargetingValuesResponse {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "";
/**
* @access public
* @var CustomTargetingValue[]
*/
public $rval;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($rval = null) {
$this->rval = $rval;
}
}
}
if (!class_exists("ApiException", false)) {
/**
* Exception class for holding a list of service errors.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class ApiException extends ApplicationException {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "ApiException";
/**
* @access public
* @var ApiError[]
*/
public $errors;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($errors = null, $message = null, $ApplicationExceptionType = null) {
parent::__construct();
$this->errors = $errors;
$this->message = $message;
$this->ApplicationExceptionType = $ApplicationExceptionType;
}
}
}
if (!class_exists("BooleanValue", false)) {
/**
* Contains a boolean value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class BooleanValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "BooleanValue";
/**
* @access public
* @var boolean
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null, $ValueType = null) {
parent::__construct();
$this->value = $value;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("DateTimeValue", false)) {
/**
* Contains a date-time value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DateTimeValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "DateTimeValue";
/**
* @access public
* @var DateTime
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null, $ValueType = null) {
parent::__construct();
$this->value = $value;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("DateValue", false)) {
/**
* Contains a date value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class DateValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "DateValue";
/**
* @access public
* @var Date
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null, $ValueType = null) {
parent::__construct();
$this->value = $value;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("NumberValue", false)) {
/**
* Contains a numeric value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class NumberValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "NumberValue";
/**
* @access public
* @var string
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null, $ValueType = null) {
parent::__construct();
$this->value = $value;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("SetValue", false)) {
/**
* Contains a set of {@link Value Values}. May not contain duplicates.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class SetValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "SetValue";
/**
* @access public
* @var Value[]
*/
public $values;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($values = null, $ValueType = null) {
parent::__construct();
$this->values = $values;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("TextValue", false)) {
/**
* Contains a string value.
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class TextValue extends Value {
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const XSI_TYPE = "TextValue";
/**
* @access public
* @var string
*/
public $value;
/**
* Gets the namesapce of this class
* @return the namespace of this class
*/
public function getNamespace() {
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return the xsi:type name of this class
*/
public function getXsiTypeName() {
return self::XSI_TYPE;
}
public function __construct($value = null, $ValueType = null) {
parent::__construct();
$this->value = $value;
$this->ValueType = $ValueType;
}
}
}
if (!class_exists("CustomTargetingService", false)) {
/**
* CustomTargetingService
* @package GoogleApiAdsDfp
* @subpackage v201403
*/
class CustomTargetingService extends DfpSoapClient {
const SERVICE_NAME = "CustomTargetingService";
const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201403";
const ENDPOINT = "https://www.google.com/apis/ads/publisher/v201403/CustomTargetingService";
/**
* The endpoint of the service
* @var string
*/
public static $endpoint = "https://www.google.com/apis/ads/publisher/v201403/CustomTargetingService";
/**
* Default class map for wsdl=>php
* @access private
* @var array
*/
public static $classmap = array(
"ApiError" => "ApiError",
"ApiException" => "ApiException",
"ApiVersionError" => "ApiVersionError",
"ApplicationException" => "ApplicationException",
"Authentication" => "Authentication",
"AuthenticationError" => "AuthenticationError",
"BooleanValue" => "BooleanValue",
"CommonError" => "CommonError",
"CustomTargetingError" => "CustomTargetingError",
"CustomTargetingKeyAction" => "CustomTargetingKeyAction",
"CustomTargetingKey" => "CustomTargetingKey",
"CustomTargetingKeyPage" => "CustomTargetingKeyPage",
"CustomTargetingValueAction" => "CustomTargetingValueAction",
"CustomTargetingValue" => "CustomTargetingValue",
"CustomTargetingValuePage" => "CustomTargetingValuePage",
"Date" => "Date",
"DateTime" => "DfpDateTime",
"DateTimeValue" => "DateTimeValue",
"DateValue" => "DateValue",
"DeleteCustomTargetingKeys" => "DeleteCustomTargetingKeys",
"DeleteCustomTargetingValues" => "DeleteCustomTargetingValues",
"FeatureError" => "FeatureError",
"InternalApiError" => "InternalApiError",
"NotNullError" => "NotNullError",
"NullError" => "NullError",
"NumberValue" => "NumberValue",
"OAuth" => "DfpOAuth",
"ParseError" => "ParseError",
"PermissionError" => "PermissionError",
"PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError",
"PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError",
"QuotaError" => "QuotaError",
"RequiredError" => "RequiredError",
"ServerError" => "ServerError",
"SetValue" => "SetValue",
"SoapRequestHeader" => "SoapRequestHeader",
"SoapResponseHeader" => "SoapResponseHeader",
"Statement" => "Statement",
"StatementError" => "StatementError",
"String_ValueMapEntry" => "String_ValueMapEntry",
"TextValue" => "TextValue",
"TypeError" => "TypeError",
"UniqueError" => "UniqueError",
"UpdateResult" => "UpdateResult",
"Value" => "Value",
"ApiVersionError.Reason" => "ApiVersionErrorReason",
"AuthenticationError.Reason" => "AuthenticationErrorReason",
"CommonError.Reason" => "CommonErrorReason",
"CustomTargetingError.Reason" => "CustomTargetingErrorReason",
"CustomTargetingKey.Type" => "CustomTargetingKeyType",
"CustomTargetingValue.MatchType" => "CustomTargetingValueMatchType",
"FeatureError.Reason" => "FeatureErrorReason",
"InternalApiError.Reason" => "InternalApiErrorReason",
"NotNullError.Reason" => "NotNullErrorReason",
"NullError.Reason" => "NullErrorReason",
"ParseError.Reason" => "ParseErrorReason",
"PermissionError.Reason" => "PermissionErrorReason",
"PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason",
"PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason",
"QuotaError.Reason" => "QuotaErrorReason",
"RequiredError.Reason" => "RequiredErrorReason",
"ServerError.Reason" => "ServerErrorReason",
"StatementError.Reason" => "StatementErrorReason",
"createCustomTargetingKeys" => "CreateCustomTargetingKeys",
"createCustomTargetingKeysResponse" => "CreateCustomTargetingKeysResponse",
"createCustomTargetingValues" => "CreateCustomTargetingValues",
"createCustomTargetingValuesResponse" => "CreateCustomTargetingValuesResponse",
"getCustomTargetingKeysByStatement" => "GetCustomTargetingKeysByStatement",
"getCustomTargetingKeysByStatementResponse" => "GetCustomTargetingKeysByStatementResponse",
"getCustomTargetingValuesByStatement" => "GetCustomTargetingValuesByStatement",
"getCustomTargetingValuesByStatementResponse" => "GetCustomTargetingValuesByStatementResponse",
"performCustomTargetingKeyAction" => "PerformCustomTargetingKeyAction",
"performCustomTargetingKeyActionResponse" => "PerformCustomTargetingKeyActionResponse",
"performCustomTargetingValueAction" => "PerformCustomTargetingValueAction",
"performCustomTargetingValueActionResponse" => "PerformCustomTargetingValueActionResponse",
"updateCustomTargetingKeys" => "UpdateCustomTargetingKeys",
"updateCustomTargetingKeysResponse" => "UpdateCustomTargetingKeysResponse",
"updateCustomTargetingValues" => "UpdateCustomTargetingValues",
"updateCustomTargetingValuesResponse" => "UpdateCustomTargetingValuesResponse",
);
/**
* Constructor using wsdl location and options array
* @param string $wsdl WSDL location for this service
* @param array $options Options for the SoapClient
*/
public function __construct($wsdl, $options, $user) {
$options["classmap"] = self::$classmap;
parent::__construct($wsdl, $options, $user, self::SERVICE_NAME,
self::WSDL_NAMESPACE);
}
/**
* Creates new {@link CustomTargetingKey} objects.
*
* The following fields are required:
* <ul>
* <li>{@link CustomTargetingKey#name}</li>
* <li>{@link CustomTargetingKey#type}</li>
* </ul>
*
* @param keys the custom targeting keys to update
* @return the updated custom targeting keys
*/
public function createCustomTargetingKeys($keys) {
$args = new CreateCustomTargetingKeys($keys);
$result = $this->__soapCall("createCustomTargetingKeys", array($args));
return $result->rval;
}
/**
* Creates new {@link CustomTargetingValue} objects.
*
* The following fields are required:
* <ul>
* <li>{@link CustomTargetingValue#customTargetingKeyId}</li>
* <li>{@link CustomTargetingValue#name}</li>
* </ul>
*
* @param values the custom targeting values to update
* @return the updated custom targeting keys
*/
public function createCustomTargetingValues($values) {
$args = new CreateCustomTargetingValues($values);
$result = $this->__soapCall("createCustomTargetingValues", array($args));
return $result->rval;
}
/**
* Gets a {@link CustomTargetingKeyPage} of {@link CustomTargetingKey} objects
* that satisfy the given {@link Statement#query}. The following fields are
* supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link CustomTargetingKey#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link CustomTargetingKey#name}</td>
* </tr>
* <tr>
* <td>{@code displayName}</td>
* <td>{@link CustomTargetingKey#displayName}</td>
* </tr>
* <tr>
* <td>{@code type}</td>
* <td>{@link CustomTargetingKey#type}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting keys
* @return the custom targeting keys that match the given filter
*/
public function getCustomTargetingKeysByStatement($filterStatement) {
$args = new GetCustomTargetingKeysByStatement($filterStatement);
$result = $this->__soapCall("getCustomTargetingKeysByStatement", array($args));
return $result->rval;
}
/**
* Gets a {@link CustomTargetingValuePage} of {@link CustomTargetingValue}
* objects that satisfy the given {@link Statement#query}.
* <p>
* The {@code WHERE} clause in the {@link Statement#query} must always contain
* {@link CustomTargetingValue#customTargetingKeyId} as one of its columns in
* a way that it is AND'ed with the rest of the query. So, if you want to
* retrieve values for a known set of key ids, valid {@link Statement#query}
* would look like:
* </p>
* <ol>
* <li>
* "WHERE customTargetingKeyId IN ('17','18','19')" retrieves all values that
* are associated with keys having ids 17, 18, 19.
* </li>
* <li>
* "WHERE customTargetingKeyId = '17' AND name = 'red'" retrieves values that
* are associated with keys having id 17 and value name is 'red'.
* </li>
* </ol>
* </p>
* <p>
* The following fields are supported for filtering:
* </p>
* <table>
* <tr>
* <th scope="col">PQL Property</th>
* <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link CustomTargetingValue#id}</td>
* </tr>
* <tr>
* <td>{@code customTargetingKeyId}</td>
* <td>{@link CustomTargetingValue#customTargetingKeyId}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link CustomTargetingValue#name}</td>
* </tr>
* <tr>
* <td>{@code displayName}</td>
* <td>{@link CustomTargetingValue#displayName}</td>
* </tr>
* <tr>
* <td>{@code matchType}</td>
* <td>{@link CustomTargetingValue#matchType}</td>
* </tr>
* </table>
*
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting values
* @return the custom targeting values that match the given filter
*/
public function getCustomTargetingValuesByStatement($filterStatement) {
$args = new GetCustomTargetingValuesByStatement($filterStatement);
$result = $this->__soapCall("getCustomTargetingValuesByStatement", array($args));
return $result->rval;
}
/**
* Performs actions on {@link CustomTargetingKey} objects that match the given
* {@link Statement#query}.
*
* @param customTargetingKeyAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of custom targeting keys
* @return the result of the action performed
*/
public function performCustomTargetingKeyAction($customTargetingKeyAction, $filterStatement) {
$args = new PerformCustomTargetingKeyAction($customTargetingKeyAction, $filterStatement);
$result = $this->__soapCall("performCustomTargetingKeyAction", array($args));
return $result->rval;
}
/**
* Performs actions on {@link CustomTargetingValue} objects that match the
* given {@link Statement#query}.
*
* @param customTargetingValueAction the action to perform
* @param filterStatement a Publisher Query Language statement used to filter
* a set of ad units
* @return the result of the action performed
*/
public function performCustomTargetingValueAction($customTargetingValueAction, $filterStatement) {
$args = new PerformCustomTargetingValueAction($customTargetingValueAction, $filterStatement);
$result = $this->__soapCall("performCustomTargetingValueAction", array($args));
return $result->rval;
}
/**
* Updates the specified {@link CustomTargetingKey} objects.
*
* @param keys the custom targeting keys to update
* @return the updated custom targeting keys
*/
public function updateCustomTargetingKeys($keys) {
$args = new UpdateCustomTargetingKeys($keys);
$result = $this->__soapCall("updateCustomTargetingKeys", array($args));
return $result->rval;
}
/**
* Updates the specified {@link CustomTargetingValue} objects.
*
* @param values the custom targeting values to update
* @return the updated custom targeting values
*/
public function updateCustomTargetingValues($values) {
$args = new UpdateCustomTargetingValues($values);
$result = $this->__soapCall("updateCustomTargetingValues", array($args));
return $result->rval;
}
}
} | {
"content_hash": "f13f6189f6345c2ea29341336619c863",
"timestamp": "",
"source": "github",
"line_count": 3990,
"max_line_length": 129,
"avg_line_length": 25.306516290726815,
"alnum_prop": 0.6212551870301962,
"repo_name": "cornernote/googleads-php-lib",
"id": "f62eba7a1f9ecbffd5de425ef61e7d8120f581bb",
"size": "101926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Google/Api/Ads/Dfp/v201403/CustomTargetingService.php",
"mode": "33261",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "05f401deace8c909751daa72246625d5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "94bb32fc4f68524a4c393024a2bc2af3f6dee3b5",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Bauhinia/Bauhinia picta/ Syn. Bauhinia kalbreyeri/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
local runner = require('user_modules/script_runner')
local common = require('test_scripts/AppServices/commonAppServices')
local test = require("user_modules/dummy_connecttest")
local events = require('events')
local utils = require('user_modules/utils')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
-- [[Local Variable]]
local hashID
--[[ Local Functions ]]
local function PTUfunc(tbl)
tbl.policy_table.app_policies[common.getConfigAppParams(1).fullAppID] = common.getAppServiceConsumerConfig(1);
end
local manifest = {
serviceName = "HMI_MEDIA_SERVICE",
serviceType = "MEDIA",
allowAppConsumers = true,
rpcSpecVersion = config.application1.registerAppInterfaceParams.syncMsgVersion,
mediaServiceManifest = {}
}
local rpc = {
name = "OnAppServiceData",
hmiName = "AppService.OnAppServiceData"
}
local appServiceData = {
serviceType = manifest.serviceType,
mediaServiceData = {
mediaType = "MUSIC",
mediaTitle = "Song name",
mediaArtist = "Band name",
mediaAlbum = "Album name",
playlistName = "Good music",
isExplicit = false,
trackPlaybackProgress = 200,
trackPlaybackDuration = 300,
queuePlaybackProgress = 2200,
queuePlaybackDuration = 4000,
queueCurrentTrackNumber = 12,
queueTotalTrackCount = 20
}
}
local expectedNotification = {
serviceData = appServiceData
}
local function processRPCSuccess()
local mobileSession = common.getMobileSession()
local service_id = common.getAppServiceID(0)
local notificationParams = expectedNotification
notificationParams.serviceData.serviceID = service_id
common.getHMIConnection():SendNotification(rpc.hmiName, notificationParams)
mobileSession:ExpectNotification(rpc.name, notificationParams)
end
local function checkResumption(pAppId)
common.getHMIConnection():ExpectRequest("BasicCommunication.ActivateApp", {})
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
common.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "NONE" },
{ hmiLevel = "FULL" })
:Times(2)
end
local function reRegisterApp(pAppId)
if not pAppId then pAppId = 1 end
common.getMobileSession():StartService(7)
:Do(function()
local params = utils.cloneTable(common.getConfigAppParams(pAppId))
params.hashID = hashID
local corId = common.getMobileSession():SendRPC("RegisterAppInterface", params)
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered",
{ application = { appName = common.getConfigAppParams(pAppId).appName } })
common.getMobileSession():ExpectResponse(corId, { success = true, resultCode = "SUCCESS" })
:Do(function()
common.getMobileSession(pAppId):ExpectNotification("OnPermissionsChange")
end)
end)
checkResumption(pAppId)
end
local function unexpectedDisconnect()
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = true })
common.mobile.disconnect()
utils.wait(1000)
end
local function connectMobile()
test.mobileConnection:Connect()
common.getMobileSession():ExpectEvent(events.connectedEvent, "Connected")
:Do(function()
utils.cprint(35, "Mobile connected")
end)
end
local function mobileSubscribeAppServiceData(pAppId)
if not pAppId then pAppId = 1 end
common.getMobileSession(pAppId):ExpectNotification("OnHashChange")
:Do(function(_, data)
hashID = data.payload.hashID
end)
common.mobileSubscribeAppServiceData(0)
end
-- [[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("App registration", common.registerApp)
runner.Step("PTU", common.policyTableUpdate, { PTUfunc })
runner.Step("App activation", common.activateApp)
runner.Step("Publish App Service", common.publishEmbeddedAppService, { manifest })
runner.Step("Subscribe App Service Data", mobileSubscribeAppServiceData)
runner.Title("Test")
runner.Step("RPC " .. rpc.name .. "_resultCode_SUCCESS", processRPCSuccess)
runner.Step("Unexpected disconnect", unexpectedDisconnect)
runner.Step("Connect mobile", connectMobile)
runner.Step("App Reregistration", reRegisterApp)
runner.Step("RPC " .. rpc.name .. "_resultCode_SUCCESS", processRPCSuccess)
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
| {
"content_hash": "5652202913d3f5d9822deca9fbe1d016",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 119,
"avg_line_length": 33.82575757575758,
"alnum_prop": 0.754087346024636,
"repo_name": "smartdevicelink/sdl_atf_test_scripts",
"id": "c56e5b398b4f8b099b34618d2092736aad163e5d",
"size": "5518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_scripts/AppServices/Resumption/001_Resumption_GetAppServiceData_Unexpected_Disconnect.lua",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Lua",
"bytes": "27589836"
},
{
"name": "Perl",
"bytes": "2557"
},
{
"name": "Python",
"bytes": "8898"
},
{
"name": "Shell",
"bytes": "12889"
}
],
"symlink_target": ""
} |
<div class="listBox" style="position:absolute; width: 600px; height: 400px; margin-left: -300px;">
<h2><span style="color: #56adfa;">Jūsų apmokėjimas sėkmingai priimtas!</span></h2>
</div> | {
"content_hash": "a9c8a91c39b27295dfb11c0323163625",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 98,
"avg_line_length": 63,
"alnum_prop": 0.7142857142857143,
"repo_name": "rokasr/pzntsltaa",
"id": "68ed263fb19fe4ae3f99ce483f88c395c18f27db",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/views/member/_success.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "497"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "94713"
},
{
"name": "JavaScript",
"bytes": "366589"
},
{
"name": "PHP",
"bytes": "1504746"
}
],
"symlink_target": ""
} |
An easy to configure informational page for your Xonotic game server
:link: [live demo](http://z.github.io/xonotic-server-info-page)
#### Features
* Live server information (polls the master server every 30 seconds)
* Multi-server support
* Configurable Maplist
* IRC widget
* News page (blog)
* Themes
* Custom Pages
* Content written in Markdown
#### Quick Start
1. Fork this repository
2. Edit `config/site.js` with your server information (this can be generated with the GUI and exported as a zip)
3. Edit `config/manifest.js` to define your map list and link to blog posts
4. To edit pages, edit the existing files in `resources/data/pages`
4. To write blog posts, add markdown files to `resources/data/blog`, be sure to include them explicitly in `config/manifest.js`
#### Tips
You can host this on [github.io](https://pages.github.com/):
* As an organization: create a `<organization>.github.io` repository within that organization (recommended)
* As a user: by create a `gh-pages` branch in your fork
You can use the github interface to write blog posts, and maintain the site.
#### Modifying Content
All content is written in markdown files that are parsed into HTML at runtime. You can add/edit/delete pages and posts this way. The site doesn't know about your markdown files (pages and posts) unless they are specified in the `config/manifest.json` file.
HTML is allowed in markdown files, in fact, this site uses some you should consider "reserved". Currently the assumption is that all these pages except "about" exist (this will be more configurable in the future). Additional pages are possible.
#### Advanced Configuration
The configuration is defined in two files, `options.json` and `config/manifest.json`. These can be created with the GUI editor, or written by hand.
While these files below contain comments for reference, *JSON does not support comments*. **Do not use comments in your *.json files or the site will not work.**
`config/options.json`:
This file defines site configuration options.
```js
{
// the remote address where a qstat xml can be returned
qstatAddress: 'http://dpmaster.deathmask.net/?&xml=1&showplayers=1',
// local or remote for bspname.jpg
mapshotDir: 'http://xonotic.co/resources/mapshots/maps/',
// theme (can be overriden by user's choice if switcher is enabled)
theme: 'default',
// IRC channel
ircChannel: 'smb',
// if true, the chat iframe will be loaded only when requested
enableLoadChatButton: true,
// this allows users to choose their own theme (uses a cookie)
enableThemeSwitcher: true,
// allow for devmode
enableEditor: true,
// debug options in developer mode
editorOptions: {
// used for development / debugging
useLocalXML: false,
// where is it located?
qstatLocalXML: 'resources/data/qstat.xml'
}
}
```
`config/manifest.json`:
This file contains information about servers, pages, posts and themes.
```js
{
// Game Server config
servers: [
{
id: 'insta',
address: '96.44.146.149',
port: '26010',
game: 'xonotic',
// list of bsp names
mapList: [
'swing',
'boxflip',
'accident_minsta',
]
},
{
id: 'kansas',
address: '96.44.146.149',
port: '26000',
game: 'xonotic',
mapList: [
'vinegar_v3',
'dance_nex',
'accident_v3',
'battlevalentine',
'furious',
'gforce2',
'got_wood',
'gothic_block'
]
}
],
// id should be alphanumeric only, no duplicates
// content refers to the .md file in resources/data/pages
// icon is a font awesome icon
pages: [
{
id: 'servers',
title: 'Servers',
content: 'servers',
icon: 'list'
},
{
id: 'about',
title: 'About',
content: 'about',
icon: 'info-circle'
},
{
id: 'maplist',
title: 'Maplist',
content: 'maplist',
icon: 'map-o'
},
{
id: 'chat',
title: 'Chat',
content: 'chat',
icon: 'comment'
},
{
id: 'news',
title: 'News',
content: 'news',
icon: 'newspaper-o'
}
],
// list the posts you'd like to show here
// latest first
posts: [
'second-post',
'first-post'
],
// Define Themes
themes: {
"default": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
"cerulean" : "//bootswatch.com/cerulean/bootstrap.min.css",
"cosmo" : "//bootswatch.com/cosmo/bootstrap.min.css",
"cyborg" : "//bootswatch.com/cyborg/bootstrap.min.css",
"darkly" : "//bootswatch.com/darkly/bootstrap.min.css",
"flatly" : "//bootswatch.com/flatly/bootstrap.min.css",
"journal" : "//bootswatch.com/journal/bootstrap.min.css",
"lumen" : "//bootswatch.com/lumen/bootstrap.min.css",
"paper" : "//bootswatch.com/paper/bootstrap.min.css",
"readable" : "//bootswatch.com/readable/bootstrap.min.css",
"sandstone" : "//bootswatch.com/sandstone/bootstrap.min.css",
"simplex" : "//bootswatch.com/simplex/bootstrap.min.css",
"slate" : "//bootswatch.com/slate/bootstrap.min.css",
"spacelab" : "//bootswatch.com/spacelab/bootstrap.min.css",
"superhero" : "//bootswatch.com/superhero/bootstrap.min.css",
"united" : "//bootswatch.com/united/bootstrap.min.css",
"yeti" : "//bootswatch.com/yeti/bootstrap.min.css"
}
}
```
This software was developed using static files, you can serve them locally for development with `python -m simpleHTTPServer 8000` and visit `http://localhost:8000`.
| {
"content_hash": "9356b371bfc7299163b0b261bf7c0984",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 256,
"avg_line_length": 31.858638743455497,
"alnum_prop": 0.6041084634346754,
"repo_name": "xonotic-na/xonotic-na.github.io",
"id": "cdeb90d503404ab35b1b39ddb28a8fdd86d55624",
"size": "6112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6445"
},
{
"name": "HTML",
"bytes": "14985"
},
{
"name": "JavaScript",
"bytes": "23447"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.cognitoidentity.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;
import com.amazonaws.services.cognitoidentity.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UnprocessedIdentityId JSON Unmarshaller
*/
public class UnprocessedIdentityIdJsonUnmarshaller implements
Unmarshaller<UnprocessedIdentityId, JsonUnmarshallerContext> {
public UnprocessedIdentityId unmarshall(JsonUnmarshallerContext context)
throws Exception {
UnprocessedIdentityId unprocessedIdentityId = new UnprocessedIdentityId();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("IdentityId", targetDepth)) {
context.nextToken();
unprocessedIdentityId.setIdentityId(context
.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ErrorCode", targetDepth)) {
context.nextToken();
unprocessedIdentityId.setErrorCode(context.getUnmarshaller(
String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return unprocessedIdentityId;
}
private static UnprocessedIdentityIdJsonUnmarshaller instance;
public static UnprocessedIdentityIdJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UnprocessedIdentityIdJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "b8f42d4884a0c576f2e76a3ce92e40a5",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 82,
"avg_line_length": 35.67123287671233,
"alnum_prop": 0.619815668202765,
"repo_name": "mhurne/aws-sdk-java",
"id": "6d958140cde3f01f561e8a7ff53e8fa252b16d36",
"size": "3191",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/transform/UnprocessedIdentityIdJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "123790"
},
{
"name": "Java",
"bytes": "110875821"
},
{
"name": "Scilab",
"bytes": "3561"
}
],
"symlink_target": ""
} |
namespace views {
class ImageView;
}
struct AutocompleteMatch;
class OmniboxResultView;
class OmniboxTextView;
class OmniboxMatchCellView : public views::View {
public:
METADATA_HEADER(OmniboxMatchCellView);
// Constants used in layout. Exposed so other views can coordinate margins.
static constexpr int kMarginLeft = 4;
static constexpr int kMarginRight = 8;
static constexpr int kImageBoundsWidth = 40;
// Computes the maximum width, in pixels, that can be allocated for the two
// parts of an autocomplete result, i.e. the contents and the description.
//
// When |description_on_separate_line| is true, the caller will be displaying
// two separate lines of text, so both contents and description can take up
// the full available width. Otherwise, the contents and description are
// assumed to be on the same line, with a separator between them.
//
// When |allow_shrinking_contents| is true, and the contents and description
// are together on a line without enough space for both, the code tries to
// divide the available space equally between the two, unless this would make
// one or both too narrow. Otherwise, the contents is given as much space as
// it wants and the description gets the remainder.
static void ComputeMatchMaxWidths(int contents_width,
int separator_width,
int description_width,
int available_width,
bool description_on_separate_line,
bool allow_shrinking_contents,
int* contents_max_width,
int* description_max_width);
explicit OmniboxMatchCellView(OmniboxResultView* result_view);
OmniboxMatchCellView(const OmniboxMatchCellView&) = delete;
OmniboxMatchCellView& operator=(const OmniboxMatchCellView&) = delete;
~OmniboxMatchCellView() override;
views::ImageView* icon() { return icon_view_; }
OmniboxTextView* content() { return content_view_; }
OmniboxTextView* description() { return description_view_; }
OmniboxTextView* separator() { return separator_view_; }
static int GetTextIndent();
// Determines if `match` should display an answer, calculator, or entity
// image.
// If #omnibox-uniform-suggestion-height experiment flag is disabled, also
// determines whether `match` should be displayed on 1 or 2 lines.
static bool ShouldDisplayImage(const AutocompleteMatch& match);
void OnMatchUpdate(const OmniboxResultView* result_view,
const AutocompleteMatch& match);
// Sets the answer image and, if the image is not square, sets the answer size
// proportional to the image size to preserve its aspect ratio.
void SetImage(const gfx::ImageSkia& image);
// views::View:
gfx::Insets GetInsets() const override;
void Layout() override;
bool GetCanProcessEventsWithinSubtree() const override;
gfx::Size CalculatePreferredSize() const override;
private:
enum class LayoutStyle {
ONE_LINE_SUGGESTION,
TWO_LINE_SUGGESTION,
};
void SetTailSuggestCommonPrefixWidth(const std::u16string& common_prefix);
bool is_search_type_ = false;
bool has_image_ = false;
LayoutStyle layout_style_ = LayoutStyle::ONE_LINE_SUGGESTION;
// Weak pointers for easy reference.
// An icon representing the type or content.
raw_ptr<views::ImageView> icon_view_;
// The image for answers in suggest and rich entity suggestions.
raw_ptr<views::ImageView> answer_image_view_;
raw_ptr<OmniboxTextView> tail_suggest_ellipse_view_;
raw_ptr<OmniboxTextView> content_view_;
raw_ptr<OmniboxTextView> description_view_;
raw_ptr<OmniboxTextView> separator_view_;
// This holds the rendered width of the common prefix of a set of tail
// suggestions so that it doesn't have to be re-calculated if the prefix
// doesn't change.
int tail_suggest_common_prefix_width_ = 0;
};
#endif // CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_MATCH_CELL_VIEW_H_
| {
"content_hash": "8af84786b3d958bfa72a78c8613122c9",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 80,
"avg_line_length": 41.05050505050505,
"alnum_prop": 0.702755905511811,
"repo_name": "chromium/chromium",
"id": "a28d4179fe75a3882ab3a5e50cce154adf5d7318",
"size": "4457",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* File Name: dowhile-005
* ECMA Section:
* Description: do...while statements
*
* Test a labeled do...while. Break out of the loop with no label
* should break out of the loop, but not out of the label.
*
* Currently causes an infinite loop in the monkey. Uncomment the
* print statement below and it works OK.
*
* Author: christine@netscape.com
* Date: 26 August 1998
*/
var SECTION = "dowhile-005";
var VERSION = "ECMA_2";
var TITLE = "do...while with a labeled continue statement";
var BUGNUMBER = "316293";
startTest();
writeHeaderToLog( SECTION + " "+ TITLE);
NestedLabel();
test();
function NestedLabel() {
i = 0;
result1 = "pass";
result2 = "fail: did not hit code after inner loop";
result3 = "pass";
outer: {
do {
inner: {
// print( i );
break inner;
result1 = "fail: did break out of inner label";
}
result2 = "pass";
break outer;
print(i);
} while ( i++ < 100 );
}
result3 = "fail: did not break out of outer label";
new TestCase(
SECTION,
"number of loop iterations",
0,
i );
new TestCase(
SECTION,
"break out of inner loop",
"pass",
result1 );
new TestCase(
SECTION,
"break out of outer loop",
"pass",
result2 );
}
| {
"content_hash": "43abbeb673e7fed940ee9680213ac54d",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 79,
"avg_line_length": 22.205479452054796,
"alnum_prop": 0.5940777297964219,
"repo_name": "sergecodd/FireFox-OS",
"id": "40b53583f51257729d6023cd85fd825792942ca5",
"size": "1621",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "B2G/gecko/js/src/tests/ecma_2/Statements/dowhile-005.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "443"
},
{
"name": "ApacheConf",
"bytes": "85"
},
{
"name": "Assembly",
"bytes": "5123438"
},
{
"name": "Awk",
"bytes": "46481"
},
{
"name": "Batchfile",
"bytes": "56250"
},
{
"name": "C",
"bytes": "101720951"
},
{
"name": "C#",
"bytes": "38531"
},
{
"name": "C++",
"bytes": "148896543"
},
{
"name": "CMake",
"bytes": "23541"
},
{
"name": "CSS",
"bytes": "2758664"
},
{
"name": "DIGITAL Command Language",
"bytes": "56757"
},
{
"name": "Emacs Lisp",
"bytes": "12694"
},
{
"name": "Erlang",
"bytes": "889"
},
{
"name": "FLUX",
"bytes": "34449"
},
{
"name": "GLSL",
"bytes": "26344"
},
{
"name": "Gnuplot",
"bytes": "710"
},
{
"name": "Groff",
"bytes": "447012"
},
{
"name": "HTML",
"bytes": "43343468"
},
{
"name": "IDL",
"bytes": "1455122"
},
{
"name": "Java",
"bytes": "43261012"
},
{
"name": "JavaScript",
"bytes": "46646658"
},
{
"name": "Lex",
"bytes": "38358"
},
{
"name": "Logos",
"bytes": "21054"
},
{
"name": "Makefile",
"bytes": "2733844"
},
{
"name": "Matlab",
"bytes": "67316"
},
{
"name": "Max",
"bytes": "3698"
},
{
"name": "NSIS",
"bytes": "421625"
},
{
"name": "Objective-C",
"bytes": "877657"
},
{
"name": "Objective-C++",
"bytes": "737713"
},
{
"name": "PHP",
"bytes": "17415"
},
{
"name": "Pascal",
"bytes": "6780"
},
{
"name": "Perl",
"bytes": "1153180"
},
{
"name": "Perl6",
"bytes": "1255"
},
{
"name": "PostScript",
"bytes": "1139"
},
{
"name": "PowerShell",
"bytes": "8252"
},
{
"name": "Protocol Buffer",
"bytes": "26553"
},
{
"name": "Python",
"bytes": "8453201"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3481"
},
{
"name": "Ruby",
"bytes": "5116"
},
{
"name": "Scilab",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "3383832"
},
{
"name": "SourcePawn",
"bytes": "23661"
},
{
"name": "TeX",
"bytes": "879606"
},
{
"name": "WebIDL",
"bytes": "1902"
},
{
"name": "XSLT",
"bytes": "13134"
},
{
"name": "Yacc",
"bytes": "112744"
}
],
"symlink_target": ""
} |
package org.hibernate.type.descriptor.java;
import java.lang.reflect.Array;
/**
* A mutability plan for arrays. Specifically arrays of immutable element type; since the elements themselves
* are immutable, a shallow copy is enough.
*
* @author Steve Ebersole
*/
public class ArrayMutabilityPlan<T> extends MutableMutabilityPlan<T> {
public static final ArrayMutabilityPlan INSTANCE = new ArrayMutabilityPlan();
@SuppressWarnings({ "unchecked", "SuspiciousSystemArraycopy" })
public T deepCopyNotNull(T value) {
if ( ! value.getClass().isArray() ) {
// ugh! cannot find a way to properly define the type signature here to
throw new IllegalArgumentException( "Value was not an array [" + value.getClass().getName() + "]" );
}
final int length = Array.getLength( value );
T copy = (T) Array.newInstance( value.getClass().getComponentType(), length );
System.arraycopy( value, 0, copy, 0, length );
return copy;
}
}
| {
"content_hash": "360d7cf59c2bdd42bde16da9e432454a",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 110,
"avg_line_length": 37.76,
"alnum_prop": 0.7277542372881356,
"repo_name": "HerrB92/obp",
"id": "9552cb7d6dc291d85b42932c26b3d2ec67be6162",
"size": "1985",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/ArrayMutabilityPlan.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "181658"
},
{
"name": "Groovy",
"bytes": "98685"
},
{
"name": "Java",
"bytes": "34621856"
},
{
"name": "JavaScript",
"bytes": "356255"
},
{
"name": "Shell",
"bytes": "194"
},
{
"name": "XSLT",
"bytes": "21372"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.