text stringlengths 2 1.04M | meta dict |
|---|---|
require_relative '../../spec_helper'
require_relative '../enumerable/shared/enumeratorized'
describe "ENV.reject!" do
it "rejects entries based on key" do
ENV["foo"] = "bar"
ENV.reject! { |k, v| k == "foo" }
ENV["foo"].should == nil
end
it "rejects entries based on value" do
ENV["foo"] = "bar"
ENV.reject! { |k, v| v == "bar" }
ENV["foo"].should == nil
end
it "returns itself or nil" do
ENV.reject! { false }.should == nil
ENV["foo"] = "bar"
ENV.reject! { |k, v| k == "foo" }.should == ENV
ENV["foo"].should == nil
end
it "returns an Enumerator if called without a block" do
ENV.reject!.should be_an_instance_of(Enumerator)
end
it "doesn't raise if empty" do
orig = ENV.to_hash
begin
ENV.clear
lambda { ENV.reject! }.should_not raise_error(LocalJumpError)
ensure
ENV.replace orig
end
end
it_behaves_like :enumeratorized_with_origin_size, :reject!, ENV
end
describe "ENV.reject" do
it "rejects entries based on key" do
ENV["foo"] = "bar"
e = ENV.reject { |k, v| k == "foo" }
e["foo"].should == nil
ENV["foo"].should == "bar"
ENV["foo"] = nil
end
it "rejects entries based on value" do
ENV["foo"] = "bar"
e = ENV.reject { |k, v| v == "bar" }
e["foo"].should == nil
ENV["foo"].should == "bar"
ENV["foo"] = nil
end
it "returns a Hash" do
ENV.reject { false }.should be_kind_of(Hash)
end
it "returns an Enumerator if called without a block" do
ENV.reject.should be_an_instance_of(Enumerator)
end
it "doesn't raise if empty" do
orig = ENV.to_hash
begin
ENV.clear
lambda { ENV.reject }.should_not raise_error(LocalJumpError)
ensure
ENV.replace orig
end
end
it_behaves_like :enumeratorized_with_origin_size, :reject, ENV
end
| {
"content_hash": "dec799af415af99199eea2b52ec26cab",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 67,
"avg_line_length": 23.818181818181817,
"alnum_prop": 0.6035986913849509,
"repo_name": "ruby/rubyspec",
"id": "409efa138507a3c904f83ffb76cc14767a736aaf",
"size": "1834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/env/reject_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "185758"
},
{
"name": "Ruby",
"bytes": "5297785"
}
],
"symlink_target": ""
} |
<?php
namespace Electro\Interop;
/**
* Defines structure information about an associative array containing information for a single migration.
*/
class MigrationStruct
{
/** The migration has already run. */
const DONE = 'done';
/** The migration no longer exists on the project. */
const OBSOLETE = 'obsolete';
/** The migration has not run yet. */
const PENDING = 'pending';
/**
* @var string The date and time of the migration creation. This is the table's primary key.
* <p>It also defines the sorting order of the migration set.
* <p>Format: <code>'YYYYMMDDhhmmss'</code>
*/
const date = 'date';
/**
* @var string The target module for the migration.
*/
const module = 'module';
/**
* @var string The migration name.
*/
const name = 'name';
/**
* @var string The file path of the corresponding migration file (if it exists).
* <p>Note: this field is computed, it's not present on the database.
*/
const path = 'path';
/**
* @var string The SQL code that reverses the migration.
*/
const reverse = 'reverse';
/**
* @var string The current migration state; either {@see MigrationInfo::UP} or {@see MigrationInfo::DOWN}.
* <p>Note: this field is computed, it's not present on the database.
*/
const status = 'status';
/**
* @var string The current migration connection.
*/
const connection = 'connection';
static public function classFromFilename ($path)
{
return ucfirst (str_dehyphenate (str_segmentsStripFirst (
pathinfo ($path)['filename'], '_'), true, '_'));
}
static public function nameFromFilename ($path)
{
return ucfirst (str_decamelize (str_dehyphenate (str_segmentsStripFirst (
pathinfo ($path)['filename'], '_'), true, '_')));
}
static public function toDateStr ($compactDate)
{
return preg_replace ('/(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/', '$1-$2-$3 $4:$5:$6', $compactDate);
}
}
| {
"content_hash": "923f2b18b3f4eac4f30ce48a1d837881",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 108,
"avg_line_length": 30.196969696969695,
"alnum_prop": 0.6266934269944807,
"repo_name": "selenia-framework/interop",
"id": "9c8cfcbfe603b79dafe54a4b2df0b0fa72db8c94",
"size": "1993",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Interop/MigrationStruct.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "86123"
}
],
"symlink_target": ""
} |
<h4 style="font-size:20px">
Educational Background 
<button class="btn btn-default" id="education_toggle_show" style="display:none">Show</button>
<button class="btn btn-default" id="education_toggle_hide">Hide</button>
</h4>
<div id="education">
<?php if ($education): ?>
<table class="table table-striped table-condensed" id="education_table" cellspacing="0" width="100%">
<thead>
<tr>
<th>Award</th>
<th>Year</th>
<th>Institution</th>
</tr>
</thead>
<tbody>
<?php
foreach ($education as $educ)
{
$date = ($educ['date_obtained']
? date('F Y', strtotime($educ['date_obtained']))
: 'N/A');
echo '<tr>
<td>', $educ['major'], '</td>
<td>', $date, '</td>
<td>', $educ['institution'], '</td>
</tr>';
}
?>
</tbody>
</table>
<?php else: ?>
<div class="alert alert-danger"><p class="text-center">No entry.</p></div>
<?php endif; ?>
</div> | {
"content_hash": "bca64c1ceb26f23e6926cda0840af917",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 102,
"avg_line_length": 23.82051282051282,
"alnum_prop": 0.573735199138859,
"repo_name": "jmgalino/up-oams",
"id": "2d9986595e653531aae444a57f96b8077b38f3dc",
"size": "929",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/views/profile/myprofile/education.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace DpiConverter.Helpers
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using Data;
internal class TrimbleJobXmlHelper
{
public static ICollection<TargetRecord> FindTargetRecords(XDocument document)
{
ICollection<TargetRecord> targetRecordsList = new List<TargetRecord>();
var targetRecords = from target in document.Root
.Elements()
.Where(x => x.Name.LocalName == "FieldBook")
.Elements()
.Where(x => x.Name.LocalName == "TargetRecord")
select target;
foreach (var targetRecord in targetRecords)
{
if (targetRecord.Element("TargetHeight").Value != string.Empty)
{
string targetIndex = targetRecord.Attribute("ID").Value;
double targetHeight = double.Parse(targetRecord.Element("TargetHeight").Value);
TargetRecord currentTargetRecord = new TargetRecord(targetIndex, targetHeight);
targetRecordsList.Add(currentTargetRecord);
}
}
return targetRecordsList;
}
public static ICollection<Station> FindStations(XDocument document)
{
ICollection<Station> stationsList = new List<Station>();
var stations = from station in document.Root
.Elements()
.Where(x => x.Name.LocalName == "FieldBook")
.Elements()
.Where(x => x.Name.LocalName == "StationRecord")
select station;
foreach (var station in stations)
{
string stationIndex = station.Attribute("ID").Value;
string stationName = station.Element("StationName").Value;
double instrumentHeight = double.Parse(station.Element("TheodoliteHeight").Value);
string stationPointCode = string.Empty;
BindingList<Observation> stationObservations = new BindingList<Observation>();
stationsList.Add(new Station(stationIndex, stationPointCode, stationName, instrumentHeight, stationObservations));
}
return stationsList;
}
}
} | {
"content_hash": "59064dc2d86c529c878ecc6840498de8",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 130,
"avg_line_length": 40.45454545454545,
"alnum_prop": 0.5127340823970038,
"repo_name": "Nanich87/DPI-Converter",
"id": "d27d7bddbc791147b20d2fd0a217d034c8e4c911",
"size": "2672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DPIConverter/Helpers/TrimbleJobXmlHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "81642"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p"
android:toXDelta="0"
android:duration="@android:integer/config_shortAnimTime"/>
</set>
| {
"content_hash": "cae66315c069df0e3e96f61ff4818720",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 73,
"avg_line_length": 37.714285714285715,
"alnum_prop": 0.6439393939393939,
"repo_name": "elias-arnold/scampiREST",
"id": "65fb4b505ee4845d7080d185907af8f6d3b286a5",
"size": "264",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/scampi/Scampi-App-Developer-Package-0.4b/example/android/GuerrillaBoards/res/anim/in_from_right.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "584"
},
{
"name": "HTML",
"bytes": "3514"
},
{
"name": "Java",
"bytes": "184135"
},
{
"name": "JavaScript",
"bytes": "2180"
},
{
"name": "Shell",
"bytes": "2390"
}
],
"symlink_target": ""
} |
void foo() {
}
int main(int argc, char **argv) {
int i;
#pragma omp target teams distribute simd nowait( // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute simd nowait (argc)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute simd nowait device (-10u)
for (i = 0; i < argc; ++i) foo();
#pragma omp target teams distribute simd nowait (3.14) device (-10u) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}}
for (i = 0; i < argc; ++i) foo();
return 0;
}
| {
"content_hash": "c4c0a5f856b2b470ed3299c458820c32",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 174,
"avg_line_length": 48.25,
"alnum_prop": 0.6748704663212435,
"repo_name": "youtube/cobalt",
"id": "25daa81eb744788e94dddc84195fd0c0c824cabb",
"size": "885",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "third_party/llvm-project/clang/test/OpenMP/target_teams_distribute_simd_nowait_messages.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.carloan.service;
import com.carloan.service.model_service.ModelServiceFactory;
import com.carloan.service.util_service.UtilServiceFactory;
public interface ServiceFactory {
public static ModelServiceFactory getModelFactory(){
return new ModelServiceFactory();
}
public static UtilServiceFactory getUtilFactory(){
return new UtilServiceFactory();
}
}
| {
"content_hash": "986233a4169ae82beeb42fcca786bca0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 61,
"avg_line_length": 30.46153846153846,
"alnum_prop": 0.7676767676767676,
"repo_name": "Spronghi/software-engineering",
"id": "38af94eef12938eaed4c37e14fd952c167f1b38c",
"size": "396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "carloan/src/com/carloan/service/ServiceFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "218627"
}
],
"symlink_target": ""
} |
.. _analysis:
Analysis routines
=================
In addition to the main pyro program, there are many analysis tools
that we describe here. Note: some problems write a report at the end
of the simulation specifying the analysis routines that can be used
with their data.
* ``compare.py``: this takes two simulation output files as input and
compares zone-by-zone for exact agreement. This is used as part of
the regression testing.
usage: ``./compare.py file1 file2``
* ``plot.py``: this takes an output file as input and plots the data
using the solver's dovis method. It deduces the solver from the
attributes stored in the HDF5 file.
usage: ``./plot.py file``
* ``analysis/``
* ``convergence.py``: this compares two files with different
resolutions (one a factor of 2 finer than the other). It coarsens
the finer data and then computes the norm of the difference. This
is used to test the convergence of solvers.
* ``dam_compare.py``: this takes an output file from the
shallow water dam break problem and plots a slice through the domain
together with the analytic solution (calculated in the script).
usage: ``./dam_compare.py file``
* ``gauss_diffusion_compare.py``: this is for the diffusion solver's
Gaussian diffusion problem. It takes a sequence of output files as
arguments, computes the angle-average, and the plots the resulting
points over the analytic solution for comparison with the exact
result.
usage: ``./gauss_diffusion_compare.py file*``
* ``incomp_converge_error.py``: this is for the incompressible
solver's converge problem. This takes a single output file as
input and compares the velocity field to the analytic solution,
reporting the L2 norm of the error.
usage: ``./incomp_converge_error.py file``
* ``plotvar.py``: this takes a single output file and a variable
name and plots the data for that variable.
usage: ``./plotvar.py file variable``
* ``sedov_compare.py``: this takes an output file from the
compressible Sedov problem, computes the angle-average profile of
the solution and plots it together with the analytic data (read in
from ``cylindrical-sedov.out``).
usage: ``./sedov_compare.py file``
* ``smooth_error.py``: this takes an output file from the advection
solver's smooth problem and compares to the analytic solution,
outputing the L2 norm of the error.
usage: ``./smooth_error.py file``
* ``sod_compare.py``: this takes an output file from the
compressible Sod problem and plots a slice through the domain over
the analytic solution (read in from ``sod-exact.out``).
usage: ``./sod_compare.py file``
| {
"content_hash": "3930a6dbc61a8d1e1dad9f8580158660",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 72,
"avg_line_length": 37.10958904109589,
"alnum_prop": 0.7139165743816906,
"repo_name": "zingale/pyro2",
"id": "3274dfe93edae4f485fd5273c0ed18b24cfc67f6",
"size": "2709",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "docs/source/analysis.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "273"
},
{
"name": "Jupyter Notebook",
"bytes": "1959967"
},
{
"name": "Logos",
"bytes": "1124"
},
{
"name": "Makefile",
"bytes": "2101"
},
{
"name": "Python",
"bytes": "702493"
},
{
"name": "Shell",
"bytes": "217"
},
{
"name": "TeX",
"bytes": "16580"
},
{
"name": "Yacc",
"bytes": "962"
}
],
"symlink_target": ""
} |
/* utptest.c */
/*-
* Copyright (c) 2013
* Nexa Center for Internet & Society, Politecnico di Torino (DAUIN)
* and Simone Basso <bassosimone@gmail.com>.
*
* 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.
*/
/*
* UTP test client and server.
*/
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <errno.h>
#include <err.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "event.h"
#include "strtonum.h"
#include "utp.h"
#define WRITESIZE_MAX (1 << 20)
#define TIMEO_CHECK_INTERVAL 500000
struct TestContext {
u_int lflag;
struct UTPSocket *utpsock;
size_t writesize;
int sock;
};
static void _utp_read(void *, const byte *, size_t);
static void _utp_write(void *, byte *, size_t);
static size_t _utp_get_rb_size(void *);
static void _utp_state(void *, int);
static void _utp_error(void *, int);
static void _utp_overhead(void *, bool, size_t, int);
static void _utp_accept(void *, struct UTPSocket *);
static void _utp_sendto(void *, const u_char *, size_t,
const struct sockaddr *, socklen_t);
static void _libevent_readwrite(int, short, void *);
static void _libevent_quit(int, short, void *);
static void _libevent_timeo(int, short, void *);
struct UTPFunctionTable _UTP_CALLBACKS = {
&_utp_read,
&_utp_write,
&_utp_get_rb_size,
&_utp_state,
&_utp_error,
&_utp_overhead,
};
static void _utp_read(void *opaque, const byte *buf, size_t cnt)
{
/* nothing */ ;
}
static void _utp_write(void *opaque, byte *buf, size_t cnt)
{
memset(buf, 'A', cnt);
}
static size_t _utp_get_rb_size(void *opaque)
{
return (0); /* means: buffer empty */
}
static void _utp_state(void *opaque, int state)
{
struct TestContext *context;
context = (struct TestContext *) opaque;
/*warnx("utp state: %d", state); */
if (!context->lflag && (state == UTP_STATE_WRITABLE ||
state == UTP_STATE_CONNECT))
while (UTP_Write(context->utpsock, context->writesize));
}
static void _utp_error(void *opaque, int error)
{
warnx("utp socket error: %d", error);
}
static void
_utp_overhead(void *opaque, bool sending, size_t count, int type)
{
/* nothing */ ;
}
static void _utp_accept(void *opaque, struct UTPSocket *utpsock)
{
struct TestContext *context;
context = (struct TestContext *) opaque;
if (context->utpsock != NULL) {
warnx("utp: ignore multiple accept attempts");
return;
}
context->utpsock = utpsock;
UTP_SetCallbacks(context->utpsock, &_UTP_CALLBACKS, context);
}
static void
_utp_sendto(void *opaque, const byte *pkt, size_t len,
const struct sockaddr *sa, socklen_t salen)
{
struct TestContext *context;
ssize_t result;
/* TODO: buffer and retry if sendto() fails? */
context = (struct TestContext *) opaque;
result = sendto(context->sock, (char *) pkt, len, 0,
(struct sockaddr *) sa, salen);
if (result < 0)
warn("sendto() failed");
}
static void _libevent_readwrite(int fd, short event, void *opaque)
{
byte buffer[8192];
struct TestContext *context;
ssize_t result;
struct sockaddr_storage sa;
socklen_t salen;
context = (struct TestContext *) opaque;
if ((event & EV_READ) != 0) {
memset(&sa, 0, sizeof(sa));
salen = sizeof(sa);
result = recvfrom(fd, (char *) buffer, sizeof(buffer),
0, (struct sockaddr *) &sa, &salen);
if (result > 0) {
(void) UTP_IsIncomingUTP(_utp_accept, _utp_sendto,
context, buffer, (size_t) result,
(const struct sockaddr *) &sa, salen);
} else
warn("recvfrom() failed");
}
/* Note: At the moment we don't poll for EV_WRITE */
}
static void _libevent_timeo(int fd, short event, void *opaque)
{
struct event *evtimeo;
struct timeval tv;
evtimeo = (struct event *) opaque;
UTP_CheckTimeouts();
memset(&tv, 0, sizeof(tv));
tv.tv_usec = TIMEO_CHECK_INTERVAL;
evtimer_add(evtimeo, &tv);
}
static void _libevent_quit(int fd, short event, void *opaque)
{
exit(0);
}
#define USAGE \
"usage: utptest [-B write-size] [-p local-port] address port\n" \
" utptest -l [-p local-port]\n"
int main(int argc, char *const *argv)
{
int activate;
struct event_base *base;
struct TestContext context;
const char *errstr;
struct event evquit;
struct event evreadwrite;
struct event evtimeo;
int opt;
long long port;
int result;
struct sockaddr_storage salocal;
struct sockaddr_storage saremote;
struct sockaddr_in *sin;
struct timeval tv;
/*
* Init.
*/
memset(&context, 0, sizeof(context));
context.writesize = 1380;
context.sock = -1;
base = event_init();
if (base == NULL)
errx(1, "event_init() failed");
memset(&salocal, 0, sizeof(struct sockaddr_storage));
sin = (struct sockaddr_in *) &salocal;
sin->sin_family = AF_INET;
sin->sin_port = htons(54321);
memset(&saremote, 0, sizeof(struct sockaddr_storage));
sin = (struct sockaddr_in *) &saremote;
sin->sin_family = AF_INET;
/*
* Process command line options.
*/
while ((opt = getopt(argc, argv, "B:lp:")) >= 0) {
switch (opt) {
case 'B':
context.writesize = openbsd_strtonum(optarg,
0, WRITESIZE_MAX, &errstr);
if (errstr)
errx(1, "writesize is %s", errstr);
break;
case 'l':
context.lflag = 1;
break;
case 'p':
sin = (struct sockaddr_in *) &salocal;
port = openbsd_strtonum(optarg, 1024, 65535, &errstr);
if (errstr)
errx(1, "port is %s", errstr);
sin->sin_port = htons((u_int16_t) port);
break;
default:
fprintf(stderr, "%s", USAGE);
exit(1);
}
}
argc -= optind;
argv += optind;
if ((context.lflag && argc > 0) || (!context.lflag && argc != 2)) {
fprintf(stderr, "%s", USAGE);
exit(1);
}
if (!context.lflag) {
sin = (struct sockaddr_in *) &saremote;
result = inet_pton(AF_INET, argv[0], &sin->sin_addr);
if (result != 1)
errx(1, "inet_pton() failed");
port = openbsd_strtonum(argv[1], 1024, 65535, &errstr);
if (errstr)
errx(1, "port is %s", errstr);
sin->sin_port = htons((u_int16_t) port);
}
/*
* Create the socket.
*/
context.sock = socket(AF_INET, SOCK_DGRAM, 0);
if (context.sock == -1)
err(1, "socket() failed");
result = evutil_make_socket_nonblocking(context.sock);
if (result != 0)
return (result);
activate = 1;
result = setsockopt(context.sock, SOL_SOCKET, SO_REUSEADDR,
&activate, sizeof(activate));
if (result != 0)
err(1, "setsockopt() failed");
sin = (struct sockaddr_in *) &salocal;
result = bind(context.sock, (struct sockaddr *) sin, sizeof(*sin));
if (result != 0)
err(1, "bind() failed");
if (!context.lflag) {
sin = (struct sockaddr_in *) &saremote;
context.utpsock = UTP_Create(_utp_sendto, &context,
(struct sockaddr *) sin,
sizeof(*sin));
if (context.utpsock == NULL)
errx(1, "UTP_Create() failed");
UTP_SetCallbacks(context.utpsock, &_UTP_CALLBACKS,
&context);
UTP_Connect(context.utpsock);
}
/*
* Create and dispatch the events.
*/
event_set(&evreadwrite, context.sock, EV_READ | EV_PERSIST,
_libevent_readwrite, &context);
event_add(&evreadwrite, NULL);
if (!context.lflag) {
evtimer_set(&evquit, _libevent_quit, NULL);
memset(&tv, 0, sizeof(tv));
tv.tv_sec = 180;
evtimer_add(&evquit, &tv);
}
evtimer_set(&evtimeo, _libevent_timeo, &evtimeo);
memset(&tv, 0, sizeof(tv));
tv.tv_usec = TIMEO_CHECK_INTERVAL;
evtimer_add(&evtimeo, &tv);
warnx("libevent method: %s", event_base_get_method(base));
event_dispatch();
return (0);
}
| {
"content_hash": "8d38048e451b3b8fa877e61d81dcd24c",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 78,
"avg_line_length": 29.810198300283286,
"alnum_prop": 0.5310272735911812,
"repo_name": "bassosimone/utpintro",
"id": "67522c991a1f10aba9ff201d35d5e15ed0f2077c",
"size": "10523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utptest.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37943"
},
{
"name": "Makefile",
"bytes": "3028"
},
{
"name": "Perl",
"bytes": "3829"
},
{
"name": "Shell",
"bytes": "2894"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 06 17:51:16 PST 2013 -->
<TITLE>
DataFuException (DataFu 1.1.0)
</TITLE>
<META NAME="date" CONTENT="2013-11-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DataFuException (DataFu 1.1.0)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/DataFuException.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../datafu/pig/util/ContextualEvalFunc.html" title="class in datafu.pig.util"><B>PREV CLASS</B></A>
<A HREF="../../../datafu/pig/util/FieldNotFound.html" title="class in datafu.pig.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?datafu/pig/util/DataFuException.html" target="_top"><B>FRAMES</B></A>
<A HREF="DataFuException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
datafu.pig.util</FONT>
<BR>
Class DataFuException</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.Throwable
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.Exception
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.RuntimeException
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>datafu.pig.util.DataFuException</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>DataFuException</B><DT>extends java.lang.RuntimeException</DL>
</PRE>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#datafu.pig.util.DataFuException">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#DataFuException()">DataFuException</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#DataFuException(java.lang.String)">DataFuException</A></B>(java.lang.String message)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#DataFuException(java.lang.String, java.lang.Throwable)">DataFuException</A></B>(java.lang.String message,
java.lang.Throwable cause)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#DataFuException(java.lang.Throwable)">DataFuException</A></B>(java.lang.Throwable cause)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.Object</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#getData()">getData</A></B>()</CODE>
<BR>
Gets data relevant to this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.Map<java.lang.String,java.lang.Integer></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#getFieldAliases()">getFieldAliases</A></B>()</CODE>
<BR>
Gets field aliases for a UDF which may be relevant to this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#setData(java.lang.Object)">setData</A></B>(java.lang.Object data)</CODE>
<BR>
Sets data relevant to this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#setFieldAliases(java.util.Map)">setFieldAliases</A></B>(java.util.Map<java.lang.String,java.lang.Integer> fieldAliases)</CODE>
<BR>
Sets field aliases for a UDF which may be relevant to this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../datafu/pig/util/DataFuException.html#toString()">toString</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Throwable"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Throwable</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="DataFuException()"><!-- --></A><H3>
DataFuException</H3>
<PRE>
public <B>DataFuException</B>()</PRE>
<DL>
</DL>
<HR>
<A NAME="DataFuException(java.lang.String)"><!-- --></A><H3>
DataFuException</H3>
<PRE>
public <B>DataFuException</B>(java.lang.String message)</PRE>
<DL>
</DL>
<HR>
<A NAME="DataFuException(java.lang.String, java.lang.Throwable)"><!-- --></A><H3>
DataFuException</H3>
<PRE>
public <B>DataFuException</B>(java.lang.String message,
java.lang.Throwable cause)</PRE>
<DL>
</DL>
<HR>
<A NAME="DataFuException(java.lang.Throwable)"><!-- --></A><H3>
DataFuException</H3>
<PRE>
public <B>DataFuException</B>(java.lang.Throwable cause)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getFieldAliases()"><!-- --></A><H3>
getFieldAliases</H3>
<PRE>
public java.util.Map<java.lang.String,java.lang.Integer> <B>getFieldAliases</B>()</PRE>
<DL>
<DD>Gets field aliases for a UDF which may be relevant to this exception.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>field aliases</DL>
</DD>
</DL>
<HR>
<A NAME="getData()"><!-- --></A><H3>
getData</H3>
<PRE>
public java.lang.Object <B>getData</B>()</PRE>
<DL>
<DD>Gets data relevant to this exception.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>data</DL>
</DD>
</DL>
<HR>
<A NAME="setFieldAliases(java.util.Map)"><!-- --></A><H3>
setFieldAliases</H3>
<PRE>
public void <B>setFieldAliases</B>(java.util.Map<java.lang.String,java.lang.Integer> fieldAliases)</PRE>
<DL>
<DD>Sets field aliases for a UDF which may be relevant to this exception.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>fieldAliases</CODE> - </DL>
</DD>
</DL>
<HR>
<A NAME="setData(java.lang.Object)"><!-- --></A><H3>
setData</H3>
<PRE>
public void <B>setData</B>(java.lang.Object data)</PRE>
<DL>
<DD>Sets data relevant to this exception.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>data</CODE> - </DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public java.lang.String <B>toString</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>toString</CODE> in class <CODE>java.lang.Throwable</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/DataFuException.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../datafu/pig/util/ContextualEvalFunc.html" title="class in datafu.pig.util"><B>PREV CLASS</B></A>
<A HREF="../../../datafu/pig/util/FieldNotFound.html" title="class in datafu.pig.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?datafu/pig/util/DataFuException.html" target="_top"><B>FRAMES</B></A>
<A HREF="DataFuException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Matthew Hayes, Sam Shah
</BODY>
</HTML>
| {
"content_hash": "7e3fc31bb0324b98f9c312c102483eb1",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 205,
"avg_line_length": 37.86069651741293,
"alnum_prop": 0.640473061760841,
"repo_name": "shaohua-zhang/incubator-datafu",
"id": "0e32b0f16e68ced970afeec1fedac93ed9f4bc32",
"size": "15220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/source/docs/datafu/1.1.0/datafu/pig/util/DataFuException.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7050"
},
{
"name": "HTML",
"bytes": "7215451"
},
{
"name": "Java",
"bytes": "1342966"
},
{
"name": "JavaScript",
"bytes": "863"
},
{
"name": "Ruby",
"bytes": "11981"
},
{
"name": "Shell",
"bytes": "1755"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>abp: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / abp - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
abp
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2020-07-27 01:07:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-27 01:07:00 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/abp"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ABP"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:alternating bit protocol" "keyword:process calculi" "keyword:reactive systems" "keyword:coinductive types" "keyword:coinduction" "category:Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols" ]
authors: [ "Eduardo Giménez <>" ]
bug-reports: "https://github.com/coq-contribs/abp/issues"
dev-repo: "git+https://github.com/coq-contribs/abp.git"
synopsis: "A verification of the alternating bit protocol expressed in CBS"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/abp/archive/v8.5.0.tar.gz"
checksum: "md5=9df2a01467f74d04c7eaeec6ebf6d2d9"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-abp.8.5.0 coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-abp -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-abp.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "b2f65a6a30763d814235d9980682409d",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 302,
"avg_line_length": 42.123456790123456,
"alnum_prop": 0.5402989449003517,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3b7795889cbb4cc5c2f63032993bce4587750366",
"size": "6850",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/extra-dev/8.11.dev/abp/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
USING_NS_CC;
using namespace ui;
WidgetTextfieldLayer::WidgetTextfieldLayer()
{
}
WidgetTextfieldLayer::~WidgetTextfieldLayer()
{
}
bool WidgetTextfieldLayer::init()
{
Director* dire = Director::getInstance();
Rect visibleRect = dire->getOpenGLView()->getVisibleRect();
Size visibleSize = dire->getVisibleSize();
Vec2 origin = dire->getVisibleOrigin();
int index = 2;
LabelTTF* label = LabelTTF::create("Label", "Marker Felt.ttf", 25);
Vec2 showingBase = Vec2(visibleRect.origin.x + visibleRect.size.width * 0.5f, visibleRect.origin.y + visibleRect.size.height * 0.5f);
label->setPosition(showingBase.x, showingBase.y - 30);
addChild(label, 1);
label = LabelTTF::create("MainMenu", "Marker Felt.ttf", 25);
MenuItemLabel* menuItem = MenuItemLabel::create(label);
menuItem->setCallback([&](cocos2d::Ref *sender) {
this->setVisible(false);
Scene* scene = Director::getInstance()->getRunningScene();
Layer* rootLayer = (Layer*)scene->getChildByName("rootLayer");
rootLayer->setVisible(true);
});
Menu* menu = Menu::create(menuItem, nullptr);
menu->setPosition(Vec2::ZERO);
menuItem->setPosition(Vec2(visibleRect.origin.x + visibleRect.size.width - 80, visibleRect.origin.y + 25));
addChild(menu, 1);
// This is for Labels section of Programmers guide;
// 1. BMFont;
TextField* textField = TextField::create("Text Field", "Marker Felt.ttf", 30);
textField->setMaxLength(25);
textField->setPosition(Vec2(showingBase.x, showingBase.y - (++index) * 40));
addChild(textField, 2);
return true;
} | {
"content_hash": "8de3af5f23cc28838f56a223087c9b55",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 134,
"avg_line_length": 31.163265306122447,
"alnum_prop": 0.7229862475442044,
"repo_name": "zoozooll/cocos2dx_exercise",
"id": "f203bd428d861d926de44802eb006f6e463ca0fb",
"size": "1587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/WidgetTextfieldLayer.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1097"
},
{
"name": "C#",
"bytes": "31686"
},
{
"name": "C++",
"bytes": "202581"
},
{
"name": "CMake",
"bytes": "4946"
},
{
"name": "Java",
"bytes": "1494"
},
{
"name": "Makefile",
"bytes": "1744"
},
{
"name": "Objective-C",
"bytes": "1889"
},
{
"name": "Objective-C++",
"bytes": "9657"
},
{
"name": "Python",
"bytes": "5740"
}
],
"symlink_target": ""
} |
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
src: local('Open Sans Light'), local('OpenSans-Light'), url(http://fonts.gstatic.com/s/opensans/v10/DXI1ORHCpsQm3Vp6mXoaTXhCUOGz7vYGh680lGh-uXM.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(http://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3T8E0i7KZn-EPnyo3HZu7kw.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(http://fonts.gstatic.com/s/opensans/v10/k3k702ZOKiLJc3WVjuplzHhCUOGz7vYGh680lGh-uXM.woff) format('woff');
}
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
src: local('Open Sans Light Italic'), local('OpenSansLight-Italic'), url(http://fonts.gstatic.com/s/opensans/v10/PRmiXeptR36kaC0GEAetxh_xHqYgAV9Bl_ZQbYUxnQU.woff) format('woff');
}
| {
"content_hash": "8f89cfd355e80d9f14e0ddc57022f724",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 180,
"avg_line_length": 42.125,
"alnum_prop": 0.7230464886251237,
"repo_name": "tommyeap/ci_template",
"id": "9b7cc19a0ae5f6f6a451219ac983eae86a1234a3",
"size": "1011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/css/font.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "758"
},
{
"name": "CSS",
"bytes": "182865"
},
{
"name": "HTML",
"bytes": "5633"
},
{
"name": "JavaScript",
"bytes": "9022"
},
{
"name": "PHP",
"bytes": "1845246"
}
],
"symlink_target": ""
} |
import {Component, EventEmitter} from 'angular2/core';
import {PlaylistComponent} from 'app/component/playlist.component';
import {ExplorerComponent} from 'app/component/explorer.component';
@Component({
selector: '[audio-tab]',
template: `
<section explorer
[class.active]="isExplorerActive"
[fileType]="'audio'"
[addFileEvent]="addFileEvent"
[playFileQueueEvent]="playFileQueueEvent"
[deleteItemSubject]="deleteItemSubject"
(click)="isExplorerActive=true">
</section>
<section playlist
[class.inactive]="isExplorerActive"
[fileType]="'audio'"
[addFileEvent]="addFileEvent"
[playingItemChangedEvent]="playingItemChangedEvent"
[playFileQueueEvent]="playFileQueueEvent"
[playNextTrackEvent]="playNextTrackEvent"
[playPrevTrackEvent]="playPrevTrackEvent"
[deleteItemSubject]="deleteItemSubject"
(click)="isExplorerActive=false">
</section>
`,
directives: [ExplorerComponent, PlaylistComponent],
inputs: ['playingItemChangedEvent', 'playFileQueueEvent', 'playNextTrackEvent', 'playPrevTrackEvent', 'deleteItemSubject']
})
export class AudioTab {
constructor() {
this.isExplorerActive = false;
this.addFileEvent = new EventEmitter();
}
} | {
"content_hash": "5c35523dd58fded80ce00cf1937a9ff3",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 123,
"avg_line_length": 30.794871794871796,
"alnum_prop": 0.7502081598667777,
"repo_name": "alex-dwt/CarMultimediaSystem",
"id": "7920955fa447a4bc18399925aa094f2c985a2c34",
"size": "1443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/tab/audio.tab.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "31043"
},
{
"name": "HTML",
"bytes": "957"
},
{
"name": "JavaScript",
"bytes": "92320"
},
{
"name": "Shell",
"bytes": "6796"
}
],
"symlink_target": ""
} |
[ ](https://codeship.com/projects/116533) [](https://scrutinizer-ci.com/g/partner-it/b2-php/?branch=master) [](https://scrutinizer-ci.com/g/partner-it/b2-php/?branch=master)
# Backblaze B2 PHP wrapper
## Installation
```
composer require partner-it/b2-php
```
## Setup
Instantiate a new client and get a token:
```php
$client = new \B2\B2Client('accountid', 'applicationKey');
$client->requestToken();
```
### Upload a file
```php
$client->Files->uploadFile('bucketId', '/my/local/path/image.jpg', 'image.jpg', 'image/jpeg');
```
### Dowload a file
Download a file by name:
```php
$data = $b2Client->Files->downloadFileByName('bucketname', 'image.jpg');
```
| {
"content_hash": "5276babcdda4fd66404577cd002000db",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 504,
"avg_line_length": 26.473684210526315,
"alnum_prop": 0.7137176938369781,
"repo_name": "partner-it/b2-php",
"id": "540cca176924d1bbd063857976382a7dc125eab9",
"size": "1007",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "15041"
}
],
"symlink_target": ""
} |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections.Generic;
using System.Web;
#endregion
namespace SageFrame.Application
{
/// <summary>
/// Options for application release mode.
/// </summary>
public enum ReleaseMode
{
None,
Alpha,
Beta,
RC,
Stable,
}
[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyStatusAttribute : System.Attribute
{
private ReleaseMode _releaseMode;
/// <summary>
/// Initializes a new instance of the application status.
/// </summary>
/// <param name="releaseMode">Release mode.</param>
public AssemblyStatusAttribute(ReleaseMode releaseMode)
{
_releaseMode = releaseMode;
}
/// <summary>
/// Get release mode.
/// </summary>
public ReleaseMode Status
{
get
{
return _releaseMode;
}
}
}
}
| {
"content_hash": "0b8e9f45d4cc26fca7e63dd59695be2f",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 91,
"avg_line_length": 21.73076923076923,
"alnum_prop": 0.5761061946902655,
"repo_name": "SageFrame/SageFrame",
"id": "f03659cda92e7c13feb2a9c1121844e6c66035ae",
"size": "1132",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "SageFrame.Common/Application/AssemblyStatusAttribute.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1554707"
},
{
"name": "ApacheConf",
"bytes": "768"
},
{
"name": "C#",
"bytes": "4514389"
},
{
"name": "CSS",
"bytes": "805481"
},
{
"name": "ColdFusion",
"bytes": "7712"
},
{
"name": "HTML",
"bytes": "466859"
},
{
"name": "JavaScript",
"bytes": "4646118"
},
{
"name": "PHP",
"bytes": "5655"
},
{
"name": "Perl",
"bytes": "4746"
}
],
"symlink_target": ""
} |
import { Disposable } from 'vs/base/common/lifecycle';
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
import { IExtensionManagementService } from 'vs/platform/extensionManagement/common/extensionManagement';
export class DeprecatedExtensionsCleaner extends Disposable {
constructor(
@IExtensionManagementService private readonly extensionManagementService: ExtensionManagementService
) {
super();
this._register(extensionManagementService); // TODO@sandy081 this seems fishy
this.cleanUpDeprecatedExtensions();
}
private cleanUpDeprecatedExtensions(): void {
this.extensionManagementService.removeDeprecatedExtensions();
}
}
| {
"content_hash": "180abd610b6b4956c3671283a1504e2e",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 109,
"avg_line_length": 32.27272727272727,
"alnum_prop": 0.8183098591549296,
"repo_name": "Krzysztof-Cieslak/vscode",
"id": "0ffa0870e955f6982de82052c146c0377ef008bf",
"size": "1061",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/vs/code/electron-browser/sharedProcess/contrib/deprecatedExtensionsCleaner.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5369"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "488"
},
{
"name": "C++",
"bytes": "1072"
},
{
"name": "CSS",
"bytes": "492454"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "Dockerfile",
"bytes": "425"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "652"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "47005"
},
{
"name": "Inno Setup",
"bytes": "165483"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "872486"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "2127"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "857"
},
{
"name": "Perl 6",
"bytes": "1065"
},
{
"name": "PowerShell",
"bytes": "6430"
},
{
"name": "Python",
"bytes": "2405"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Roff",
"bytes": "351"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "532"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "25657"
},
{
"name": "Swift",
"bytes": "284"
},
{
"name": "TypeScript",
"bytes": "21067343"
},
{
"name": "Visual Basic",
"bytes": "893"
}
],
"symlink_target": ""
} |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;
/**
* MsoDebugOptions.
*
*/
@CoInterface(guid="{000C035A-0000-0000-C000-000000000046}")
public interface MsoDebugOptions extends IDispatch {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(1610743808) public IDispatch getApplication() throws ComException;
@DeclDISPID(1610743809) public Integer getCreator() throws ComException;
@DeclDISPID(5) public Boolean getOutputToDebugger() throws ComException;
@DeclDISPID(5) public void setOutputToDebugger(final Boolean value) throws ComException;
@DeclDISPID(6) public Boolean getOutputToFile() throws ComException;
@DeclDISPID(6) public void setOutputToFile(final Boolean value) throws ComException;
@DeclDISPID(7) public Boolean getOutputToMessageBox() throws ComException;
@DeclDISPID(7) public void setOutputToMessageBox(final Boolean value) throws ComException;
@DeclDISPID(8) public Object getUnitTestManager() throws ComException;
@DeclDISPID(9) public void AddIgnoredAssertTag(final String bstrTagToIgnore) throws ComException;
@DeclDISPID(10) public void RemoveIgnoredAssertTag(final String bstrTagToIgnore) throws ComException;
}
| {
"content_hash": "4f1d8a04091f5e561897f5725140cac8",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 104,
"avg_line_length": 55.30434782608695,
"alnum_prop": 0.7735849056603774,
"repo_name": "wolfgangimig/joa",
"id": "968a303c063d2a147d2c110090654b98a0179c26",
"size": "1272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/joa/src-gen/com/wilutions/mslib/office/MsoDebugOptions.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1296"
},
{
"name": "CSS",
"bytes": "792"
},
{
"name": "HTML",
"bytes": "1337"
},
{
"name": "Java",
"bytes": "9952275"
},
{
"name": "VBScript",
"bytes": "338"
}
],
"symlink_target": ""
} |
WPDMZ
=====
Tracking the human:edit funnel.
| {
"content_hash": "3f031492ab26e4ca2d8521b002b20229",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 31,
"avg_line_length": 11.25,
"alnum_prop": 0.6888888888888889,
"repo_name": "yuvipanda/edit-stats",
"id": "53b6ea9ac164802a7d766e82d5f3710ffc0eaa26",
"size": "45",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "12228"
}
],
"symlink_target": ""
} |
SELECT e.FirstName + ' ' + e.LastName AS Employee,
m.FirstName + ' ' + m.LastName as Manager,
AddressText
FROM [TelerikAcademy].[dbo].[Employees] e
INNER JOIN [TelerikAcademy].[dbo].[Employees] m
ON m.EmployeeID = e.ManagerID
INNER JOIN [TelerikAcademy].[dbo].[Addresses] a
ON e.AddressID = a.AddressID | {
"content_hash": "d1e8780c6961c354de42cca81fc30053",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 51,
"avg_line_length": 39.25,
"alnum_prop": 0.7070063694267515,
"repo_name": "svetlai/TelerikAcademy",
"id": "7b8d481bd27383f1a764895fea2f2cb4b2ee539f",
"size": "470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Software-Technologies/Databases/03-SQL-Intro/3. SQL Intro Solution/21-SelectEmployeesWithTheirManagerAndAddress.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "251046"
},
{
"name": "Batchfile",
"bytes": "37"
},
{
"name": "C#",
"bytes": "5866409"
},
{
"name": "CSS",
"bytes": "128738"
},
{
"name": "CoffeeScript",
"bytes": "70"
},
{
"name": "HTML",
"bytes": "337095"
},
{
"name": "JavaScript",
"bytes": "2326558"
},
{
"name": "Objective-C",
"bytes": "14987"
},
{
"name": "PLSQL",
"bytes": "13508"
},
{
"name": "Shell",
"bytes": "37"
},
{
"name": "XSLT",
"bytes": "3316"
}
],
"symlink_target": ""
} |
__all__ = ['rightclickmenu.RightClickMenu']
| {
"content_hash": "4d2cedac443ca41cf9ab5d5d370e7d00",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 43,
"avg_line_length": 44,
"alnum_prop": 0.7045454545454546,
"repo_name": "Errantgod/azaharTEA",
"id": "c68915543d403e05b5ebd5f855336910b2ff5224",
"size": "44",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "editorcontainer/rightclickmenu/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "77665"
}
],
"symlink_target": ""
} |
package com.haulmont.cuba.web.widgets.client.grid;
public interface HasClickSettings {
boolean isClickThroughEnabled();
void setClickThroughEnabled(boolean enabled);
}
| {
"content_hash": "8a6dce4b0c0b67b51b2e62ff31690d3d",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 50,
"avg_line_length": 18.1,
"alnum_prop": 0.7790055248618785,
"repo_name": "cuba-platform/cuba",
"id": "d7eabb78258910d92f3a204b4bb1b13535666fca",
"size": "782",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/web-toolkit/src/com/haulmont/cuba/web/widgets/client/grid/HasClickSettings.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "77"
},
{
"name": "CSS",
"bytes": "68"
},
{
"name": "FreeMarker",
"bytes": "3996"
},
{
"name": "GAP",
"bytes": "20634"
},
{
"name": "Groovy",
"bytes": "897992"
},
{
"name": "HTML",
"bytes": "6464"
},
{
"name": "Java",
"bytes": "20605191"
},
{
"name": "PLSQL",
"bytes": "30678"
},
{
"name": "PLpgSQL",
"bytes": "1333"
},
{
"name": "SCSS",
"bytes": "306671"
},
{
"name": "Shell",
"bytes": "88"
},
{
"name": "XSLT",
"bytes": "63258"
}
],
"symlink_target": ""
} |
'''!
@brief frontend forms
@date Created on Aug , 2016
@author [Ryu-CZ](https://github.com/Ryu-CZ)
'''
import flask
import markdown
import datetime as dt
from flask_mongoengine import Document
from mongoengine import fields, NULLIFY
from werkzeug import generate_password_hash
class User(Document):
nickname = fields.StringField(required=True, max_length=50)
first_name = fields.StringField(required=True, max_length=50)
last_name = fields.StringField(required=True, max_length=50)
email = fields.EmailField(required=True)
city = fields.StringField(max_length=80)
country = fields.StringField(max_length=80)
pw_hash = fields.StringField(required=True)
created = fields.DateTimeField(required=True)
admin = fields.BooleanField()
def __init__(self, status=1, admin=True, *args, **kw):
super(User, self).__init__(*args, **kw)
self.status = status
self.admin = admin
def full_name(self):
return '%s %s' % (self.first_name, self.last_name)
def is_authenticated(self):
return True
def is_admin(self):
return self.admin
def is_active(self):
return self.status > 0
def is_anonymous(self):
return False
def mask_password(self, password=None):
if password:
return generate_password_hash(password)
return generate_password_hash(self.password)
def get_id(self):
return unicode(self.nickname)
def as_player(self):
r = {'nickname':self.nickname,
'first_name':self.first_name,
'last_name':self.last_name,
'email':self.email,
'city':self.city,
'country':self.country,
'created':self.created,
'admin':self.admin
}
if self.password:
r['pw_hash'] = self.mask_password()
return r
def __repr__(self):
return '<User: {}>'.format(self.nickname.encode())
def __str__(self):
return '<User: {} ({})>'.format(self.nickname, self.full_name())
class WikiDoc(Document):
title = fields.StringField(required=True, max_length=62)
name = fields.StringField(required=True, max_length=62)
create_date = fields.DateTimeField(required=True)
edit_date = fields.DateTimeField(required=True, default=dt.datetime.utcnow)
author_id = fields.ReferenceField('User')
text = fields.StringField(required=True, default='')
User.register_delete_rule(WikiDoc, 'author', NULLIFY)
class Image(Document):
name = fields.StringField(required=True, unique=True,
max_length=62,
placeholder='Unique name of file')
extension = fields.StringField(required=True, max_length=6)
author_id = fields.ReferenceField('User')
created = fields.DateTimeField(required=True, default=dt.datetime.utcnow)
description = fields.StringField(required=False, default='')
file = fields.ImageField(size=(2048, 2048, True),
thumbnail_size=(200,200, True),
collection_name='image')
def full_name(self):
return '{}.{}'.format(self.name, self.extension)
User.register_delete_rule(Image, 'author', NULLIFY)
class Character(Document):
name = fields.StringField(required=True, unique=True,
max_length=62,
placeholder='Unique name of character')
slug = fields.StringField(required=True, unique=True,
max_length=62,
placeholder='url-item-name')
image_id = fields.ReferenceField('Image')
owner_id = fields.ReferenceField('User')
create_date = fields.DateTimeField(required=True)
edit_date = fields.DateTimeField(required=True, default=dt.datetime.utcnow)
quick_desription = fields.StringField(required=False, default='') #short char description
desription = fields.StringField(required=False, default='') #markdown char description
biography = fields.StringField(required=False, default='') #markdown char history
tags = fields.ListField(fields.StringField())
is_player = fields.BooleanField(required=True, defauld=False)
gender = fields.StringField(required=False, defauld=None)
def html_biography(self):
return flask.Markup(markdown.markdown(self.biography))
def html_desription(self):
return flask.Markup(markdown.markdown(self.desription))
Image.register_delete_rule(Character, 'image_id', NULLIFY)
User.register_delete_rule(Character, 'owner_id', NULLIFY) | {
"content_hash": "a191918d8bba85993ad9e82dd5aa1fc8",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 93,
"avg_line_length": 36.496062992125985,
"alnum_prop": 0.6405609492988134,
"repo_name": "Ryu-CZ/flask-dnd",
"id": "0e9d30ac06f8d31a5ab8dcbdb991145fad809315",
"size": "4659",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dnd/docs.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5789"
},
{
"name": "HTML",
"bytes": "27993"
},
{
"name": "JavaScript",
"bytes": "597"
},
{
"name": "Python",
"bytes": "42799"
}
],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Spot;
/**
* SpotSearch represents the model behind the search form about `app\models\Spot`.
*/
class SpotSearch extends Spot
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['spot_id'], 'integer'],
[['spot_name', 'spot_city'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Spot::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'spot_id' => $this->spot_id,
]);
$query->andFilterWhere(['like', 'spot_name', $this->spot_name])
->andFilterWhere(['like', 'spot_city', $this->spot_city]);
return $dataProvider;
}
}
| {
"content_hash": "7250400907b13f7f0f3d1b83defc6d02",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 106,
"avg_line_length": 21.71641791044776,
"alnum_prop": 0.5374570446735395,
"repo_name": "boylee1111/Reservation",
"id": "755ce09aa44759bd5fbca33c1cb20828fdf49ebd",
"size": "1455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frontend/models/SpotSearch.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "199"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "2728"
},
{
"name": "PHP",
"bytes": "385371"
}
],
"symlink_target": ""
} |
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { createDecorator, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookEditor, INotebookEditorCreationOptions } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { Event } from 'vs/base/common/event';
import { Dimension } from 'vs/base/browser/dom';
export const INotebookEditorService = createDecorator<INotebookEditorService>('INotebookEditorWidgetService');
export interface IBorrowValue<T> {
readonly value: T | undefined;
}
export interface INotebookEditorService {
_serviceBrand: undefined;
retrieveWidget(accessor: ServicesAccessor, group: IEditorGroup, input: NotebookEditorInput, creationOptions?: INotebookEditorCreationOptions, dimension?: Dimension): IBorrowValue<INotebookEditor>;
onDidAddNotebookEditor: Event<INotebookEditor>;
onDidRemoveNotebookEditor: Event<INotebookEditor>;
addNotebookEditor(editor: INotebookEditor): void;
removeNotebookEditor(editor: INotebookEditor): void;
getNotebookEditor(editorId: string): INotebookEditor | undefined;
listNotebookEditors(): readonly INotebookEditor[];
}
| {
"content_hash": "538794d978ef6af0c9e4dde1cf737ed3",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 197,
"avg_line_length": 47.44444444444444,
"alnum_prop": 0.8212334113973458,
"repo_name": "microsoft/vscode",
"id": "ac80184de3e8b0ed80b11c3b457883b6a35ade7b",
"size": "1632",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/vs/workbench/contrib/notebook/browser/services/notebookEditorService.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "19488"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "709"
},
{
"name": "C++",
"bytes": "2745"
},
{
"name": "CSS",
"bytes": "694473"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "Cuda",
"bytes": "3634"
},
{
"name": "Dart",
"bytes": "324"
},
{
"name": "Dockerfile",
"bytes": "475"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "652"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "386747"
},
{
"name": "Hack",
"bytes": "16"
},
{
"name": "Handlebars",
"bytes": "1064"
},
{
"name": "Inno Setup",
"bytes": "307296"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "956022"
},
{
"name": "Julia",
"bytes": "940"
},
{
"name": "Jupyter Notebook",
"bytes": "929"
},
{
"name": "Less",
"bytes": "1029"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "2252"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "Objective-C++",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "1922"
},
{
"name": "PowerShell",
"bytes": "13597"
},
{
"name": "Pug",
"bytes": "654"
},
{
"name": "Python",
"bytes": "2171"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Roff",
"bytes": "351"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "301179"
},
{
"name": "SCSS",
"bytes": "6732"
},
{
"name": "Scilab",
"bytes": "54706"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "63596"
},
{
"name": "Swift",
"bytes": "284"
},
{
"name": "TeX",
"bytes": "1602"
},
{
"name": "TypeScript",
"bytes": "43400033"
},
{
"name": "Visual Basic .NET",
"bytes": "893"
}
],
"symlink_target": ""
} |
using System.Diagnostics;
using System.Runtime.Serialization;
namespace BinInfo.Models
{
/// <summary>
/// Brief information about the bank who issued the card
/// </summary>
[DataContract]
[DebuggerDisplay("Name: {Name}, City: {City}")]
public class BankInformation
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name="url")]
public string Url { get; set; }
[DataMember(Name = "phone")]
public string Phone { get; set; }
[DataMember(Name = "city")]
public string City { get; set; }
}
} | {
"content_hash": "2a27157d547aa9626a94cb355820e941",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 60,
"avg_line_length": 24.6,
"alnum_prop": 0.5886178861788618,
"repo_name": "gustavofrizzo/BinInfo",
"id": "451449a3c4c05711a13a560e5858ef9d083d0b23",
"size": "617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BinInfo/Models/BankInformation.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10486"
}
],
"symlink_target": ""
} |
* [Lawyers certification webinar in Russian. March, 2020](/#!/webinars/001) | {
"content_hash": "ca4089b4efff2755acef1d4bf6c3d026",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 75,
"avg_line_length": 75,
"alnum_prop": 0.7466666666666667,
"repo_name": "Cryptonomica/cryptonomica",
"id": "ed8a105e9ee7c4f6f62b213b3fcab39b5b71d5ff",
"size": "106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/webapp/app/webinars/webinars.list.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100600"
},
{
"name": "HTML",
"bytes": "629937"
},
{
"name": "Java",
"bytes": "749347"
},
{
"name": "JavaScript",
"bytes": "689163"
},
{
"name": "Shell",
"bytes": "15636"
},
{
"name": "Solidity",
"bytes": "252127"
}
],
"symlink_target": ""
} |
<?php $this->pageTitle="修改密码";?>
<div class="subheader">
<h1>修改密码</h1>
</div>
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($form); ?>
<div class="row">
<?php echo CHtml::activeLabelEx($form,'password'); ?>
<?php echo CHtml::activePasswordField($form,'password'); ?>
<p class="hint">
<?php echo "密码至少4个字符"; ?>
</p>
</div>
<div class="row">
<?php echo CHtml::activeLabelEx($form,'verifyPassword'); ?>
<?php echo CHtml::activePasswordField($form,'verifyPassword'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton("提交"); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form --> | {
"content_hash": "7c38914631cdee8b8c178b62d523b0a4",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 66,
"avg_line_length": 22.9,
"alnum_prop": 0.5924308588064047,
"repo_name": "snowpine/qanswer",
"id": "3ed0bd381fa3c677c745e97d925c610a115cd837",
"size": "721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/users/changepassword.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "38971"
},
{
"name": "JavaScript",
"bytes": "295093"
},
{
"name": "PHP",
"bytes": "1360645"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <!-- Use Chrome Frame in IE -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<meta name="description" content="Draw polylines with various widths and materials.">
<meta name="cesium-sandcastle-labels" content="Geometries">
<title>Cesium Demo</title>
<script type="text/javascript" src="../Sandcastle-header.js"></script>
<script type="text/javascript" src="../../../ThirdParty/requirejs-2.1.9/require.js"></script>
<script type="text/javascript">
require.config({
baseUrl : '../../../Source',
waitSeconds : 60
});
</script>
</head>
<body class="sandcastle-loading" data-sandcastle-bucket="bucket-requirejs.html">
<style>
@import url(../templates/bucket.css);
</style>
<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar"></div>
<script id="cesium_sandcastle_script">
function startup(Cesium) {
"use strict";
//Sandcastle_Begin
var viewer = new Cesium.Viewer('cesiumContainer');
var redLine = viewer.entities.add({
name : 'Red line on the surface',
polyline : {
positions : Cesium.Cartesian3.fromDegreesArray([-75, 35,
-125, 35]),
width : 5,
material : Cesium.Color.RED
}
});
var glowingLine = viewer.entities.add({
name : 'Glowing blue line on the surface',
polyline : {
positions : Cesium.Cartesian3.fromDegreesArray([-75, 37,
-125, 37]),
width : 10,
material : new Cesium.PolylineGlowMaterialProperty({
glowPower : 0.2,
color : Cesium.Color.BLUE
})
}
});
var orangeOutlined = viewer.entities.add({
name : 'Orange line with black outline at height and following the surface',
polyline : {
positions : Cesium.Cartesian3.fromDegreesArrayHeights([-75, 39, 250000,
-125, 39, 250000]),
width : 5,
material : new Cesium.PolylineOutlineMaterialProperty({
color : Cesium.Color.ORANGE,
outlineWidth : 2,
outlineColor : Cesium.Color.BLACK
})
}
});
var yellowLine = viewer.entities.add({
name : 'Purple straight line at height',
polyline : {
positions : Cesium.Cartesian3.fromDegreesArrayHeights([-75, 43, 500000,
-125, 43, 500000]),
width : 3,
followSurface : false,
material : Cesium.Color.PURPLE
}
});
viewer.zoomTo(viewer.entities);
//Sandcastle_End
Sandcastle.finishedLoading();
}
if (typeof Cesium !== "undefined") {
startup(Cesium);
} else if (typeof require === "function") {
require(["Cesium"], startup);
}
</script>
</body>
</html>
| {
"content_hash": "3d4dc901833bb7108673770f2c178766",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 124,
"avg_line_length": 33.53846153846154,
"alnum_prop": 0.5874836173001311,
"repo_name": "linkitapps/linkit-cesium-app",
"id": "3403d1ffddf435f1854d45fd1b14a36b0e35200b",
"size": "3052",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "app/Cesium/Apps/Sandcastle/gallery/Polyline.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "990969"
},
{
"name": "Erlang",
"bytes": "2146"
},
{
"name": "GLSL",
"bytes": "142361"
},
{
"name": "HTML",
"bytes": "995507"
},
{
"name": "JavaScript",
"bytes": "42360361"
},
{
"name": "Shell",
"bytes": "291"
}
],
"symlink_target": ""
} |
package net.jafama;
/**
* Copy-paste from FastMathTest, replacing FastMath with StrictFastMath
* and updating copySign tests.
*/
public class StrictFastMathTest extends AbstractFastMathTezt {
//--------------------------------------------------------------------------
// PUBLIC METHODS
//--------------------------------------------------------------------------
/*
* trigonometry
*/
public void test_sin_double() {
final double oneDegRad = StrictMath.toRadians(1.0);
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double ref = StrictMath.sin(value);
double res = StrictFastMath.sin(value);
double refValueNormalizedMPP = StrictMath.atan2(StrictMath.sin(value),StrictMath.cos(value));
boolean is_0_1 = Math.abs(refValueNormalizedMPP) < oneDegRad;
boolean is_179_180 = Math.abs(Math.abs(refValueNormalizedMPP) - Math.PI) < oneDegRad;
helper.process(
ref,
res,
TOL_SIN_COS_ABS,
((is_0_1 || is_179_180) ? TOL_SIN_COS_REL_BAD : TOL_SIN_COS_REL),
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_sinQuick_double() {
final double bound = Integer.MAX_VALUE * (2*Math.PI/(1<<11)) - 2.0;
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleUniform(-bound,bound);
double ref = StrictMath.sin(value);
double res = StrictFastMath.sinQuick(value);
helper.process(
ref,
res,
TOL_SINQUICK_COSQUICK_ABS,
Double.NaN,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_cos_double() {
final double oneDegRad = StrictMath.toRadians(1.0);
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double ref = StrictMath.cos(value);
double res = StrictFastMath.cos(value);
double refValueNormalizedMPP = StrictMath.atan2(StrictMath.sin(value),StrictMath.cos(value));
boolean is_89_91 = Math.abs(Math.abs(refValueNormalizedMPP) - Math.PI/2) < oneDegRad;
helper.process(
ref,
res,
TOL_SIN_COS_ABS,
(is_89_91 ? TOL_SIN_COS_REL_BAD : TOL_SIN_COS_REL),
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_cosQuick_double() {
final double bound = Integer.MAX_VALUE * (2*Math.PI/(1<<11));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleUniform(-bound,bound);
double ref = StrictMath.cos(value);
double res = StrictFastMath.cosQuick(value);
helper.process(
ref,
res,
TOL_SINQUICK_COSQUICK_ABS,
Double.NaN,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_sinAndCos_double_DoubleWrapper() {
final DoubleWrapper tmpCos = new DoubleWrapper();
final double oneDegRad = StrictMath.toRadians(1.0);
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double refSin = StrictMath.sin(value);
double refCos = StrictMath.cos(value);
double resSin = StrictFastMath.sinAndCos(value, tmpCos);
double resCos = tmpCos.value;
double refValueNormalizedMPP = StrictMath.atan2(StrictMath.sin(value),StrictMath.cos(value));
boolean is_0_1 = Math.abs(refValueNormalizedMPP) < oneDegRad;
boolean is_89_91 = Math.abs(Math.abs(refValueNormalizedMPP) - Math.PI/2) < oneDegRad;
boolean is_179_180 = Math.abs(Math.abs(refValueNormalizedMPP) - Math.PI) < oneDegRad;
sinHelper.process(
refSin,
resSin,
TOL_SIN_COS_ABS,
((is_0_1 || is_179_180) ? TOL_SIN_COS_REL_BAD : TOL_SIN_COS_REL),
value);
cosHelper.process(
refCos,
resCos,
TOL_SIN_COS_ABS,
(is_89_91 ? TOL_SIN_COS_REL_BAD : TOL_SIN_COS_REL),
value);
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
}
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_tan_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double ref = StrictMath.tan(value);
double res = StrictFastMath.tan(value);
final double relTol;
if (Math.abs(ref) < 1e-5) {
relTol = TOL_SIN_COS_REL_BAD;
} else if (Math.abs(ref) < 30.0) {
relTol = 4e-15;
} else if (Math.abs(ref) < 1e7) {
relTol = 1.5e-9;
} else {
relTol = 0.8;
}
boolean log = helper.process(
ref,
res,
Double.NaN,
relTol,
value);
if (log) {
System.out.println("atan(ref) = "+StrictMath.atan(ref));
System.out.println("atan(res) = "+StrictMath.atan(res));
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_asin_double() {
assertEquals(Math.PI/2, StrictFastMath.asin(1.0));
assertEquals(-Math.PI/2, StrictFastMath.asin(-1.0));
assertEquals(Double.NaN, StrictFastMath.asin(-1.1));
assertEquals(Double.NaN, StrictFastMath.asin(1.1));
assertEquals(Double.NaN, StrictFastMath.asin(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = this.randomDoubleWhatever(-1.0, 1.0);
double ref = StrictMath.asin(value);
double res = StrictFastMath.asin(value);
helper.process(
ref,
res,
Double.NaN,
((Math.abs(Math.abs(value)-0.5) < 0.4) ? TOL_1EM15 : 1e-13),
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_asinInRange_double() {
assertEquals(-Math.PI/2, StrictFastMath.asinInRange(-1.1));
assertEquals(Math.PI/2, StrictFastMath.asinInRange(1.1));
assertEquals(StrictFastMath.asin(-0.1), StrictFastMath.asinInRange(-0.1));
assertEquals(StrictFastMath.asin(0.1), StrictFastMath.asinInRange(0.1));
assertEquals(Double.NaN, StrictFastMath.asinInRange(Double.NaN));
}
public void test_acos_double() {
assertEquals(0.0, StrictFastMath.acos(1.0));
assertEquals(Math.PI, StrictFastMath.acos(-1.0));
assertEquals(Double.NaN, StrictFastMath.acos(-1.1));
assertEquals(Double.NaN, StrictFastMath.acos(1.1));
assertEquals(Double.NaN, StrictFastMath.acos(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = this.randomDoubleWhatever(-1.0, 1.0);
double ref = StrictMath.acos(value);
double res = StrictFastMath.acos(value);
helper.process(
ref,
res,
Double.NaN,
((Math.abs(value) < 0.85) ? TOL_1EM15 : 1e-8),
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_acosInRange_double() {
assertEquals(Math.PI, StrictFastMath.acosInRange(-1.1));
assertEquals(0.0, StrictFastMath.acosInRange(1.1));
assertEquals(StrictFastMath.acos(-0.1), StrictFastMath.acosInRange(-0.1));
assertEquals(StrictFastMath.acos(0.1), StrictFastMath.acosInRange(0.1));
assertEquals(Double.NaN, StrictFastMath.acosInRange(Double.NaN));
}
public void test_atan_double() {
assertEquals(Math.PI/4, StrictFastMath.atan(1.0));
assertEquals(-Math.PI/4, StrictFastMath.atan(-1.0));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.atan(value);
double res = StrictFastMath.atan(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM14,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_atan2_2double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double y = randomDoubleWhatever();
double x = randomDoubleWhatever();
double ref = StrictMath.atan2(y,x);
double res = StrictFastMath.atan2(y,x);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM14,
y,
x);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_toRadians_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.toRadians(value);
double res = StrictFastMath.toRadians(value);
if ((ref == 0.0) && (Math.abs(res) > 0.0)) {
// Might underflow before us, due to its
// computation being done in two steps.
assertTrue(value / 180.0 == 0.0);
--i;continue;
}
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_toDegrees_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.toDegrees(value);
double res = StrictFastMath.toDegrees(value);
if (Double.isInfinite(ref) && (!Double.isInfinite(res))) {
// Might overflow before us, due to its
// computation being done in two steps.
--i;continue;
}
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_toRadians_boolean_2int_double() {
final double before60 = StrictFastMath.nextDown(60.0);
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
boolean sign = this.random.nextBoolean();
int degrees = this.random.nextInt(181);
int minutes = this.random.nextInt(60);
double seconds = randomDoubleUniform(0.0, before60);
double ref = (sign ? 1 : -1) * StrictMath.toRadians(degrees + (1.0/60) * (minutes + (1.0/60) * seconds));
double res = StrictFastMath.toRadians(sign, degrees, minutes, seconds);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
sign,
degrees,
minutes,
seconds);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_toDegrees_boolean_2int_double() {
final double before60 = StrictFastMath.nextDown(60.0);
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
boolean sign = this.random.nextBoolean();
int degrees = this.random.nextInt(181);
int minutes = this.random.nextInt(60);
double seconds = randomDoubleUniform(0.0, before60);
double ref = (sign ? 1 : -1) * (degrees + (1.0/60) * (minutes + (1.0/60) * seconds));
double res = StrictFastMath.toDegrees(sign, degrees, minutes, seconds);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
sign,
degrees,
minutes,
seconds);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/**
* Supposes that toRadians(boolean,int,int,double) works.
*/
public void test_toDMS_double_IntWrapper_IntWrapper_DoubleWrapper() {
IntWrapper resDegrees = new IntWrapper();
IntWrapper resMinutes = new IntWrapper();
DoubleWrapper resSeconds = new DoubleWrapper();
final double before60 = StrictFastMath.nextDown(60.0);
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
boolean refSign = this.random.nextBoolean();
int refDegrees = this.random.nextInt(181);
int refMinutes = this.random.nextInt(60);
double refSeconds = randomDoubleUniform(0.0, before60);
double value = StrictFastMath.toRadians(refSign, refDegrees, refMinutes, refSeconds);
boolean resSign = StrictFastMath.toDMS(value, resDegrees, resMinutes, resSeconds);
double resRad = StrictFastMath.toRadians(resSign, resDegrees.value, resMinutes.value, resSeconds.value);
double refRad = refMod(value, resRad, 2*Math.PI);
boolean log = helper.process(
refRad,
resRad,
Double.NaN,
TOL_1EM15,
value);
if (log) {
System.out.println("refSign = "+refSign);
System.out.println("resSign = "+resSign);
System.out.println("refDegrees = "+refDegrees);
System.out.println("resDegrees = "+resDegrees);
System.out.println("refMinutes = "+refMinutes);
System.out.println("resMinutes = "+resMinutes);
System.out.println("refSeconds = "+refSeconds);
System.out.println("resSeconds = "+resSeconds);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_isInClockwiseDomain_3double() {
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, 0.0));
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, -Math.PI));
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, Math.PI));
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, 2*Math.PI));
assertTrue(StrictFastMath.isInClockwiseDomain(-Math.PI, 2*Math.PI, -Math.PI));
assertTrue(StrictFastMath.isInClockwiseDomain(-Math.PI, 2*Math.PI, 0.0));
assertTrue(StrictFastMath.isInClockwiseDomain(-Math.PI, 2*Math.PI, Math.PI));
// always in
for (int i=-10;i<10;i++) {
double startAngRad = StrictMath.toRadians(55.0*i);
double spanAngRad = Math.PI/2;
double angRad = startAngRad + Math.PI/3;
assertTrue(StrictFastMath.isInClockwiseDomain(startAngRad, spanAngRad, angRad));
}
// never in
for (int i=-10;i<10;i++) {
double startAngRad = StrictMath.toRadians(55.0*i);
double spanAngRad = Math.PI/3;
double angRad = startAngRad + Math.PI/2;
assertFalse(StrictFastMath.isInClockwiseDomain(startAngRad, spanAngRad, angRad));
}
// small angular values
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, -1e-10));
assertFalse(StrictFastMath.isInClockwiseDomain(0.0, 2*Math.PI, -1e-20));
assertTrue(StrictFastMath.isInClockwiseDomain(0.0, 2*StrictFastMath.PI_SUP, -1e-20));
assertTrue(StrictFastMath.isInClockwiseDomain(1e-10, 2*Math.PI, -1e-20));
assertFalse(StrictFastMath.isInClockwiseDomain(1e-20, 2*Math.PI, -1e-20));
assertTrue(StrictFastMath.isInClockwiseDomain(1e-20, 2*StrictFastMath.PI_SUP, -1e-20));
// NaN
assertFalse(StrictFastMath.isInClockwiseDomain(Double.NaN, Math.PI, Math.PI/2));
assertFalse(StrictFastMath.isInClockwiseDomain(Double.NaN, 3*Math.PI, Math.PI/2));
assertFalse(StrictFastMath.isInClockwiseDomain(0.0, Math.PI, Double.NaN));
assertFalse(StrictFastMath.isInClockwiseDomain(0.0, 3*Math.PI, Double.NaN));
assertFalse(StrictFastMath.isInClockwiseDomain(0.0, Double.NaN, Math.PI/2));
}
/*
* hyperbolic trigonometry
*/
public void test_sinh_double() {
assertEquals(Double.NEGATIVE_INFINITY, StrictFastMath.sinh(-711.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.sinh(711.0));
assertEquals(Double.NaN, StrictFastMath.sinh(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = random.nextBoolean() ? randomDoubleWhatever() : randomDoubleWhatever(-711,711);
value = knownBadValues_sinh_cosh_tanh(i, value);
double ref = StrictMath.sinh(value);
double res = StrictFastMath.sinh(value);
helper.process(
ref,
res,
Double.NaN,
TOL_SINH_COSH_REL,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_cosh_double() {
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.cosh(-711.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.cosh(711.0));
assertEquals(Double.NaN, StrictFastMath.cosh(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = random.nextBoolean() ? randomDoubleWhatever() : randomDoubleWhatever(-711,711);
value = knownBadValues_sinh_cosh_tanh(i, value);
double ref = StrictMath.cosh(value);
double res = StrictFastMath.cosh(value);
helper.process(
ref,
res,
Double.NaN,
TOL_SINH_COSH_REL,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_coshm1_double() {
assertEquals(-0.0,StrictFastMath.coshm1(-0.0));
assertEquals(0.0,StrictFastMath.coshm1(0.0));
assertEquals(Double.NaN,StrictFastMath.coshm1(Double.NaN));
for (double tiny : new double[]{StrictMath.pow(2, -28),StrictMath.sqrt(2*Double.MIN_VALUE)}) {
assertEquals(0.5 * tiny*tiny,StrictFastMath.coshm1(tiny));
}
/*
* Testing
* StrictMath.cosh(value) ~= coshm1(value) + 1
*/
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.cosh(value);
double res = StrictFastMath.coshm1(value) + 1;
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_sinhAndCosh_double_DoubleWrapper() {
final DoubleWrapper tmpCosh = new DoubleWrapper();
final MyDoubleResHelper sinhHelper = new MyDoubleResHelper("sinh");
final MyDoubleResHelper coshHelper = new MyDoubleResHelper("cosh");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = random.nextBoolean() ? randomDoubleWhatever() : randomDoubleWhatever(-711,711);
value = knownBadValues_sinh_cosh_tanh(i, value);
double refSinh = StrictMath.sinh(value);
double refCosh = StrictMath.cosh(value);
double resSinh = StrictFastMath.sinhAndCosh(value, tmpCosh);
double resCosh = tmpCosh.value;
sinhHelper.process(
refSinh,
resSinh,
Double.NaN,
TOL_SINH_COSH_REL,
value);
coshHelper.process(
refCosh,
resCosh,
Double.NaN,
TOL_SINH_COSH_REL,
value);
assertTrue(sinhHelper.lastOK());
assertTrue(coshHelper.lastOK());
}
sinhHelper.finalLogIfNeeded();
coshHelper.finalLogIfNeeded();
}
public void test_tanh_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
value = knownBadValues_sinh_cosh_tanh(i, value);
double ref = StrictMath.tanh(value);
double res = StrictFastMath.tanh(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_asinh_double() {
assertEquals(-0.0, StrictFastMath.asinh(-0.0));
assertEquals(0.0, StrictFastMath.asinh(0.0));
assertEquals(Double.NEGATIVE_INFINITY, StrictFastMath.asinh(Double.NEGATIVE_INFINITY));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.asinh(Double.POSITIVE_INFINITY));
assertEquals(Double.NaN, StrictFastMath.asinh(Double.NaN));
/*
* Testing asinh(StrictMath.sinh(value)) ~= value.
*/
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(-711.0, 711.0);
double sinhValue = StrictMath.sinh(value);
if (NumbersUtils.isNaNOrInfinite(sinhValue)) {
--i;continue;
}
double asinhSinhValue = StrictFastMath.asinh(sinhValue);
helper.process(
asinhSinhValue,
value,
Double.NaN,
TOL_1EM14,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_acosh_double() {
assertEquals(Double.NaN, StrictFastMath.acosh(Double.NaN));
assertEquals(Double.NaN, StrictFastMath.acosh(-10.0));
assertEquals(Double.NaN, StrictFastMath.acosh(0.0));
assertEquals(Double.NaN, StrictFastMath.acosh(0.9));
assertEquals(0.0, StrictFastMath.acosh(1.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.acosh(Double.POSITIVE_INFINITY));
/*
* Testing
* StrictMath.cosh(acosh(value)) ~= value
* or
* acosh(StrictMath.cosh(value)) ~= value
* (only considering best rel delta of both,
* to avoid bad delta only due to double precision loss,
* either for cosh(small values), or acosh(big values)).
*/
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
// Only using positive-x-half of cosh.
double value = randomDoubleWhatever(0.0, 711.0);
double coshValue = StrictMath.cosh(value);
if (NumbersUtils.isNaNOrInfinite(coshValue)) {
--i;continue;
}
double acoshCoshValue = StrictFastMath.acosh(coshValue);
double coshAcoshCoshValue = StrictMath.cosh(acoshCoshValue);
double relDelta1 = relDelta(value, acoshCoshValue);
double relDelta2 = relDelta(coshValue, coshAcoshCoshValue);
boolean use1 = (relDelta1 < relDelta2);
boolean log = helper.process(
(use1 ? value : coshValue),
(use1 ? acoshCoshValue : coshAcoshCoshValue),
Double.NaN,
TOL_1EM15,
value);
if (log) {
System.out.println("value = "+value);
System.out.println("coshValue = "+coshValue);
System.out.println("acoshCoshValue = "+acoshCoshValue);
System.out.println("coshAcoshCoshValue = "+coshAcoshCoshValue);
System.out.println("relDelta1 = "+relDelta1);
System.out.println("relDelta2 = "+relDelta2);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_acosh1p_double() {
assertEquals(Double.NaN,StrictFastMath.acosh1p(Double.NaN));
assertEquals(0.0,StrictFastMath.acosh1p(0.0));
assertEquals(-0.0,StrictFastMath.acosh1p(-0.0));
/*
* Testing
* acosh1p(StrictMath.cosh(value)-1) ~= value
* (only considering best rel delta of both,
* to avoid bad delta only due to double precision loss,
* for cosh(small values)).
*/
{
final MyDoubleResHelper helper = new MyDoubleResHelper("cosh as ref");
for (int i=0;i<NBR_OF_VALUES;i++) {
// Only using positive-x-half of cosh.
double value = randomDoubleWhatever(0.0, 711.0);
double coshValueM1 = StrictMath.cosh(value) - 1;
if (NumbersUtils.isNaNOrInfinite(coshValueM1)) {
--i;continue;
}
double acosh1pCoshValueM1 = StrictFastMath.acosh1p(coshValueM1); // acosh(1+cosh(value)-1) = value
double coshAcosh1pCoshValueM1M1 = StrictMath.cosh(acosh1pCoshValueM1)-1; // cosh(acosh(1+cosh(value)-1))-1 = cosh(value)-1
double relDelta1 = relDelta(value, acosh1pCoshValueM1);
double relDelta2 = relDelta(coshValueM1, coshAcosh1pCoshValueM1M1);
boolean use1 = (relDelta1 < relDelta2);
boolean log = helper.process(
(use1 ? value : coshValueM1),
(use1 ? acosh1pCoshValueM1 : coshAcosh1pCoshValueM1M1),
Double.NaN,
TOL_1EM14,
value);
if (log) {
System.out.println("value = "+value);
System.out.println("coshValueM1 = "+coshValueM1);
System.out.println("acosh1pCoshValueM1 = "+acosh1pCoshValueM1);
System.out.println("coshAcosh1pCoshValueM1M1 = "+coshAcosh1pCoshValueM1M1);
System.out.println("relDelta1 = "+relDelta1);
System.out.println("relDelta2 = "+relDelta2);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/*
* Testing against coshm1, for tiny values.
* (only considering best rel delta of both,
* to avoid bad delta only due to double precision loss).
*/
{
final MyDoubleResHelper helper = new MyDoubleResHelper("coshm1 as ref");
for (int i=0;i<NBR_OF_VALUES;i++) {
// Only using positive-x-half of cosh.
double value = randomDoubleWhatever(0.0, Double.MAX_VALUE);
double coshm1Value = StrictFastMath.coshm1(value); // cosh(value)-1
if ((coshm1Value == 0.0) || Double.isInfinite(coshm1Value)) {
// Underflow or overflow.
--i;continue;
}
double acosh1pCoshm1Value = StrictFastMath.acosh1p(coshm1Value); // acosh(1+cosh(value)-1) = value
double coshm1Acosh1pCoshm1Value = StrictFastMath.coshm1(acosh1pCoshm1Value); // cosh(acosh(1+cosh(value)-1))-1 = cosh(value)-1
double relDelta1 = relDelta(value, acosh1pCoshm1Value);
double relDelta2 = relDelta(coshm1Value, coshm1Acosh1pCoshm1Value);
boolean use1 = (relDelta1 < relDelta2);
boolean log = helper.process(
(use1 ? value : coshm1Value),
(use1 ? acosh1pCoshm1Value : coshm1Acosh1pCoshm1Value),
Double.NaN,
1e-7,
value);
if (log) {
System.out.println("value = "+value);
System.out.println("coshm1Value = "+coshm1Value);
System.out.println("acosh1pCoshm1Value = "+acosh1pCoshm1Value);
System.out.println("coshm1Acosh1pCoshm1Value = "+coshm1Acosh1pCoshm1Value);
System.out.println("relDelta1 = "+relDelta1);
System.out.println("relDelta2 = "+relDelta2);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
}
public void test_atanh_double() {
assertEquals(Double.NaN, StrictFastMath.atanh(Double.NaN));
assertEquals(Double.NaN, StrictFastMath.atanh(-1.1));
assertEquals(Double.NEGATIVE_INFINITY, StrictFastMath.atanh(-1.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.atanh(1.0));
assertEquals(Double.NaN, StrictFastMath.atanh(1.1));
/*
* Testing
* StrictMath.tanh(atanh(value)) ~= value
* or
* atanh(StrictMath.tanh(value)) ~= value
* (only considering best rel delta of both,
* to avoid bad delta only due to double precision loss,
* either for tanh(big values), or atanh(values near +-1)).
*/
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(-711.0, 711.0);
double tanhValue = StrictMath.tanh(value);
if (!(Math.abs(tanhValue) < 1.0)) {
// NaN or limit.
--i;continue;
}
double atanhTanhValue = StrictFastMath.atanh(tanhValue);
double tanhAtanhTanhValue = StrictMath.tanh(atanhTanhValue);
double relDelta1 = relDelta(value, atanhTanhValue);
double relDelta2 = relDelta(tanhValue, tanhAtanhTanhValue);
boolean use1 = (relDelta1 < relDelta2);
boolean log = helper.process(
(use1 ? value : tanhValue),
(use1 ? atanhTanhValue : tanhAtanhTanhValue),
Double.NaN,
TOL_1EM14,
value);
if (log) {
System.out.println("value = "+value);
System.out.println("tanhValue = "+tanhValue);
System.out.println("atanhTanhValue = "+atanhTanhValue);
System.out.println("tanhAtanhTanhValue = "+tanhAtanhTanhValue);
System.out.println("relDelta1 = "+relDelta1);
System.out.println("relDelta2 = "+relDelta2);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/*
* exponentials
*/
public void test_exp_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = this.random.nextBoolean() ? randomDoubleWhatever() : randomDoubleWhatever(-746.0, 710.0);
double ref = StrictMath.exp(value);
double res = StrictFastMath.exp(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_expQuick_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(-700.0, 700.0);
value = knownBadValues_expQuick_double(i, value);
double ref = StrictMath.exp(value);
double res = StrictFastMath.expQuick(value);
helper.process(
ref,
res,
Double.NaN,
2.94e-2,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_expm1_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = this.random.nextBoolean() ? randomDoubleWhatever() : randomDoubleWhatever(-746.0, 710.0);
double ref = StrictMath.expm1(value);
double res = StrictFastMath.expm1(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/*
* logarithms
*/
public void test_log_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
value = knownBadValues_logQuick_double(i, value);
double ref = StrictMath.log(value);
double res = StrictFastMath.log(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM14,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_logQuick_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(DOUBLE_MIN_NORMAL, Double.MAX_VALUE);
double ref = StrictMath.log(value);
double res = StrictFastMath.logQuick(value);
helper.process(
ref,
res,
Double.NaN,
1.9e-3,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_log10_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.log10(value);
double res = StrictFastMath.log10(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM14,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_log1p_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.log1p(value);
double res = StrictFastMath.log1p(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM14,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_log2_int() {
for (int value : new int[]{Integer.MIN_VALUE,0}) {
try {
StrictFastMath.log2(value);
assertTrue(false);
} catch (IllegalArgumentException e) {
// ok
}
}
for (int p=0;p<=30;p++) {
int pot = (1<<p);
if (p != 0) {
assertEquals(p-1, StrictFastMath.log2(pot-1));
}
assertEquals(p, StrictFastMath.log2(pot));
assertEquals(p, StrictFastMath.log2(pot+pot-1));
if (p != 30) {
assertEquals(p+1, StrictFastMath.log2(pot+pot));
}
}
}
public void test_log2_long() {
for (long value : new long[]{Long.MIN_VALUE,0}) {
try {
StrictFastMath.log2(value);
assertTrue(false);
} catch (IllegalArgumentException e) {
// ok
}
}
for (int p=0;p<=62;p++) {
long pot = (1L<<p);
if (p != 0) {
assertEquals(p-1, StrictFastMath.log2(pot-1));
}
assertEquals(p, StrictFastMath.log2(pot));
assertEquals(p, StrictFastMath.log2(pot+pot-1));
if (p != 62) {
assertEquals(p+1, StrictFastMath.log2(pot+pot));
}
}
}
/*
* powers
*/
public void test_pow_2double() {
assertEquals(1.0, StrictFastMath.pow(0.0,0.0));
assertEquals(0.0, StrictFastMath.pow(0.0,2.0));
assertEquals(0.0, StrictFastMath.pow(-0.0,2.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.pow(0.0,-2.0));
assertEquals(0.0, StrictFastMath.pow(0.0,3.0));
assertEquals(-0.0, StrictFastMath.pow(-0.0,3.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.pow(0.0,-3.0));
assertEquals(4.0, StrictFastMath.pow(2.0,2.0), TOL_1EM15);
assertEquals(8.0, StrictFastMath.pow(2.0,3.0), TOL_1EM15);
assertEquals(1.0/4.0, StrictFastMath.pow(2.0,-2.0), TOL_1EM15);
assertEquals(1.0/8.0, StrictFastMath.pow(2.0,-3.0), TOL_1EM15);
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.pow(Double.NEGATIVE_INFINITY,2.0));
assertEquals(Double.NEGATIVE_INFINITY, StrictFastMath.pow(Double.NEGATIVE_INFINITY,3.0));
assertEquals(0.0, StrictFastMath.pow(Double.NEGATIVE_INFINITY,-2.0));
assertEquals(-0.0, StrictFastMath.pow(Double.NEGATIVE_INFINITY,-3.0));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.pow(-2.0,(1L<<40))); // even power
assertEquals(Double.NEGATIVE_INFINITY, StrictFastMath.pow(-2.0,(1L<<40)+1)); // odd power
assertEquals(Double.NaN, StrictFastMath.pow(Double.NaN,1.0));
assertEquals(Double.NaN, StrictFastMath.pow(1.0,Double.NaN));
assertEquals(Double.NaN, StrictFastMath.pow(Double.NaN,-1.0));
assertEquals(Double.NaN, StrictFastMath.pow(-1.0,Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
a = knownBadValues_pow_2double_a(i, a);
b = knownBadValues_pow_2double_b(i, b);
double ref = StrictMath.pow(a,b);
double res = StrictFastMath.pow(a,b);
helper.process(
ref,
res,
Double.NaN,
3e-12,
a,
b);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_powQuick_2double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double a = randomDoubleWhatever(DOUBLE_MIN_NORMAL, Double.MAX_VALUE);
double b = randomDoubleWhatever(-Double.MAX_VALUE, Double.MAX_VALUE);
a = knownBadValues_powQuick_2double_a(i, a);
b = knownBadValues_powQuick_2double_b(i, b);
double ref = StrictMath.pow(a, b);
double res = StrictFastMath.powQuick(a,b);
double absRef = Math.abs(ref);
final double relTol;
if ((absRef > 1e-10) && (absRef < 1e10)) {
relTol = 1e-2;
} else if ((absRef > 1e-40) && (absRef < 1e40)) {
relTol = 6e-2;
} else {
--i;continue;
}
helper.process(
ref,
res,
Double.NaN,
relTol,
a,
b);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_powFast_double_int() {
assertEquals(1.0, StrictFastMath.powFast(1.0,Integer.MIN_VALUE));
assertEquals(Double.POSITIVE_INFINITY, StrictFastMath.powFast(Double.MIN_VALUE,Integer.MIN_VALUE));
assertEquals(Double.NaN, StrictFastMath.powFast(Double.NaN,1));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double a = randomDoubleWhatever(-10.0,10.0);
int b = randomIntUniform(-10,10);
double ref = StrictMath.pow(a,b);
double res = StrictFastMath.powFast(a,b);
helper.process(
ref,
res,
Double.NaN,
2e-15,
a,
b);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_twoPow_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int value = randomIntWhatever();
double ref = StrictMath.pow(2,value);
double res = StrictFastMath.twoPow(value);
assertEquals(ref, res);
}
}
public void test_pow2_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int value = randomIntWhatever();
int ref = value*value;
int res = StrictFastMath.pow2(value);
assertEquals(ref, res);
}
}
public void test_pow2_long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long value = randomLongWhatever();
long ref = value*value;
long res = StrictFastMath.pow2(value);
assertEquals(ref, res);
}
}
public void test_pow2_float() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = value*value;
float res = StrictFastMath.pow2(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_pow2_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = value*value;
double res = StrictFastMath.pow2(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_pow3_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int value = randomIntWhatever();
int ref = value*value*value;
int res = StrictFastMath.pow3(value);
assertEquals(ref, res);
}
}
public void test_pow3_long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long value = randomLongWhatever();
long ref = value*value*value;
long res = StrictFastMath.pow3(value);
assertEquals(ref, res);
}
}
public void test_pow3_float() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = value*value*value;
float res = StrictFastMath.pow3(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_pow3_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = value*value*value;
double res = StrictFastMath.pow3(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/*
* roots
*/
public void test_sqrt_double() {
assertEquals(-0.0, StrictFastMath.sqrt(-0.0));
assertEquals(0.0, StrictFastMath.sqrt(0.0));
assertEquals(Double.NaN, StrictFastMath.sqrt(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.sqrt(value);
double res = StrictFastMath.sqrt(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_sqrtQuick_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(DOUBLE_MIN_NORMAL, Double.MAX_VALUE);
value = knownBadValues_sqrtQuick_double(i, value);
double ref = StrictMath.sqrt(value);
double res = StrictFastMath.sqrtQuick(value);
helper.process(
ref,
res,
Double.NaN,
3.41e-2,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_invSqrtQuick_double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever(DOUBLE_MIN_NORMAL, Double.MAX_VALUE);
value = knownBadValues_invSqrtQuick_double(i, value);
double ref = 1/StrictMath.sqrt(value);
double res = StrictFastMath.invSqrtQuick(value);
helper.process(
ref,
res,
Double.NaN,
3.44e-2,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_cbrt_double() {
assertEquals(-0.0, StrictFastMath.cbrt(-0.0));
assertEquals(0.0, StrictFastMath.cbrt(0.0));
assertEquals(Double.NaN, StrictFastMath.cbrt(Double.NaN));
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhatever();
double ref = StrictMath.cbrt(value);
double res = StrictFastMath.cbrt(value);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
value);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_hypot_2double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double x = randomDoubleWhatever();
double y = this.random.nextBoolean() ? x * randomDoubleUniform(1e-16, 1e16) : randomDoubleWhatever();
double ref = StrictMath.hypot(x,y);
double res = StrictFastMath.hypot(x,y);
helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
x,
y);
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
public void test_hypot_3double() {
final MyDoubleResHelper helper = new MyDoubleResHelper();
for (int i=0;i<NBR_OF_VALUES;i++) {
double x = randomDoubleWhatever();
double y = this.random.nextBoolean() ? x * randomDoubleUniform(1e-16, 1e16) : randomDoubleWhatever();
double z = this.random.nextBoolean() ? y * randomDoubleUniform(1e-16, 1e16) : randomDoubleWhatever();
double xy = StrictMath.hypot(x,y);
double xz = StrictMath.hypot(x,z);
double yz = StrictMath.hypot(y,z);
double xyz = StrictMath.hypot(xy,z);
double xzy = StrictMath.hypot(xz,y);
double yzx = StrictMath.hypot(yz,x);
// max(+Infinity,NaN) = NaN
double ref = Math.max(xyz, Math.max(xzy, yzx));
double res = StrictFastMath.hypot(x,y,z);
boolean log = helper.process(
ref,
res,
Double.NaN,
TOL_1EM15,
x,
y,
z);
if (log) {
System.out.println("xy = "+xy);
System.out.println("xz = "+xz);
System.out.println("yz = "+yz);
System.out.println("xyz = "+xyz);
System.out.println("xzy = "+xzy);
System.out.println("yzx = "+yzx);
}
assertTrue(helper.lastOK());
}
helper.finalLogIfNeeded();
}
/*
* absolute values
*/
public void test_abs_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int value = randomIntWhatever();
int ref = Math.abs(value);
int res = StrictFastMath.abs(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_abs_long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long value = randomLongWhatever();
long ref = Math.abs(value);
long res = StrictFastMath.abs(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
/*
* close values
*/
public void test_toIntExact_long() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MAX_VALUE, StrictFastMath.toIntExact((long)Integer.MAX_VALUE));
try {
StrictFastMath.toIntExact(((long)Integer.MAX_VALUE)+1L);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_toInt_long() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MAX_VALUE, StrictFastMath.toInt((long)Integer.MAX_VALUE));
assertEquals(Integer.MAX_VALUE, StrictFastMath.toInt(Long.MAX_VALUE));
}
public void test_floor_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = (float)Math.floor(value);
float res = StrictFastMath.floor(value);
assertEquals(ref, res);
}
}
public void test_floor_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.floor(value);
double res = StrictFastMath.floor(value);
assertEquals(ref, res);
}
}
public void test_ceil_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = (float)Math.ceil(value);
float res = StrictFastMath.ceil(value);
assertEquals(ref, res);
}
}
public void test_ceil_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.ceil(value);
double res = StrictFastMath.ceil(value);
assertEquals(ref, res);
}
}
public void test_round_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
int ref;
if (NumbersUtils.isMathematicalInteger(value) || NumbersUtils.isNaNOrInfinite(value)) {
ref = (int)value; // exact, or closest int, or 0 if NaN
} else {
boolean neg = (value < 0);
int lowerMag = (int)value;
float postCommaPart = value - lowerMag;
if (neg) {
ref = (postCommaPart < -0.5f) ? lowerMag-1 : lowerMag;
} else {
ref = (postCommaPart < 0.5f) ? lowerMag : lowerMag+1;
}
}
int res = StrictFastMath.round(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_round_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
long ref;
if (NumbersUtils.isMathematicalInteger(value) || NumbersUtils.isNaNOrInfinite(value)) {
ref = (long)value; // exact, or closest int, or 0 if NaN
} else {
boolean neg = (value < 0);
long lowerMag = (long)value;
double postCommaPart = value - lowerMag;
if (neg) {
ref = (postCommaPart < -0.5) ? lowerMag-1 : lowerMag;
} else {
ref = (postCommaPart < 0.5) ? lowerMag : lowerMag+1;
}
}
long res = StrictFastMath.round(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_roundEven_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
int ref;
if (NumbersUtils.isMathematicalInteger(value) || NumbersUtils.isNaNOrInfinite(value)) {
ref = (int)value; // exact, or closest int, or 0 if NaN
} else {
boolean neg = (value < 0);
int lowerMag = (int)value;
if (NumbersUtils.isEquidistant(value)) {
ref = (((lowerMag&1) == 0) ? lowerMag : lowerMag + (neg ? -1 : 1));
} else {
float postCommaPart = value - lowerMag;
if (neg) {
ref = (postCommaPart < -0.5f) ? lowerMag-1 : lowerMag;
} else {
ref = (postCommaPart < 0.5f) ? lowerMag : lowerMag+1;
}
}
}
int res = StrictFastMath.roundEven(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_roundEven_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
long ref;
if (NumbersUtils.isMathematicalInteger(value) || NumbersUtils.isNaNOrInfinite(value)) {
ref = (long)value; // exact, or closest int, or 0 if NaN
} else {
boolean neg = (value < 0);
long lowerMag = (long)value;
if (NumbersUtils.isEquidistant(value)) {
ref = (((lowerMag&1) == 0) ? lowerMag : lowerMag + (neg ? -1 : 1));
} else {
double postCommaPart = value - lowerMag;
if (neg) {
ref = (postCommaPart < -0.5) ? lowerMag-1 : lowerMag;
} else {
ref = (postCommaPart < 0.5) ? lowerMag : lowerMag+1;
}
}
}
long res = StrictFastMath.roundEven(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_rint_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = (float)Math.rint((double)value);
float res = StrictFastMath.rint(value);
boolean ok = equivalent(ref,res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_rint_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.rint(value);
double res = StrictFastMath.rint(value);
boolean ok = equivalent(ref,res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
/*
* ranges
*/
public void test_toRange_3int() {
assertEquals(0, StrictFastMath.toRange(0, 2, -1));
assertEquals(0, StrictFastMath.toRange(0, 2, 0));
assertEquals(1, StrictFastMath.toRange(0, 2, 1));
assertEquals(2, StrictFastMath.toRange(0, 2, 2));
assertEquals(2, StrictFastMath.toRange(0, 2, 3));
}
public void test_toRange_3long() {
assertEquals(0L, StrictFastMath.toRange(0L, 2L, -1L));
assertEquals(0L, StrictFastMath.toRange(0L, 2L, 0L));
assertEquals(1L, StrictFastMath.toRange(0L, 2L, 1L));
assertEquals(2L, StrictFastMath.toRange(0L, 2L, 2L));
assertEquals(2L, StrictFastMath.toRange(0L, 2L, 3L));
}
public void test_toRange_3float() {
assertEquals(0.0f, StrictFastMath.toRange(0.0f, 2.0f, -1.0f));
assertEquals(0.0f, StrictFastMath.toRange(0.0f, 2.0f, 0.0f));
assertEquals(1.0f, StrictFastMath.toRange(0.0f, 2.0f, 1.0f));
assertEquals(2.0f, StrictFastMath.toRange(0.0f, 2.0f, 2.0f));
assertEquals(2.0f, StrictFastMath.toRange(0.0f, 2.0f, 3.0f));
}
public void test_toRange_3double() {
assertEquals(0.0, StrictFastMath.toRange(0.0, 2.0, -1.0));
assertEquals(0.0, StrictFastMath.toRange(0.0, 2.0, 0.0));
assertEquals(1.0, StrictFastMath.toRange(0.0, 2.0, 1.0));
assertEquals(2.0, StrictFastMath.toRange(0.0, 2.0, 2.0));
assertEquals(2.0, StrictFastMath.toRange(0.0, 2.0, 3.0));
}
/*
* binary operators (+,-,*)
*/
public void test_addExact_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MAX_VALUE, StrictFastMath.addExact(Integer.MAX_VALUE-1, 1));
try {
StrictFastMath.addExact(Integer.MAX_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_addExact_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MAX_VALUE, StrictFastMath.addExact(Long.MAX_VALUE-1L, 1L));
try {
StrictFastMath.addExact(Long.MAX_VALUE, 1L);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_addBounded_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MAX_VALUE, StrictFastMath.addBounded(Integer.MAX_VALUE-1, 1));
assertEquals(Integer.MAX_VALUE, StrictFastMath.addBounded(Integer.MAX_VALUE, 1));
}
public void test_addBounded_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MAX_VALUE, StrictFastMath.addBounded(Long.MAX_VALUE-1L, 1L));
assertEquals(Long.MAX_VALUE, StrictFastMath.addBounded(Long.MAX_VALUE, 1L));
}
public void test_subtractExact_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MIN_VALUE, StrictFastMath.subtractExact(Integer.MIN_VALUE+1, 1));
try {
StrictFastMath.subtractExact(Integer.MIN_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_subtractExact_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MIN_VALUE, StrictFastMath.subtractExact(Long.MIN_VALUE+1L, 1L));
try {
StrictFastMath.subtractExact(Long.MIN_VALUE, 1L);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_subtractBounded_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MIN_VALUE, StrictFastMath.subtractBounded(Integer.MIN_VALUE+1, 1));
assertEquals(Integer.MIN_VALUE, StrictFastMath.subtractBounded(Integer.MIN_VALUE, 1));
}
public void test_subtractBounded_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MIN_VALUE, StrictFastMath.subtractBounded(Long.MIN_VALUE+1L, 1L));
assertEquals(Long.MIN_VALUE, StrictFastMath.subtractBounded(Long.MIN_VALUE, 1L));
}
public void test_multiplyExact_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MIN_VALUE, StrictFastMath.multiplyExact(Integer.MIN_VALUE/2, 2));
try {
StrictFastMath.multiplyExact(Integer.MIN_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_multiplyExact_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MIN_VALUE, StrictFastMath.multiplyExact(Long.MIN_VALUE/2L, 2L));
try {
StrictFastMath.multiplyExact(Long.MIN_VALUE, 2L);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
}
public void test_multiplyBounded_2int() {
/*
* quick test (delegates)
*/
assertEquals(Integer.MIN_VALUE, StrictFastMath.multiplyBounded(Integer.MIN_VALUE/2, 2));
assertEquals(Integer.MIN_VALUE, StrictFastMath.multiplyBounded(Integer.MIN_VALUE, 2));
}
public void test_multiplyBounded_2long() {
/*
* quick test (delegates)
*/
assertEquals(Long.MIN_VALUE, StrictFastMath.multiplyBounded(Long.MIN_VALUE/2L, 2L));
assertEquals(Long.MIN_VALUE, StrictFastMath.multiplyBounded(Long.MIN_VALUE, 2L));
}
/*
* binary operators (/,%)
*/
public void test_floorDiv_2int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
final int x = randomIntWhatever();
int y = randomIntWhatever();
if (y == 0) {
try {
StrictFastMath.floorDiv(x,y);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
} else {
final int expected;
final boolean exact = ((x/y)*y == x);
if (exact || ((x^y) >= 0)) {
// exact or same sign
expected = x/y;
} else {
// different signs and not exact
expected = x/y - 1;
}
final int actual = StrictFastMath.floorDiv(x,y);
assertEquals(expected, actual);
}
}
}
public void test_floorDiv_2long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
final long x = randomLongWhatever();
long y = randomLongWhatever();
if (y == 0) {
try {
StrictFastMath.floorDiv(x,y);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
} else {
final long expected;
final boolean exact = ((x/y)*y == x);
if (exact || ((x^y) >= 0)) {
// exact or same sign
expected = x/y;
} else {
// different signs and not exact
expected = x/y - 1;
}
final long actual = StrictFastMath.floorDiv(x,y);
assertEquals(expected, actual);
}
}
}
public void test_floorMod_2int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
final int x = randomIntWhatever();
int y = randomIntWhatever();
if (y == 0) {
try {
StrictFastMath.floorMod(x,y);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
} else {
final int expected;
final boolean exact = ((x/y)*y == x);
if (exact || ((x^y) >= 0)) {
// exact or same sign
expected = x%y;
} else {
// different signs and not exact
expected = x%y + y;
}
final int actual = StrictFastMath.floorMod(x,y);
assertEquals(expected, actual);
// identity
assertEquals(x - StrictFastMath.floorDiv(x, y) * y, StrictFastMath.floorMod(x,y));
}
}
}
public void test_floorMod_2long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long x = randomIntWhatever();
long y = randomIntWhatever();
if (y == 0) {
try {
StrictFastMath.floorMod(x,y);
assertTrue(false);
} catch (ArithmeticException e) {
// ok
}
} else {
long expected;
boolean exact = ((x/y)*y == x);
if (exact || ((x^y) >= 0)) {
// exact or same sign
expected = x%y;
} else {
// different signs and not exact
expected = x%y + y;
}
long actual = StrictFastMath.floorMod(x,y);
assertEquals(expected, actual);
// identity
assertEquals(x - StrictFastMath.floorDiv(x, y) * y, StrictFastMath.floorMod(x,y));
}
}
}
public void test_remainder_2double() {
/* Can have that kind of failure with Java 5 or 6,
* but it's just a "%" bug (bug_id=8015396).
test_remainder_2double()
a = -1.7976931348623157E308
b = -5.9728871583771424E-300
ref = -4.55688172866467E-305
res = NaN
IEEE = -4.55688172866467E-305
*/
for (int i=0;i<NBR_OF_VALUES;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = getExpectedResult_remainder_2double(a,b);
double res = StrictFastMath.remainder(a,b);
boolean ok = equivalent(ref,res);
if (!ok) {
printCallerName();
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
System.out.println("IEEE = "+Math.IEEEremainder(a,b));
}
assertTrue(ok);
}
}
public void test_normalizeMinusPiPi_double() {
final MyDoubleResHelper normHelper = new MyDoubleResHelper("norm");
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double res = StrictFastMath.normalizeMinusPiPi(value);
if (NumbersUtils.isInRange(-Math.PI, Math.PI, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double refCos = StrictMath.cos(value);
double ref = StrictMath.atan2(refSin, refCos);
double resSin = StrictMath.sin(res);
double resCos = StrictMath.cos(res);
double relTolSin;
double relTolCos;
if (Math.abs(res) <= Math.PI/4) {
relTolSin = TOL_TRIG_NORM_REL;
relTolCos = TOL_1EM15;
} else {
// Relative delta might be bad due to large ULPs.
relTolSin = Double.POSITIVE_INFINITY;
relTolCos = Double.POSITIVE_INFINITY;
}
boolean logNorm = normHelper.process(
ref,
res,
TOL_1EM15,
TOL_TRIG_NORM_REL,
value);
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_1EM15,
relTolSin,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_1EM15,
relTolCos,
value);
if (logNorm || logSin || logCos) {
System.out.println("ref = "+StrictMath.toDegrees(ref)+" deg");
System.out.println("res = "+StrictMath.toDegrees(res)+" deg");
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(normHelper.lastOK());
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(-Math.PI, Math.PI, res));
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
normHelper.finalLogIfNeeded();
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_normalizeMinusPiPiFast_double() {
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
if (Math.abs(value) > MAX_VALUE_FAST_TRIG_NORM) {
value = randomDoubleUniform(-MAX_VALUE_FAST_TRIG_NORM,MAX_VALUE_FAST_TRIG_NORM);
}
double res = StrictFastMath.normalizeMinusPiPiFast(value);
if (NumbersUtils.isInRange(-Math.PI, Math.PI, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double resSin = StrictMath.sin(res);
double refCos = StrictMath.cos(value);
double resCos = StrictMath.cos(res);
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
if (logSin || logCos) {
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(-Math.PI, Math.PI, res));
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_normalizeZeroTwoPi_double() {
final MyDoubleResHelper normHelper = new MyDoubleResHelper("norm");
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double res = StrictFastMath.normalizeZeroTwoPi(value);
if (NumbersUtils.isInRange(0.0, 2*Math.PI, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double refCos = StrictMath.cos(value);
double ref = StrictMath.atan2(refSin, refCos);
if (ref < 0.0) {
ref = NumbersUtils.plus2PI_strict(ref);
}
double resSin = StrictMath.sin(res);
double resCos = StrictMath.cos(res);
double relTolSin;
double relTolCos;
if (Math.abs(res) <= Math.PI/4) {
relTolSin = TOL_TRIG_NORM_REL;
relTolCos = TOL_1EM15;
} else {
// Relative delta might be bad due to large ULPs.
relTolSin = Double.POSITIVE_INFINITY;
relTolCos = Double.POSITIVE_INFINITY;
}
boolean logNorm = normHelper.process(
ref,
res,
TOL_1EM15,
TOL_TRIG_NORM_REL,
value);
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_1EM15,
relTolSin,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_1EM15,
relTolCos,
value);
if (logNorm || logSin || logCos) {
System.out.println("ref = "+StrictMath.toDegrees(ref)+" deg");
System.out.println("res = "+StrictMath.toDegrees(res)+" deg");
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(normHelper.lastOK());
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(0.0, 2*Math.PI, res));
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
normHelper.finalLogIfNeeded();
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_normalizeZeroTwoPiFast_double() {
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
if (Math.abs(value) > MAX_VALUE_FAST_TRIG_NORM) {
value = randomDoubleUniform(-MAX_VALUE_FAST_TRIG_NORM,MAX_VALUE_FAST_TRIG_NORM);
}
double res = StrictFastMath.normalizeZeroTwoPiFast(value);
if (NumbersUtils.isInRange(0.0, 2*Math.PI, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double resSin = StrictMath.sin(res);
double refCos = StrictMath.cos(value);
double resCos = StrictMath.cos(res);
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
if (logSin || logCos) {
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(0.0, 2*Math.PI, res));
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_normalizeMinusHalfPiHalfPi_double() {
final MyDoubleResHelper normHelper = new MyDoubleResHelper("norm");
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
value = knownBadValues_trigNorm(i, value);
double res = StrictFastMath.normalizeMinusHalfPiHalfPi(value);
if (NumbersUtils.isInRange(-Math.PI/2, Math.PI/2, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double refCos = StrictMath.cos(value);
if (refCos < 0.0) {
refSin = -refSin;
refCos = -refCos;
}
double ref = StrictMath.atan2(refSin, refCos);
double resSin = StrictMath.sin(res);
double resCos = StrictMath.cos(res);
double relTolSin;
double relTolCos;
if (Math.abs(res) <= Math.PI/4) {
relTolSin = TOL_TRIG_NORM_REL;
relTolCos = TOL_1EM15;
} else {
// Sin close to 1, so accurate.
relTolSin = TOL_1EM15;
// Relative delta might be bad due to large ULPs.
relTolCos = Double.POSITIVE_INFINITY;
}
boolean logNorm = normHelper.process(
ref,
res,
TOL_1EM15,
TOL_TRIG_NORM_REL,
value);
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_1EM15,
relTolSin,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_1EM15,
relTolCos,
value);
if (logNorm || logSin || logCos) {
System.out.println("ref = "+StrictMath.toDegrees(ref)+" deg");
System.out.println("res = "+StrictMath.toDegrees(res)+" deg");
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(normHelper.lastOK());
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(-Math.PI/2, Math.PI/2, res));
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
normHelper.finalLogIfNeeded();
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
public void test_normalizeMinusHalfPiHalfPiFast_double() {
final MyDoubleResHelper sinHelper = new MyDoubleResHelper("sin");
final MyDoubleResHelper cosHelper = new MyDoubleResHelper("cos");
for (int i=0;i<NBR_OF_VALUES;i++) {
double value = randomDoubleWhateverOrPiIsh();
if (Math.abs(value) > MAX_VALUE_FAST_TRIG_NORM) {
value = randomDoubleUniform(-MAX_VALUE_FAST_TRIG_NORM,MAX_VALUE_FAST_TRIG_NORM);
}
double res = StrictFastMath.normalizeMinusHalfPiHalfPiFast(value);
if (NumbersUtils.isInRange(-Math.PI/2, Math.PI/2, value)) {
// Unchanged if already in range.
assertEquals(value, res);
continue;
}
double refSin = StrictMath.sin(value);
double refCos = StrictMath.cos(value);
if (refCos < 0.0) {
refSin = -refSin;
refCos = -refCos;
}
double resSin = StrictMath.sin(res);
double resCos = StrictMath.cos(res);
// Normalization of value done in sin or cos
// can end up in the left side of the trigonometric circle,
// and we normalize into its right side,
// so cos signs can be different, but their
// absolute values should be close.
boolean sinSignDiff = Math.signum(refSin) != Math.signum(resSin);
boolean cosSignDiff = Math.signum(refCos) != Math.signum(resCos);
if (sinSignDiff) {
refSin = -refSin;
}
if (cosSignDiff) {
refCos = -refCos;
}
boolean logSin = sinHelper.process(
refSin,
resSin,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
boolean logCos = cosHelper.process(
refCos,
resCos,
TOL_FAST_TRIG_NORM_ABS,
Double.NaN,
value);
if (logSin || logCos) {
System.out.println("refSin = "+refSin);
System.out.println("resSin = "+resSin);
System.out.println("refCos = "+refCos);
System.out.println("resCos = "+resCos);
}
assertTrue(sinHelper.lastOK());
assertTrue(cosHelper.lastOK());
boolean rangeOK = (Double.isNaN(res) || NumbersUtils.isInRange(-Math.PI/2, Math.PI/2, res));
// Either both diff or none diff.
if (sinSignDiff ^ cosSignDiff) {
// If only one sign changes,
// we must be very close to +-PI/2 or 0 or PI.
rangeOK &= (Math.abs(refSin) < TOL_FAST_TRIG_NORM_ABS) || (Math.abs(refCos) < TOL_FAST_TRIG_NORM_ABS);
}
if (!rangeOK) {
System.out.println("value = "+value);
System.out.println("res = "+res);
}
assertTrue(rangeOK);
}
sinHelper.finalLogIfNeeded();
cosHelper.finalLogIfNeeded();
}
/*
* floating points utils
*/
public void test_isNaNOrInfinite_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
boolean ref = Float.isNaN(value) || Float.isInfinite(value);
boolean res = StrictFastMath.isNaNOrInfinite(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_isNaNOrInfinite_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
boolean ref = Double.isNaN(value) || Double.isInfinite(value);
boolean res = StrictFastMath.isNaNOrInfinite(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_getExponent_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
int ref = Math.getExponent(value);
int res = StrictFastMath.getExponent(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_getExponent_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
int ref = Math.getExponent(value);
int res = StrictFastMath.getExponent(value);
boolean ok = (ref == res);
if (!ok) {
printCallerName();
System.out.println("value = "+value);
System.out.println("ref = "+ref);
System.out.println("res = "+res);
}
assertTrue(ok);
}
}
public void test_signum_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = Math.signum(value);
float res = StrictFastMath.signum(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_signum_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.signum(value);
double res = StrictFastMath.signum(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_signFromBit_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
int ref = (Float.floatToRawIntBits(value) < 0 ? -1 : 1);
int res = StrictFastMath.signFromBit(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_signFromBit_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
long ref = (Double.doubleToRawLongBits(value) < 0 ? -1L : 1L);
long res = StrictFastMath.signFromBit(value);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_copySign_2float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float a = randomFloatWhatever();
float b = randomFloatWhatever();
float ref = StrictMath.copySign(a,b);
float res = StrictFastMath.copySign(a,b);
assertEquals(ref, res);
}
}
public void test_copySign_2double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = StrictMath.copySign(a,b);
double res = StrictFastMath.copySign(a,b);
assertEquals(ref, res);
}
}
public void test_ulp_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = Math.ulp(value);
float res = StrictFastMath.ulp(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_ulp_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.ulp(value);
double res = StrictFastMath.ulp(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextAfter_float_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float a = randomFloatWhatever();
double b = randomDoubleWhatever();
float ref = Math.nextAfter(a,b);
float res = StrictFastMath.nextAfter(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextAfter_2double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = Math.nextAfter(a,b);
double res = StrictFastMath.nextAfter(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextDown_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = Math.nextAfter(value,Double.NEGATIVE_INFINITY);
float res = StrictFastMath.nextDown(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextDown_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.nextAfter(value,Double.NEGATIVE_INFINITY);
double res = StrictFastMath.nextDown(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextUp_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = Math.nextAfter(value,Double.POSITIVE_INFINITY);
float res = StrictFastMath.nextUp(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_nextUp_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.nextAfter(value,Double.POSITIVE_INFINITY);
double res = StrictFastMath.nextUp(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_scalb_float_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float a = randomFloatWhatever();
int b = randomIntWhatever();
float ref = Math.scalb(a,b);
float res = StrictFastMath.scalb(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_scalb_double_int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
int b = randomIntWhatever();
double ref = Math.scalb(a,b);
double res = StrictFastMath.scalb(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
/*
* Non-redefined public values and treatments.
*/
public void test_E() {
assertEquals(Math.E, StrictFastMath.E);
}
public void test_PI() {
assertEquals(Math.PI, StrictFastMath.PI);
}
public void test_abs_float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float value = randomFloatWhatever();
float ref = Math.abs(value);
float res = StrictFastMath.abs(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_abs_double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double value = randomDoubleWhatever();
double ref = Math.abs(value);
double res = StrictFastMath.abs(value);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_min_2int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int a = randomIntWhatever();
int b = randomIntWhatever();
int ref = Math.min(a,b);
int res = StrictFastMath.min(a,b);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_min_2long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long a = randomLongWhatever();
long b = randomLongWhatever();
long ref = Math.min(a,b);
long res = StrictFastMath.min(a,b);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_min_2float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float a = randomFloatWhatever();
float b = randomFloatWhatever();
float ref = Math.min(a,b);
float res = StrictFastMath.min(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_min_2double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = Math.min(a,b);
double res = StrictFastMath.min(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_max_2int() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
int a = randomIntWhatever();
int b = randomIntWhatever();
int ref = Math.max(a,b);
int res = StrictFastMath.max(a,b);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_max_2long() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
long a = randomLongWhatever();
long b = randomLongWhatever();
long ref = Math.max(a,b);
long res = StrictFastMath.max(a,b);
boolean ok = (ref == res);
assertTrue(ok);
}
}
public void test_max_2float() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
float a = randomFloatWhatever();
float b = randomFloatWhatever();
float ref = Math.max(a,b);
float res = StrictFastMath.max(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_max_2double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = Math.max(a,b);
double res = StrictFastMath.max(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_IEEEremainder_2double() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double a = randomDoubleWhatever();
double b = randomDoubleWhatever();
double ref = Math.IEEEremainder(a,b);
double res = StrictFastMath.IEEEremainder(a,b);
boolean ok = equivalent(ref,res);
assertTrue(ok);
}
}
public void test_random() {
for (int i=0;i<NBR_OF_VALUES_SMALL;i++) {
double res = StrictFastMath.random();
assertTrue((res >= 0.0) && (res < 1.0));
}
}
}
| {
"content_hash": "8a1630a5d2138fdf138e1f0c3aae1b44",
"timestamp": "",
"source": "github",
"line_count": 2620,
"max_line_length": 142,
"avg_line_length": 37.92404580152672,
"alnum_prop": 0.5176678978673726,
"repo_name": "Trugath/Jafama",
"id": "9897184379a9c8b965521cbcd22a14f77ad819c6",
"size": "99953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/net/jafama/StrictFastMathTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1092925"
},
{
"name": "Scala",
"bytes": "379"
}
],
"symlink_target": ""
} |
package org.gradle.test.performance.mediummonolithicjavaproject.p104;
public class Production2092 {
private Production2089 property0;
public Production2089 getProperty0() {
return property0;
}
public void setProperty0(Production2089 value) {
property0 = value;
}
private Production2090 property1;
public Production2090 getProperty1() {
return property1;
}
public void setProperty1(Production2090 value) {
property1 = value;
}
private Production2091 property2;
public Production2091 getProperty2() {
return property2;
}
public void setProperty2(Production2091 value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | {
"content_hash": "1d450c509eb7a578ae7d043fce4c8020",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 69,
"avg_line_length": 18.695238095238096,
"alnum_prop": 0.6311767702496179,
"repo_name": "oehme/analysing-gradle-performance",
"id": "7277688b46f56fa07a03436ca28bb5548766fb7d",
"size": "1963",
"binary": false,
"copies": "1",
"ref": "refs/heads/before",
"path": "my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p104/Production2092.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "40770723"
}
],
"symlink_target": ""
} |
"""Tests for clif.testing.python.template_alias."""
from absl.testing import absltest
from clif.testing.python import template_alias
class TemplateAliasTest(absltest.TestCase):
def testTemplateAlias(self):
# Calling the following functions should not blow up.
template_alias.func_default_vector_input([])
output = template_alias.func_default_vector_output()
self.assertLen(output, 1)
self.assertEqual(output[0], 123)
return_list = template_alias.func_default_vector_return()
self.assertLen(return_list, 1)
self.assertEqual(return_list[0], 100)
template_alias.func_clif_vector([1])
template_alias.func_signed_size_type_output()
if __name__ == '__main__':
absltest.main()
| {
"content_hash": "56b82c4ed29d990b5c07fe80edce5573",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 61,
"avg_line_length": 30.041666666666668,
"alnum_prop": 0.7212205270457698,
"repo_name": "google/clif",
"id": "323f17fa06ba6b8d5d7977a5c3ce43fc61e80f1f",
"size": "1298",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "clif/testing/python/template_alias_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4035"
},
{
"name": "C++",
"bytes": "685973"
},
{
"name": "CMake",
"bytes": "29813"
},
{
"name": "Dockerfile",
"bytes": "4053"
},
{
"name": "Python",
"bytes": "742833"
},
{
"name": "Starlark",
"bytes": "28337"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Javadoc API documentation for Fresco 1.1.0." />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../favicon.ico" />
<title>
AnimatedImageDecoder - Fresco 1.1.0 API
| Fresco 1.1.0
</title>
<link href="../../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<script src="../../../../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script>
<script src="../../../../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
setToRoot("../../../../../", "../../../../../../assets/");
</script>
<script src="../../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script>
<script src="../../../../../../assets/navtree_data.js" type="text/javascript"></script>
<script src="../../../../../../assets/customizations.js" type="text/javascript"></script>
<noscript>
<style type="text/css">
html,body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
</head>
<body class="">
<div id="header">
<div id="headerLeft">
<span id="masthead-title"><a href="../../../../../packages.html">Fresco 1.1.0</a></span>
</div>
<div id="headerRight">
<div id="search" >
<div id="searchForm">
<form accept-charset="utf-8" class="gsc-search-box"
onsubmit="return submit_search()">
<table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
<tr>
<td class="gsc-input">
<input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
title="search developer docs" name="q"
value="search developer docs"
onFocus="search_focus_changed(this, true)"
onBlur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../')" />
<div id="search_filtered_div" class="no-display">
<table id="search_filtered" cellspacing=0>
</table>
</div>
</td>
<!-- <td class="gsc-search-button">
<input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
</td>
<td class="gsc-clear-button">
<div title="clear results" class="gsc-clear-button"> </div>
</td> -->
</tr></tbody>
</table>
</form>
</div><!-- searchForm -->
</div><!-- search -->
</div>
</div><!-- header -->
<div class="g-section g-tpl-240" id="body-content">
<div class="g-unit g-first side-nav-resizable" id="side-nav">
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav">
<div id="index-links">
<a href="../../../../../packages.html" >Packages</a> |
<a href="../../../../../classes.html" >Classes</a>
</div>
<ul>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/fresco/animation/wrapper/package-summary.html">com.facebook.fresco.animation.wrapper</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li>
<li class="selected api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li>
<li class="api apilevel-">
<a href="../../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li>
</ul><br/>
</div> <!-- end packages -->
</div> <!-- end resize-packages -->
<div id="classes-nav">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedDrawableFactory.html">AnimatedDrawableFactory</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedFactory.html">AnimatedFactory</a></li>
<li class="selected api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedImageDecoder.html">AnimatedImageDecoder</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedImageFactory.html">AnimatedImageFactory</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedDrawableFactoryImpl.html">AnimatedDrawableFactoryImpl</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedDrawableFactoryImplSupport.html">AnimatedDrawableFactoryImplSupport</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedFactoryImpl.html">AnimatedFactoryImpl</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedFactoryImplSupport.html">AnimatedFactoryImplSupport</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedFactoryProvider.html">AnimatedFactoryProvider</a></li>
<li class="api apilevel-"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedImageFactoryImpl.html">AnimatedImageFactoryImpl</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none">
<div id="index-links">
<a href="../../../../../packages.html" >Packages</a> |
<a href="../../../../../classes.html" >Classes</a>
</div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
</div> <!-- end side-nav -->
<script>
if (!isMobile) {
//$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav");
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../");
} else {
addLoadEvent(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
}
//$("#swapper").css({borderBottom:"2px solid #aaa"});
} else {
swapNav(); // tree view should be used on mobile
}
</script>
<div class="g-unit" id="doc-content">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#pubmethods">Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
interface
<h1>AnimatedImageDecoder</h1>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="1" class="jd-inheritance-class-cell">com.facebook.imagepipeline.animated.factory.AnimatedImageDecoder</td>
</tr>
</table>
<table class="jd-sumtable jd-sumtable-subclasses"><tr><td colspan="12" style="border:none;margin:0;padding:0;">
<a href="#" onclick="return toggleInherited(this, null)" id="subclasses-indirect" class="jd-expando-trigger closed"
><img id="subclasses-indirect-trigger"
src="../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>Known Indirect Subclasses
<div id="subclasses-indirect">
<div id="subclasses-indirect-list"
class="jd-inheritedlinks"
>
<a href="../../../../../com/facebook/animated/gif/GifImage.html">GifImage</a>,
<a href="../../../../../com/facebook/animated/webp/WebPImage.html">WebPImage</a>
</div>
<div id="subclasses-indirect-summary"
style="display: none;"
>
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../com/facebook/animated/gif/GifImage.html">GifImage</a></td>
<td class="jd-descrcol" width="100%">A representation of a GIF image. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../com/facebook/animated/webp/WebPImage.html">WebPImage</a></td>
<td class="jd-descrcol" width="100%">A representation of a WebP image. </td>
</tr>
</table>
</div>
</div>
</td></tr></table>
<div class="jd-descr">
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">
abstract
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImage.html">AnimatedImage</a>
</td>
<td class="jd-linkcol" width="100%">
<span class="sympad"><a href="../../../../../com/facebook/imagepipeline/animated/factory/AnimatedImageDecoder.html#decode(long, int)">decode</a></span>(long nativePtr, int sizeInBytes)
<div class="jd-descrdiv">Factory method to create the AnimatedImage from the</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<a id="decode(long, int)"></a>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
abstract
<a href="../../../../../com/facebook/imagepipeline/animated/base/AnimatedImage.html">AnimatedImage</a>
</span>
<span class="sympad">decode</span>
<span class="normal">(long nativePtr, int sizeInBytes)</span>
</h4>
<div class="api-level">
<div>
</div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Factory method to create the AnimatedImage from the</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>nativePtr</th>
<td>The native pointer</td>
</tr>
<tr>
<th>sizeInBytes</th>
<td>The size in byte to allocate</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The AnimatedImage allocation
</li></ul>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<a id="navbar_top"></a>
<div id="footer">
+Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>.
+</div> <!-- end footer - @generated -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script type="text/javascript">
init(); /* initialize doclava-developer-docs.js */
</script>
</body>
</html>
| {
"content_hash": "5d9567b10027b1a6e5b1b86de7b107de",
"timestamp": "",
"source": "github",
"line_count": 658,
"max_line_length": 296,
"avg_line_length": 34.650455927051674,
"alnum_prop": 0.5901315789473685,
"repo_name": "desmond1121/fresco",
"id": "b83acc736e58165a4e580ae86aa2404571bd61e1",
"size": "22800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadoc/reference/com/facebook/imagepipeline/animated/factory/AnimatedImageDecoder.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "22418"
},
{
"name": "C++",
"bytes": "212041"
},
{
"name": "IDL",
"bytes": "1003"
},
{
"name": "Java",
"bytes": "2750756"
},
{
"name": "Makefile",
"bytes": "7247"
},
{
"name": "Prolog",
"bytes": "153"
},
{
"name": "Python",
"bytes": "10351"
},
{
"name": "Shell",
"bytes": "102"
}
],
"symlink_target": ""
} |
package com.fpt.mic.mobile.checker.app;
import android.app.Application;
import android.content.Context;
/**
* Created by trungdq on 06/08/2014.
*/
public class MainApplication extends Application {
public static Context mContext;
/**
* Static class to get app context everywhere.
* Use it carefully if or you will get memory leak
* @return Context
*/
public static Context getAppContext() {
return mContext;
}
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
@Override
public void onTerminate() {
super.onTerminate();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
| {
"content_hash": "2b3bfb9d2479a6b7cde31be1baff3eea",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 54,
"avg_line_length": 19.657894736842106,
"alnum_prop": 0.6345381526104418,
"repo_name": "trungdq88/insurance-card",
"id": "e972a72ba9c13f2dfba0c975d9a3d18e9b95bd19",
"size": "747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source code/CheckerMobileApp/app/src/main/java/com/fpt/mic/mobile/checker/app/MainApplication.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "242281"
},
{
"name": "HTML",
"bytes": "416170"
},
{
"name": "Java",
"bytes": "1844256"
},
{
"name": "JavaScript",
"bytes": "803794"
}
],
"symlink_target": ""
} |
Rails.application.routes.draw do
mount Sidekiq::Web => '/sidekiq'
get 'auth/:provider/callback', to: 'sessions#create', as: :oauth_callback
get 'auth/failure', to: redirect('/')
get :sign_in, to: "sessions#new", as: :sign_in
get :sign_out, to: "sessions#destroy", as: :sign_out
resources :tags
resources :authors, only: [:index, :show, :new, :create, :update] do
put :toggle_status, to: "authors#toggle_status", as: :toggle_status
put :toggle_email_privacy
end
resources :articles do
collection do
get :fresh
get :stale
get :outdated
get :archived
get :popular
end
member do
put :toggle_subscription
put :toggle_endorsement
put :report_outdated
put :mark_fresh
put :toggle_archived
get :subscriptions
end
end
resources :guides, only: [:index]
resources :subscriptions, only: :index
resources :endorsements, only: :index
get 'opensearchdescription.xml' => 'open_search/descriptions#show',
format: false,
defaults: { format: :osd_xml },
as: :open_search_description
# this has to be the last route because we're catching slugs at the root path
resources :articles, path: "", only: :show
root "guides#index"
# Serve websocket cable requests in-process
# mount ActionCable.server => '/cable'
end
| {
"content_hash": "258463d4057ea762d949e272a834ed87",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 79,
"avg_line_length": 26.82,
"alnum_prop": 0.6621923937360179,
"repo_name": "orientation/orientation",
"id": "001399dbea7fcb602f03e8e8176c795dfd4e86f4",
"size": "1341",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/routes.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "19686"
},
{
"name": "Dockerfile",
"bytes": "1431"
},
{
"name": "HTML",
"bytes": "4588"
},
{
"name": "Haml",
"bytes": "24951"
},
{
"name": "JavaScript",
"bytes": "974"
},
{
"name": "Ruby",
"bytes": "158928"
},
{
"name": "SCSS",
"bytes": "7798"
},
{
"name": "Sass",
"bytes": "52565"
},
{
"name": "Shell",
"bytes": "3770"
}
],
"symlink_target": ""
} |
require_relative 'ar_virtual'
module ArRegion
extend ActiveSupport::Concern
DEFAULT_RAILS_SEQUENCE_FACTOR = 1_000_000_000_000
COMPRESSED_ID_SEPARATOR = 'r'.freeze
CID_OR_ID_MATCHER = "\\d+?(#{COMPRESSED_ID_SEPARATOR}\\d+)?".freeze
RE_COMPRESSED_ID = /^(\d+)#{COMPRESSED_ID_SEPARATOR}(\d+)$/
included do
cache_with_timeout(:id_to_miq_region) { Hash.new }
end
def self.anonymous_class_with_ar_region
@klass_with_ar_region ||= Class.new(ActiveRecord::Base).send(:include, self)
end
module ClassMethods
def inherited(other)
if other == other.base_class
other.class_eval do
virtual_column :region_number, :type => :integer
virtual_column :region_description, :type => :string
end
end
super
end
def my_region_number(force_reload = false)
clear_region_cache if force_reload
@@my_region_number ||= discover_my_region_number
end
def rails_sequence_factor
DEFAULT_RAILS_SEQUENCE_FACTOR
end
def rails_sequence_start
@@rails_sequence_start ||= my_region_number * rails_sequence_factor
end
def rails_sequence_end
@@rails_sequence_end ||= rails_sequence_start + rails_sequence_factor - 1
end
def rails_sequence_range
rails_sequence_start..rails_sequence_end
end
def clear_region_cache
@@my_region_number = @@rails_sequence_start = @@rails_sequence_end = nil
end
def id_to_region(id)
id.to_i / rails_sequence_factor
end
def id_in_region(id, region_number)
region_number * rails_sequence_factor + id
end
def region_to_range(region_number)
(region_number * rails_sequence_factor)..(region_number * rails_sequence_factor + rails_sequence_factor - 1)
end
def region_to_conditions(region_number, col = "id")
["#{col} >= ? AND #{col} <= ?", *region_to_array(region_number)]
end
def region_to_array(region_number)
range = region_to_range(region_number)
[range.first, range.last]
end
def in_my_region
in_region(my_region_number)
end
def in_region(region_number)
region_number.nil? ? all : where(:id => region_to_range(region_number))
end
def with_region(region_number)
where(:id => region_to_range(region_number)).scoping { yield }
end
def id_in_current_region?(id)
id_to_region(id) == my_region_number
end
def split_id(id)
return [my_region_number, nil] if id.nil?
id = uncompress_id(id)
region_number = id_to_region(id)
short_id = (region_number == 0) ? id : id % (region_number * rails_sequence_factor)
return region_number, short_id
end
#
# ID compression
#
def compressed_id?(id)
id.to_s =~ /^#{CID_OR_ID_MATCHER}$/
end
def compress_id(id)
return nil if id.nil?
region_number, short_id = split_id(id)
(region_number == 0) ? short_id.to_s : "#{region_number}#{COMPRESSED_ID_SEPARATOR}#{short_id}"
end
def uncompress_id(compressed_id)
return nil if compressed_id.nil?
compressed_id.to_s =~ RE_COMPRESSED_ID ? ($1.to_i * rails_sequence_factor + $2.to_i) : compressed_id.to_i
end
#
# Helper methods
#
# Partition the passed AR objects into local and remote sets
def partition_objs_by_remote_region(objs)
objs.partition(&:in_current_region?)
end
# Partition the passed ids into local and remote sets
def partition_ids_by_remote_region(ids)
ids.partition { |id| self.id_in_current_region?(id) }
end
def group_ids_by_region(ids)
ids.group_by { |id| id_to_region(id) }
end
def region_number_from_sequence
return unless connection.data_source_exists?("miq_databases")
id_to_region(connection.select_value("SELECT last_value FROM miq_databases_id_seq"))
end
private
def discover_my_region_number
region_file = File.join(Rails.root, "REGION")
region_num = File.read(region_file) if File.exist?(region_file)
region_num ||= ENV.fetch("REGION", nil)
region_num ||= region_number_from_sequence
region_num.to_i
end
end
def my_region_number
self.class.my_region_number
end
def in_current_region?
region_number == my_region_number
end
def region_number
id ? (id / self.class.rails_sequence_factor) : my_region_number
end
alias_method :region_id, :region_number
def region_description
miq_region.description if miq_region
end
def miq_region
self.class.id_to_miq_region[region_number] || (self.class.id_to_miq_region[region_number] = MiqRegion.where(:region => region_number).first)
end
def compressed_id
self.class.compress_id(id)
end
def split_id
self.class.split_id(id)
end
end
| {
"content_hash": "d59e9f50754a9cd9fe99bb3920d63da6",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 144,
"avg_line_length": 26.229508196721312,
"alnum_prop": 0.643125,
"repo_name": "fbladilo/manageiq",
"id": "c26f9e73052e03911c93be513c74e3f36c3bdf06",
"size": "4800",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "lib/extensions/ar_region.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2167"
},
{
"name": "JavaScript",
"bytes": "183"
},
{
"name": "PowerShell",
"bytes": "2644"
},
{
"name": "Ruby",
"bytes": "10494037"
},
{
"name": "Shell",
"bytes": "2696"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>reflexive-first-order: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.1 / reflexive-first-order - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
reflexive-first-order
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-27 06:24:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-27 06:24:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/reflexive-first-order"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ReflexiveFirstOrder"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [
"keyword: computational reflection"
"keyword: interpretation"
"keyword: first-order logic"
"keyword: equational reasoning"
"category: Miscellaneous/Coq Extensions"
"date: 2005-05"
]
authors: [ "Pierre Corbineau <pierre.corbineau@lri.fr> [http://www.cs.ru.nl/~corbineau]" ]
bug-reports: "https://github.com/coq-contribs/reflexive-first-order/issues"
dev-repo: "git+https://github.com/coq-contribs/reflexive-first-order.git"
synopsis: "Reflexive first-order proof interpreter"
description: """
This contribution is a package which can be used to interpret firstorder
proofs provided by an external theorem prover, using computational
reflexion."""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/reflexive-first-order/archive/v8.8.0.tar.gz"
checksum: "md5=1d9a59f1bcae100117c45eefd670e30b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-reflexive-first-order.8.8.0 coq.8.11.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1).
The following dependencies couldn't be met:
- coq-reflexive-first-order -> coq < 8.9~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-reflexive-first-order.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "0cc8d1dc618a4de827ce955ffa1101d9",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 159,
"avg_line_length": 41.31791907514451,
"alnum_prop": 0.5537213206491326,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "8fbf3b79502a7e7489b623d09ae907f2e00ceaae",
"size": "7173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.11.1/reflexive-first-order/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.google.cloud.compute.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;
@Generated("by GAPIC")
@BetaApi
public final class UsableSubnetworksAggregatedList implements ApiMessage {
private final String id;
private final List<UsableSubnetwork> items;
private final String kind;
private final String nextPageToken;
private final String selfLink;
private final Warning warning;
private UsableSubnetworksAggregatedList() {
this.id = null;
this.items = null;
this.kind = null;
this.nextPageToken = null;
this.selfLink = null;
this.warning = null;
}
private UsableSubnetworksAggregatedList(
String id,
List<UsableSubnetwork> items,
String kind,
String nextPageToken,
String selfLink,
Warning warning) {
this.id = id;
this.items = items;
this.kind = kind;
this.nextPageToken = nextPageToken;
this.selfLink = selfLink;
this.warning = warning;
}
@Override
public Object getFieldValue(String fieldName) {
if ("id".equals(fieldName)) {
return id;
}
if ("items".equals(fieldName)) {
return items;
}
if ("kind".equals(fieldName)) {
return kind;
}
if ("nextPageToken".equals(fieldName)) {
return nextPageToken;
}
if ("selfLink".equals(fieldName)) {
return selfLink;
}
if ("warning".equals(fieldName)) {
return warning;
}
return null;
}
@Nullable
@Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@Nullable
@Override
/**
* The fields that should be serialized (even if they have empty values). If the containing
* message object has a non-null fieldmask, then all the fields in the field mask (and only those
* fields in the field mask) will be serialized. If the containing object does not have a
* fieldmask, then only non-empty fields will be serialized.
*/
public List<String> getFieldMask() {
return null;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
*/
public String getId() {
return id;
}
/** [Output] A list of usable subnetwork URLs. */
public List<UsableSubnetwork> getItemsList() {
return items;
}
/**
* [Output Only] Type of resource. Always compute#usableSubnetworksAggregatedList for aggregated
* lists of usable subnetworks.
*/
public String getKind() {
return kind;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/** [Output Only] Server-defined URL for this resource. */
public String getSelfLink() {
return selfLink;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(UsableSubnetworksAggregatedList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
public static UsableSubnetworksAggregatedList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final UsableSubnetworksAggregatedList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new UsableSubnetworksAggregatedList();
}
public static class Builder {
private String id;
private List<UsableSubnetwork> items;
private String kind;
private String nextPageToken;
private String selfLink;
private Warning warning;
Builder() {}
public Builder mergeFrom(UsableSubnetworksAggregatedList other) {
if (other == UsableSubnetworksAggregatedList.getDefaultInstance()) return this;
if (other.getId() != null) {
this.id = other.id;
}
if (other.getItemsList() != null) {
this.items = other.items;
}
if (other.getKind() != null) {
this.kind = other.kind;
}
if (other.getNextPageToken() != null) {
this.nextPageToken = other.nextPageToken;
}
if (other.getSelfLink() != null) {
this.selfLink = other.selfLink;
}
if (other.getWarning() != null) {
this.warning = other.warning;
}
return this;
}
Builder(UsableSubnetworksAggregatedList source) {
this.id = source.id;
this.items = source.items;
this.kind = source.kind;
this.nextPageToken = source.nextPageToken;
this.selfLink = source.selfLink;
this.warning = source.warning;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the
* server.
*/
public String getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the
* server.
*/
public Builder setId(String id) {
this.id = id;
return this;
}
/** [Output] A list of usable subnetwork URLs. */
public List<UsableSubnetwork> getItemsList() {
return items;
}
/** [Output] A list of usable subnetwork URLs. */
public Builder addAllItems(List<UsableSubnetwork> items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.addAll(items);
return this;
}
/** [Output] A list of usable subnetwork URLs. */
public Builder addItems(UsableSubnetwork items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.add(items);
return this;
}
/**
* [Output Only] Type of resource. Always compute#usableSubnetworksAggregatedList for aggregated
* lists of usable subnetworks.
*/
public String getKind() {
return kind;
}
/**
* [Output Only] Type of resource. Always compute#usableSubnetworksAggregatedList for aggregated
* lists of usable subnetworks.
*/
public Builder setKind(String kind) {
this.kind = kind;
return this;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public Builder setNextPageToken(String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
/** [Output Only] Server-defined URL for this resource. */
public String getSelfLink() {
return selfLink;
}
/** [Output Only] Server-defined URL for this resource. */
public Builder setSelfLink(String selfLink) {
this.selfLink = selfLink;
return this;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
/** [Output Only] Informational warning message. */
public Builder setWarning(Warning warning) {
this.warning = warning;
return this;
}
public UsableSubnetworksAggregatedList build() {
return new UsableSubnetworksAggregatedList(id, items, kind, nextPageToken, selfLink, warning);
}
public Builder clone() {
Builder newBuilder = new Builder();
newBuilder.setId(this.id);
newBuilder.addAllItems(this.items);
newBuilder.setKind(this.kind);
newBuilder.setNextPageToken(this.nextPageToken);
newBuilder.setSelfLink(this.selfLink);
newBuilder.setWarning(this.warning);
return newBuilder;
}
}
@Override
public String toString() {
return "UsableSubnetworksAggregatedList{"
+ "id="
+ id
+ ", "
+ "items="
+ items
+ ", "
+ "kind="
+ kind
+ ", "
+ "nextPageToken="
+ nextPageToken
+ ", "
+ "selfLink="
+ selfLink
+ ", "
+ "warning="
+ warning
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof UsableSubnetworksAggregatedList) {
UsableSubnetworksAggregatedList that = (UsableSubnetworksAggregatedList) o;
return Objects.equals(this.id, that.getId())
&& Objects.equals(this.items, that.getItemsList())
&& Objects.equals(this.kind, that.getKind())
&& Objects.equals(this.nextPageToken, that.getNextPageToken())
&& Objects.equals(this.selfLink, that.getSelfLink())
&& Objects.equals(this.warning, that.getWarning());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(id, items, kind, nextPageToken, selfLink, warning);
}
}
| {
"content_hash": "c70493b5e93f3c40b119f80062d54982",
"timestamp": "",
"source": "github",
"line_count": 352,
"max_line_length": 100,
"avg_line_length": 27.832386363636363,
"alnum_prop": 0.6511176890884964,
"repo_name": "vam-google/google-cloud-java",
"id": "68fff21b7c56b7dc58cf9ed527a4ed8b315654f5",
"size": "10391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/UsableSubnetworksAggregatedList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "128"
},
{
"name": "CSS",
"bytes": "23036"
},
{
"name": "Dockerfile",
"bytes": "127"
},
{
"name": "Go",
"bytes": "9641"
},
{
"name": "HTML",
"bytes": "16158"
},
{
"name": "Java",
"bytes": "47356483"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "110799"
},
{
"name": "Shell",
"bytes": "9162"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "86094fb732e6970e14804b15208669cf",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e9a2a2677fbb6f89007a0428b546ef389d495404",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Laseguea/Laseguea acutifolia/Laseguea acutifolia obliquinervia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require "yaml"
require "rdf"
require "configatron/core"
require "parmenides/client"
require "parmenides/environment"
require "parmenides/cachable"
require "parmenides/entity"
require "parmenides/ontology/klass"
require "parmenides/ontology/property"
require "parmenides/ontology"
require "parmenides/resource"
require "parmenides/infobox"
# require "parmenides/loader/klass_loader"
require "parmenides/processor"
require "parmenides/processor/histogram_processor"
require "parmenides/processor/generic_processor"
require "parmenides/processor/specific_processor"
require "parmenides/processor/merge_preprocessor"
require "parmenides/mapper/mapper"
require "parmenides/mapper/known_mappers"
require "parmenides/evaluation/evaluation_result"
require "parmenides/evaluation/resource_base"
require "parmenides/evaluation/evaluator"
require "parmenides/evaluation/pnr_resource_evaluator"
require "parmenides/evaluation/tag_resource_evaluator"
require "parmenides/evaluation/resource_evaluator"
require "parmenides/evaluation/property_evaluator"
require "parmenides/version" | {
"content_hash": "3b2ce2deda0014e248eb1d13395bd4cd",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 54,
"avg_line_length": 29.88888888888889,
"alnum_prop": 0.8355018587360595,
"repo_name": "theollyr/parmenides",
"id": "dc59a0c68caf8fc9dee1f6f4fb6ad57a74824876",
"size": "1076",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/parmenides.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "53733"
}
],
"symlink_target": ""
} |
"""
input data
save yaml file
"""
import yaml
import codecs
import os
import sys
class cover :
def __init__(self,width,height,font,fontsize,color,nOfCover,makingway,title):
self.font = font
self.fontsize = fontsize
self.width = width
self.height = height
self.color = color
self.nOfCover = nOfCover
self.makingway = makingway
self.title = title
def print_Cover(cover) :
"""
print "Nmae", ":",cover["nmae"]
print "width",":",cover["width"]
print "height",":",cover["height"]
print "font",":",cover["font"]
"""
data =dict(width = cover.width, height = cover.height,font = cover.font, fontsize = cover.fontsize, color = cover.color, numberOfCover = cover.nOfCover, makingway = cover.makingway, title = cover.title)
return data
"""
a = cover("test1",20,10,33,0)
cover_list = list()
cover_list.append(a)
doc = yaml.load(codecs.open("cover.yaml","w","euc-kr"))
if cover_list :
for cover in cover_list :
print_Cover(cover)
"""
data_list = dict()
a = cover(250,350,"Arial.ttf",40,"Yellow",10,"auto",'')
cover_list = list()
data = print_Cover(a)
cover_list.append(data)
#data_list.update(data)
#cover_list.append(data)
with open('config.yaml','w') as outfile:
outfile.write(yaml.dump_all(cover_list,default_flow_style=False)) | {
"content_hash": "05d619d26cb3651a923e6bf05fcf7b15",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 206,
"avg_line_length": 23.50877192982456,
"alnum_prop": 0.6425373134328358,
"repo_name": "BD823/pcover",
"id": "fd055c716b5e195cfbb3b3c76ce50d71429c022d",
"size": "1340",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project_version1/MakingYaml.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "61691"
}
],
"symlink_target": ""
} |
package org.springframework.security.test.web.servlet.showcase.secured;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SecurityRequestsTests.Config.class)
@WebAppConfiguration
public class SecurityRequestsTests {
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private UserDetailsService userDetailsService;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
mvc
.perform(get("/").with(user("user")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
mvc
.perform(get("/admin").with(user("admin").roles("ADMIN")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with admin
.andExpect(authenticated().withUsername("admin"));
}
@Test
public void requestProtectedUrlWithUserDetails() throws Exception {
UserDetails user = userDetailsService.loadUserByUsername("user");
mvc
.perform(get("/").with(user(user)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthenticationPrincipal(user));
}
@Test
public void requestProtectedUrlWithAuthentication() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "notused", "ROLE_USER");
mvc
.perform(get("/").with(authentication(authentication)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthentication(authentication));
}
@Configuration
@EnableWebMvcSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
} | {
"content_hash": "f1f4d835538c1df29a0e9d60b518bf4a",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 107,
"avg_line_length": 39.53543307086614,
"alnum_prop": 0.7124078868751245,
"repo_name": "drdamour/spring-security",
"id": "82af6745f5a4b9cb67eef2ea5c5b058a382152dc",
"size": "5641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/SecurityRequestsTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.bosphorus.core.expression.scalar.factory.date;
import java.util.Date;
import org.bosphorus.core.expression.scalar.executor.IScalarExecutor1;
import org.bosphorus.core.expression.scalar.executor.date.TruncateToDayExecutor;
import org.bosphorus.core.expression.scalar.factory.IScalarExecutorFactory1;
public class TruncateToDayExecutorFactory implements IScalarExecutorFactory1<Date, Date> {
private static TruncateToDayExecutor instance = new TruncateToDayExecutor();
@Override
public IScalarExecutor1<Date, Date> create() {
return instance;
}
}
| {
"content_hash": "91ead19178f9016dcd9b3f38d3cc39ab",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 90,
"avg_line_length": 28.6,
"alnum_prop": 0.8269230769230769,
"repo_name": "unluonur/bosphorus",
"id": "2f2d7ec82d6a01f6f1294f985923b859d151cf60",
"size": "1252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bosphorus-core/src/main/java/org/bosphorus/core/expression/scalar/factory/date/TruncateToDayExecutorFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "575320"
}
],
"symlink_target": ""
} |
module Hipe::SocialSync::Plugins
class Items
include Hipe::Cli
include Hipe::SocialSync::Model
include Hipe::SocialSync::ControllerCommon
include Hipe::SocialSync::ViewCommon
cli.out.klass = Hipe::SocialSync::GoldenHammer
cli.description = "blog entries"
cli.does 'help','overview of item commands'
cli.default_command = :help
cli.does(:add, "add an entry and asociate it w/ an account") do
option('-h','--help',&help)
option('-d', '--[no-]dry', "Dry run. Does everything the same but doesn't write to the database.")
option('-s', '--source ID', "If this blog is a clone, what is the source item id?") do |it|
it.must_be_positive_integer()
end
required('service-name')
required('name-credential')
required('foreign-id')
required('author')
required('content-str')
required('keywords-str')
required('published_at')
required('status')
required('title')
required('current_user_email')
end
def add(service_name, name_credential, foreign_id,
author, content, keywords_str,
published_at, status, title,
user_email, opts)
out = cli.out.new
user = current_user(user_email)
svc = Service.first_or_throw(:name=>service_name)
acct = Account.first_or_throw(:name_credential=>name_credential, :service=>svc, :user=>user)
if (opts.dry)
item = Object.new # openstruct won't work
def item.id; 'dry-run' end
out << %{Added blog entry (ours: ##{item.id}, theirs: ##{foreign_id}).}
else
validation_errors = catch(:invalid) do
item = Item.kreate(acct, foreign_id, author, content, keywords_str, published_at, status, title, user, opts)
out << %{Added blog entry (ours: ##{item.id}, theirs: ##{foreign_id}).}
out.data.item = item
nil
end
if validation_errors
out.errors << validation_errors.to_s
end
end
out
end
cli.does(:view, "show all details for an individual item") do
option('-h',&help)
option('--ah','admin hack')
required('id','id of the item to view')
required('current_user_email')
end
def view(id, current_user_email, opts)
item = Item.first_or_throw(:id=>id)
user = current_user current_user_email
if item.user != user && ! opts.ah
return cli.out.new(:error => "That item doesn't belong to you")
end
out = cli.out.new :suggested_template => :tables
out.data.item = item
out.data.tables = OrderedHash.new
table = self.class.table
table.list = [item]
table.axis = :horizontal
table.label = item.one_word
out.data.tables[table.name] = table
table = Log.table
table.list = item.events
out.data.tables[table.name] = table
# clones_table = Events.table
# clones_table.name = 'clones'
# clones_table.show_only :id,:theirs,:user,:service,:name_cred,:published_at,:title,:excerpt,:last_event
# clones_table.list = item.clones
# d.tables << clones_table
out
end
def self.table
Hipe::Table.make do
extend Hipe::SocialSync::ViewCommon
self.name = 'items'
field(:id){|x| x.id}
field(:theirs){|x| x.foreign_id}
field(:user){|x| x.account.user.one_word }
field(:service){|x| x.account.service.name}
field(:name_cred){|x| x.account.name_credential}
field(:account){|x| x.account.one_word }
field(:published_at){|x| x.published_at.strftime('%Y-%m-%d')}
field(:title){|x| truncate(x.title,10) }
field(:excerpt){|x| truncate(x.content,10) }
field(:last_event){|x| x.last_event.as_relative_sentence(x) }
field(:source){|x| x.source ? x.source.account.one_word : '(none)' }
field(:targets, :label => 'target items'){|x| t=x.targets; t.size == 0 ? '(none)' : t.map{|y| y.account.one_word }}
field(:target_accounts) do |x|
if (x.target_accounts.size == 0)
'(none)'
else
x.target_accounts.map{|y| y.account ? y.account.one_word : '(account deleted)' } * ','
end
end
end
end
# @todo below we hard-code svc names just for fun -- to play w/ optparse completion
cli.does(:list, "show some items, maybe do something to them") do
option('-h',&help)
option('-a','--account ID', 'items that are from this account id [and...]')
option('-u','--user EMAIL', 'items that belong to this sosy user [and...]')
option('-s','--service NAME',['wordpress','tumblr'],'items that are from this service [and...]')
option('-n','--name-credential NAME','items that are from the account with this username [and...]')
option('-i','--ids IDS', 'comma-separated list of item ids') do |x|
it.must_match(/^\d+(?:\d+)*$/)
end
optional('COMMAND', 'one day, aggregate actions')
optional('current_user_email','if you are going to do anything destructive')
end
def list(command_name, current_user_email, opts)
command_name = nil if command_name == "" # @todo rack nils
if (command_name && ! current_user_email)
#unless [0,2].include? [current_user_email, command_name].compact.size
argument_error(%{If you indicate a command (#{command_name.inspect})}<<
%{ you must indicate a user (#{current_user_email.inspect})})
end
user = opts.user ? User.first_or_throw(:email => opts.user) : nil
svc = opts.service ? Service.first_or_throw(:name => opts.service) : nil
if (opts.name_credential && (missing = [:service,:user] - opts._table.keys).size > 0)
argument_error(%{To search with name credential you must indicate a #{missing.map{|x| %{#{x}}}*' and a '}.})
end
if opts.name_credential
argument_error("You can't indicate both a name credential and an account id") if opts.account
acct = Account.first_or_throw(:service => svc, :name_credential => opts.name_credential)
elsif opts.account
acct = Account.first_or_throw(:id => opts.account)
else
acct = nil
end
if (acct && user && acct.user != user)
argument_error(%{You can't view items of other users})
end
table = self.class.table
table.show_only :id,:theirs,:user,:account,:published_at,:title,:excerpt,:source,:targets,:target_accounts
table.field[:target_accounts].show if acct # this is just cosmetic :/
items = get_items(table, user, svc, acct)
items[0].last_event
out = cli.out.new :suggested_template => :tables
out.data.user = user
out.data.service = svc
out.data.account = acct
if command_name
sub_out = do_aggregate(items, command_name, current_user_email, opts)
acct.reload if acct
items = get_items(table, user, svc, acct)
out.merge! sub_out
end
table.list = items
out.data.tables = [table]
out
end
def get_items(table, user, svc, acct)
# see #datamapper at 2009-12-28 3:30am for a discussion of how to do this query
items =
if (acct) then acct.items
elsif (svc)
table.field[:service].hide()
if (user)
table.field[:user].hide()
amazing = user.items & svc.items
amazing.map # strange bug when you call amazing.each
else
svc.items
end
elsif (user)
table.field[:user].hide()
user.items
else; Item.all end
items
end
def do_aggregate list, command, current_user_identifier, opts
current_user_obj = current_user(current_user_identifier)
argument_error("Invalid aggregate command: #{command.inspect}") unless ['delete'].include?(command)
out = cli.out.new
if (list.count < 0)
out.messages << "There were no items to #{command}."
else
list.each do |item|
out.messages << delete(item, current_user_obj, nil)
end
end
out
end
cli.does(:delete, "remove the reflection of the item(s)") do
option('-h',&help)
required('item_ids', "comma-separated list of item ids to delete") do |it|
it.must_match(/^\d+(?:,\d+)*$/) unless it.kind_of?(Item)
it
end
required('current_user_email')
end
def delete items, current_user_email, opts
user = current_user current_user_email
case items
when Item: items = [items]
when String: items = items.split(',')
else argument_error("very unexpected class for items: #{items.inspect}")
end
out = cli.out.new # (:on_data_collision => :pluralize)
items.each do |item_identifier|
out.merge! Item.remove(item_identifier, user)
end
out
end
cli.does(:add_target_account, "add to the list of targeted accounts(s)") do
option('-h','--help',&help)
required('item_ids') do |x|
x.must_match(/^\d+(?:,\d+)*$/)
end
required 'account', 'account identifer - either a primary key or "<service name>/<name credential>"'
required 'current_user_email'
end
def add_target_account item_ids, account_identifier, current_user_email, opts
user = current_user current_user_email
acct = Account.first_from_identifier_or_throw account_identifier
items = Item.all(:id => item_ids.split(','))
return cli.out.new("no matching item(s) found for #{item_ids}") unless items.size > 0
out = cli.out.new
items.each do |item|
item.account # @todo
existing_list = item.target_accounts.select{|x| x.account = acct }
if existing_list.size > 0 # existing
argument_error("Account #{acct.one_word} has already been targeted by item #{item.one_word}.")
else
item.target_accounts.new(:account => acct)
item.save
Event.kreate :target_account_added, :from_item => item, :to_account => acct, :by => user
out.puts("Added target #{acct.one_word} to item #{item.one_word}.")
end
end
out
end
cli.does(:remove_target_accounts, "add to the list of targeted accounts(s)") do
option('-h','--help',&help)
required('item_ids'){|x| x.must_match(/^(\d+(?:,\d+)*)$/) }
required 'current_user_email'
end
def remove_target_accounts item_ids, current_user_email, opts
user = current_user current_user_email
items = Item.all(:id => item_ids[0].split(','))
return cli.out.new("no matching item(s) found") if items.size == 0
out = cli.out.new
items.each do |item|
size = item.target_accounts.size
item.account #@todo
if (size == 0)
argument_error("Item #{item.one_word} is already cleared of targets.")
else
rs = item.target_accounts.map{|targeting| targeting.destroy}
num_destroyed = rs.select{|x| x==true}.size
Event.kreate :target_accounts_removed, :from_item => item, :by => user
out.puts("Removed "<<en{np('target',num_destroyed)}.say<<" from item #{item.one_word}.")
end
end
out
end
cli.does(:sync, "sync the list of items to their (first) target account") do
option('-h','--help',&help)
option('-p','--password_credential ARG')
required('item_ids'){|x| x.must_match(/^(\d+(?:,\d+)*)$/) }
required 'current_user_email'
end
def sync item_ids, current_user_email, opts
user = current_user current_user_email
items = Item.all(:id => item_ids[0].split(','))
return cli.out.new("no matching item(s) found") if items.size == 0
out = cli.out.new
items.each do |item|
size = item.target_accounts.size
item.account #@todo
case size
when 0
out.errors << "Item #{item.one_word} has no target accounts."
when 1
svc_name = item.target_accounts[0].account.service.name
if (svc_name != "tumblr")
out.errors << "syncing to #{svc_name} is not yet supported for #{item.one_word}"
end
else
out.errors << "for now, can't target multiple accounts for #{item.one_word}"
end
end
if ! out.valid? then return out end
items.each do |item|
request = {
'command_name' => 'tumblr:push',
'ids' => item.id.to_s,
'tumblr_password' => opts.password_credential
}
sub_out = cli.parent.application.run(request, user && user.email)
if ! sub_out.valid?
return out
else
sub_out.data.local_item_id = item.id
end
out.merge! sub_out
end
out
end
end
end
| {
"content_hash": "d5d47852bdc1acc0c86c32b24bd0c75d",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 123,
"avg_line_length": 38.03560830860534,
"alnum_prop": 0.59026369168357,
"repo_name": "hipe/hipe-socialsync",
"id": "68d6c2a936716827cef4cc4f1ec9680b715e2575",
"size": "12818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/hipe-socialsync/controllers/items.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "140841"
}
],
"symlink_target": ""
} |
from numba import types
from numba.core.types import IterableType, SimpleIterableType, SimpleIteratorType
from numba.extending import (models, register_model, make_attribute_wrapper, )
from collections.abc import MutableMapping
class ConcDictIteratorType(SimpleIteratorType):
def __init__(self, iterable):
self.parent = iterable.parent
self.iterable = iterable
yield_type = iterable.yield_type
name = "iter[{}->{}],{}".format(
iterable.parent, yield_type, iterable.name
)
super(ConcDictIteratorType, self).__init__(name, yield_type)
class ConcDictKeysIterableType(SimpleIterableType):
"""Concurrent Dictionary iterable type for .keys()
"""
def __init__(self, parent):
assert isinstance(parent, ConcurrentDictType)
self.parent = parent
self.yield_type = self.parent.key_type
name = "keys[{}]".format(self.parent.name)
self.name = name
iterator_type = ConcDictIteratorType(self)
super(ConcDictKeysIterableType, self).__init__(name, iterator_type)
class ConcDictItemsIterableType(SimpleIterableType):
"""Concurrent Dictionary iterable type for .items()
"""
def __init__(self, parent):
assert isinstance(parent, ConcurrentDictType)
self.parent = parent
self.yield_type = self.parent.keyvalue_type
name = "items[{}]".format(self.parent.name)
self.name = name
iterator_type = ConcDictIteratorType(self)
super(ConcDictItemsIterableType, self).__init__(name, iterator_type)
class ConcDictValuesIterableType(SimpleIterableType):
"""Concurrent Dictionary iterable type for .values()
"""
def __init__(self, parent):
assert isinstance(parent, ConcurrentDictType)
self.parent = parent
self.yield_type = self.parent.value_type
name = "values[{}]".format(self.parent.name)
self.name = name
iterator_type = ConcDictIteratorType(self)
super(ConcDictValuesIterableType, self).__init__(name, iterator_type)
@register_model(ConcDictItemsIterableType)
@register_model(ConcDictKeysIterableType)
@register_model(ConcDictValuesIterableType)
@register_model(ConcDictIteratorType)
class ConcDictIterModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('parent', fe_type.parent), # reference to the dict
('state', types.voidptr), # iterator state in native code
('meminfo', types.MemInfoPointer(types.voidptr)), # meminfo for allocated iter state
]
super(ConcDictIterModel, self).__init__(dmm, fe_type, members)
class ConcurrentDictType(IterableType):
def __init__(self, keyty, valty):
self.key_type = keyty
self.value_type = valty
self.keyvalue_type = types.Tuple([keyty, valty])
super(ConcurrentDictType, self).__init__(
name='ConcurrentDictType({}, {})'.format(keyty, valty))
@property
def iterator_type(self):
return ConcDictKeysIterableType(self).iterator_type
@register_model(ConcurrentDictType)
class ConcurrentDictModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('data_ptr', types.CPointer(types.uint8)),
('meminfo', types.MemInfoPointer(types.voidptr)),
]
models.StructModel.__init__(self, dmm, fe_type, members)
make_attribute_wrapper(ConcurrentDictType, 'data_ptr', '_data_ptr')
class ConcurrentDict(MutableMapping):
def __new__(cls, dcttype=None, meminfo=None):
return object.__new__(cls)
@classmethod
def empty(cls, key_type, value_type):
return cls(dcttype=ConcurrentDictType(key_type, value_type))
@classmethod
def from_arrays(cls, keys, values):
return cls(dcttype=ConcurrentDictType(keys.dtype, values.dtype))
@classmethod
def fromkeys(cls, keys, value):
return cls(dcttype=ConcurrentDictType(keys.dtype, value))
def __init__(self, **kwargs):
if kwargs:
self._dict_type, self._opaque = self._parse_arg(**kwargs)
else:
self._dict_type = None
@property
def _numba_type_(self):
if self._dict_type is None:
raise TypeError("invalid operation on untyped dictionary")
return self._dict_type
| {
"content_hash": "17515942b60000f619428a5111172328",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 98,
"avg_line_length": 34.68217054263566,
"alnum_prop": 0.6399195350916406,
"repo_name": "IntelLabs/hpat",
"id": "2c598ea6fbe0750bb4e4599dc29b4b8d7b7e5b4e",
"size": "6011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdc/extensions/sdc_hashmap_type.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2045"
},
{
"name": "C",
"bytes": "5555"
},
{
"name": "C++",
"bytes": "306500"
},
{
"name": "CMake",
"bytes": "933"
},
{
"name": "Dockerfile",
"bytes": "4859"
},
{
"name": "Makefile",
"bytes": "517"
},
{
"name": "Python",
"bytes": "1552168"
},
{
"name": "Shell",
"bytes": "4347"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Framework\Module;
class ResourceResolverTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Framework\Module\ResourceResolver
*/
protected $_model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $_moduleReaderMock;
protected function setUp()
{
$this->_moduleReaderMock = $this->getMock('Magento\Framework\Module\Dir\Reader', [], [], '', false);
$this->_model = new \Magento\Framework\Module\ResourceResolver($this->_moduleReaderMock);
}
public function testGetResourceList()
{
$moduleName = 'Module';
$this->_moduleReaderMock->expects(
$this->any()
)->method(
'getModuleDir'
)->will(
$this->returnValueMap(
[
['data', $moduleName, __DIR__ . '/_files/Module/data'],
['sql', $moduleName, __DIR__ . '/_files/Module/sql'],
]
)
);
$expectedResult = ['module_first_setup', 'module_second_setup'];
$this->assertEquals($expectedResult, array_values($this->_model->getResourceList($moduleName)));
}
}
| {
"content_hash": "95184ac16f4a0067f64b6dd8fa09342c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 108,
"avg_line_length": 28.666666666666668,
"alnum_prop": 0.5606312292358804,
"repo_name": "webadvancedservicescom/magento",
"id": "dad630f3dbcafe14003196724646f65c554adbf8",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/tests/unit/testsuite/Magento/Framework/Module/ResourceResolverTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "16380"
},
{
"name": "CSS",
"bytes": "2592299"
},
{
"name": "HTML",
"bytes": "9192193"
},
{
"name": "JavaScript",
"bytes": "2874762"
},
{
"name": "PHP",
"bytes": "41399372"
},
{
"name": "Shell",
"bytes": "3084"
},
{
"name": "VCL",
"bytes": "3547"
},
{
"name": "XSLT",
"bytes": "19817"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3ec951ef44bd4840339004e60197f702",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "1d762d9e216f9d2b0139abbb8dfd1d0e17a42cf8",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Cuviera/Cuviera macroura/ Syn. Cuviera djalonensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'test_helper'
class IfElseTagTest < Minitest::Test
include Liquid
def test_if
assert_template_result(' ',' {% if false %} this text should not go into the output {% endif %} ')
assert_template_result(' this text should go into the output ',
' {% if true %} this text should go into the output {% endif %} ')
assert_template_result(' you rock ?','{% if false %} you suck {% endif %} {% if true %} you rock {% endif %}?')
end
def test_literal_comparisons
assert_template_result(' NO ','{% assign v = false %}{% if v %} YES {% else %} NO {% endif %}')
assert_template_result(' YES ','{% assign v = nil %}{% if v == nil %} YES {% else %} NO {% endif %}')
end
def test_if_else
assert_template_result(' YES ','{% if false %} NO {% else %} YES {% endif %}')
assert_template_result(' YES ','{% if true %} YES {% else %} NO {% endif %}')
assert_template_result(' YES ','{% if "foo" %} YES {% else %} NO {% endif %}')
end
def test_if_boolean
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => true)
end
def test_if_or
assert_template_result(' YES ','{% if a or b %} YES {% endif %}', 'a' => true, 'b' => true)
assert_template_result(' YES ','{% if a or b %} YES {% endif %}', 'a' => true, 'b' => false)
assert_template_result(' YES ','{% if a or b %} YES {% endif %}', 'a' => false, 'b' => true)
assert_template_result('', '{% if a or b %} YES {% endif %}', 'a' => false, 'b' => false)
assert_template_result(' YES ','{% if a or b or c %} YES {% endif %}', 'a' => false, 'b' => false, 'c' => true)
assert_template_result('', '{% if a or b or c %} YES {% endif %}', 'a' => false, 'b' => false, 'c' => false)
end
def test_if_or_with_operators
assert_template_result(' YES ','{% if a == true or b == true %} YES {% endif %}', 'a' => true, 'b' => true)
assert_template_result(' YES ','{% if a == true or b == false %} YES {% endif %}', 'a' => true, 'b' => true)
assert_template_result('','{% if a == false or b == false %} YES {% endif %}', 'a' => true, 'b' => true)
end
def test_comparison_of_strings_containing_and_or_or
awful_markup = "a == 'and' and b == 'or' and c == 'foo and bar' and d == 'bar or baz' and e == 'foo' and foo and bar"
assigns = {'a' => 'and', 'b' => 'or', 'c' => 'foo and bar', 'd' => 'bar or baz', 'e' => 'foo', 'foo' => true, 'bar' => true}
assert_template_result(' YES ',"{% if #{awful_markup} %} YES {% endif %}", assigns)
end
def test_comparison_of_expressions_starting_with_and_or_or
assigns = {'order' => {'items_count' => 0}, 'android' => {'name' => 'Roy'}}
assert_template_result( "YES",
"{% if android.name == 'Roy' %}YES{% endif %}",
assigns)
assert_template_result( "YES",
"{% if order.items_count == 0 %}YES{% endif %}",
assigns)
end
def test_if_and
assert_template_result(' YES ','{% if true and true %} YES {% endif %}')
assert_template_result('','{% if false and true %} YES {% endif %}')
assert_template_result('','{% if false and true %} YES {% endif %}')
end
def test_hash_miss_generates_false
assert_template_result('','{% if foo.bar %} NO {% endif %}', 'foo' => {})
end
def test_if_from_variable
assert_template_result('','{% if var %} NO {% endif %}', 'var' => false)
assert_template_result('','{% if var %} NO {% endif %}', 'var' => nil)
assert_template_result('','{% if foo.bar %} NO {% endif %}', 'foo' => {'bar' => false})
assert_template_result('','{% if foo.bar %} NO {% endif %}', 'foo' => {})
assert_template_result('','{% if foo.bar %} NO {% endif %}', 'foo' => nil)
assert_template_result('','{% if foo.bar %} NO {% endif %}', 'foo' => true)
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => "text")
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => true)
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => 1)
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => {})
assert_template_result(' YES ','{% if var %} YES {% endif %}', 'var' => [])
assert_template_result(' YES ','{% if "foo" %} YES {% endif %}')
assert_template_result(' YES ','{% if foo.bar %} YES {% endif %}', 'foo' => {'bar' => true})
assert_template_result(' YES ','{% if foo.bar %} YES {% endif %}', 'foo' => {'bar' => "text"})
assert_template_result(' YES ','{% if foo.bar %} YES {% endif %}', 'foo' => {'bar' => 1 })
assert_template_result(' YES ','{% if foo.bar %} YES {% endif %}', 'foo' => {'bar' => {} })
assert_template_result(' YES ','{% if foo.bar %} YES {% endif %}', 'foo' => {'bar' => [] })
assert_template_result(' YES ','{% if var %} NO {% else %} YES {% endif %}', 'var' => false)
assert_template_result(' YES ','{% if var %} NO {% else %} YES {% endif %}', 'var' => nil)
assert_template_result(' YES ','{% if var %} YES {% else %} NO {% endif %}', 'var' => true)
assert_template_result(' YES ','{% if "foo" %} YES {% else %} NO {% endif %}', 'var' => "text")
assert_template_result(' YES ','{% if foo.bar %} NO {% else %} YES {% endif %}', 'foo' => {'bar' => false})
assert_template_result(' YES ','{% if foo.bar %} YES {% else %} NO {% endif %}', 'foo' => {'bar' => true})
assert_template_result(' YES ','{% if foo.bar %} YES {% else %} NO {% endif %}', 'foo' => {'bar' => "text"})
assert_template_result(' YES ','{% if foo.bar %} NO {% else %} YES {% endif %}', 'foo' => {'notbar' => true})
assert_template_result(' YES ','{% if foo.bar %} NO {% else %} YES {% endif %}', 'foo' => {})
assert_template_result(' YES ','{% if foo.bar %} NO {% else %} YES {% endif %}', 'notfoo' => {'bar' => true})
end
def test_nested_if
assert_template_result('', '{% if false %}{% if false %} NO {% endif %}{% endif %}')
assert_template_result('', '{% if false %}{% if true %} NO {% endif %}{% endif %}')
assert_template_result('', '{% if true %}{% if false %} NO {% endif %}{% endif %}')
assert_template_result(' YES ', '{% if true %}{% if true %} YES {% endif %}{% endif %}')
assert_template_result(' YES ', '{% if true %}{% if true %} YES {% else %} NO {% endif %}{% else %} NO {% endif %}')
assert_template_result(' YES ', '{% if true %}{% if false %} NO {% else %} YES {% endif %}{% else %} NO {% endif %}')
assert_template_result(' YES ', '{% if false %}{% if true %} NO {% else %} NONO {% endif %}{% else %} YES {% endif %}')
end
def test_comparisons_on_null
assert_template_result('','{% if null < 10 %} NO {% endif %}')
assert_template_result('','{% if null <= 10 %} NO {% endif %}')
assert_template_result('','{% if null >= 10 %} NO {% endif %}')
assert_template_result('','{% if null > 10 %} NO {% endif %}')
assert_template_result('','{% if 10 < null %} NO {% endif %}')
assert_template_result('','{% if 10 <= null %} NO {% endif %}')
assert_template_result('','{% if 10 >= null %} NO {% endif %}')
assert_template_result('','{% if 10 > null %} NO {% endif %}')
end
def test_else_if
assert_template_result('0','{% if 0 == 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}')
assert_template_result('1','{% if 0 != 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}')
assert_template_result('2','{% if 0 != 0 %}0{% elsif 1 != 1%}1{% else %}2{% endif %}')
assert_template_result('elsif','{% if false %}if{% elsif true %}elsif{% endif %}')
end
def test_syntax_error_no_variable
assert_raises(SyntaxError){ assert_template_result('', '{% if jerry == 1 %}')}
end
def test_syntax_error_no_expression
assert_raises(SyntaxError) { assert_template_result('', '{% if %}') }
end
def test_if_with_custom_condition
original_op = Condition.operators['contains']
Condition.operators['contains'] = :[]
assert_template_result('yes', %({% if 'bob' contains 'o' %}yes{% endif %}))
assert_template_result('no', %({% if 'bob' contains 'f' %}yes{% else %}no{% endif %}))
ensure
Condition.operators['contains'] = original_op
end
def test_operators_are_ignored_unless_isolated
original_op = Condition.operators['contains']
Condition.operators['contains'] = :[]
assert_template_result('yes',
%({% if 'gnomeslab-and-or-liquid' contains 'gnomeslab-and-or-liquid' %}yes{% endif %}))
ensure
Condition.operators['contains'] = original_op
end
def test_operators_are_whitelisted
assert_raises(SyntaxError) do
assert_template_result('', %({% if 1 or throw or or 1 %}yes{% endif %}))
end
end
end
| {
"content_hash": "8801d6a939315440d77ec5612c1ed5c5",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 128,
"avg_line_length": 51.662721893491124,
"alnum_prop": 0.5323559729698775,
"repo_name": "sideci-sample/sideci-sample-liquid",
"id": "3e1797e2a1dacb1d750885bc1f85f2c1fbcc7246",
"size": "8731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/integration/tags/if_else_tag_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "269689"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../凋/index.html">
<meta http-equiv=refresh content="0; url='../凋/index.html'">
<h1>Redirecting...</h1>
<a href="../凋/index.html">Click here if you are not redirected.</a>
<script>location='../凋/index.html'</script>
| {
"content_hash": "8c43bd41d046eba7ff30bb6f50a792c9",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 67,
"avg_line_length": 38.5,
"alnum_prop": 0.6785714285714286,
"repo_name": "hochanh/hochanh.github.io",
"id": "9a1826060a16cf613c4efeb19f9d53d7e47332c5",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rtk/v4/2135.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6969"
},
{
"name": "JavaScript",
"bytes": "5041"
}
],
"symlink_target": ""
} |
<script type="text/javascript">
RED.nodes.registerType('mix4',{
category: 'pyo generators',
color: '#a6bbcf',
defaults: {
arg_input1: {value:""},
arg_input2:{value:""},
arg_input3:{value:""},
arg_input4:{value:""},
arg_mul:{value:1},
arg_add:{value:0}
},
inputs:5,
inputLabels: ["input1","input2","input3","input4","mul"],
outputs:1,
outputLabels: ["audio"],
icon: "file.png",
label: function() {
return this.name||"mix4";
}
});
</script>
<script type="text/x-red" data-template-name="mix4">
<div class="form-row">
<label for="node-input-arg_mul">Multiplication</label>
<input type="text" id="node-input-arg_mul"><br/>
<label for="node-input-arg_add">Addition</label>
<input type="text" id="node-input-arg_add"><br/>
</div>
</script>
<script type="text/x-red" data-help-name="mix4">
<p>4 channel mixer</p>
</script> | {
"content_hash": "8aab173ed10a207e6fb20281ba51103c",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 65,
"avg_line_length": 29.4,
"alnum_prop": 0.5296404275996113,
"repo_name": "sinneb/pyo-patcher",
"id": "96eaf0876c62c0b36e3391de9ca84c688fec2e25",
"size": "1029",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nodes/mix4.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "69809"
},
{
"name": "JavaScript",
"bytes": "753860"
},
{
"name": "Python",
"bytes": "14915"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation
/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
/// -> A CharacterMotor and a CharacterController component will be automatically added.
/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class Camera360 : MonoBehaviour {
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
void Update ()
{
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
void Start ()
{
// Make the rigid body not change rotation
if (GetComponent<Rigidbody>())
GetComponent<Rigidbody>().freezeRotation = true;
}
} | {
"content_hash": "850cd1d11a668c074446735f1f020051",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 125,
"avg_line_length": 33.82539682539682,
"alnum_prop": 0.6921633036133271,
"repo_name": "leo92613/Outerspacecomposer",
"id": "4d090f902674620e7eed97a98457dd4c2b56a1d7",
"size": "2131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Space Skybox Part-2/Script/Camera360.cs",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "355947"
},
{
"name": "C#",
"bytes": "1047437"
},
{
"name": "GLSL",
"bytes": "451918"
}
],
"symlink_target": ""
} |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package Bio::EnsEMBL::Production::Pipeline::ProteinFeatures::InterProScan;
use strict;
use warnings;
use base ('Bio::EnsEMBL::Production::Pipeline::Common::Base');
use Path::Tiny qw(tempdir);
sub param_defaults {
my ($self) = @_;
return {
%{$self->SUPER::param_defaults},
'run_interproscan' => 1,
'seq_type' => 'p',
};
}
sub fetch_input {
my ($self) = @_;
my $input_file = $self->param_required('input_file');
$self->throw("File '$input_file' does not exist") if (! -e $input_file);
}
sub run {
my ($self) = @_;
my $input_file = $self->param_required('input_file');
my $seq_type = $self->param_required('seq_type');
my $run_mode = $self->param_required('run_mode');
my $interproscan_exe = $self->param_required('interproscan_exe');
my $applications = $self->param_required('interproscan_applications');
my $run_interproscan = $self->param_required('run_interproscan');
my $scratch_dir = $self->param_required('scratch_dir');
my $outfile_base = "$input_file.$run_mode";
my $outfile_xml = "$outfile_base.xml";
my $outfile_tsv = "$outfile_base.tsv";
if (scalar(@$applications)) {
if ($run_interproscan) {
unlink $outfile_xml if -e $outfile_xml;
unlink $outfile_tsv if -e $outfile_tsv;
my $tempdir = tempdir(DIR => $scratch_dir, CLEANUP => 1);
my $options = "--iprlookup --goterms ";
$options .= "-f TSV, XML -t $seq_type --tempdir $tempdir ";
$options .= '--applications '.join(',', @$applications).' ';
my $input_option = "-i $input_file ";
my $output_option = "--output-file-base $outfile_base ";
if ($run_mode =~ /^(nolookup|local)$/) {
$options .= "--disable-precalc ";
}
my $interpro_cmd = qq($interproscan_exe $options $input_option $output_option);
if ($self->param_is_defined('species')) {
my $dba = $self->get_DBAdaptor('core');
$dba->dbc && $dba->dbc->disconnect_if_idle();
}
$self->dbc and $self->dbc->disconnect_if_idle();
$self->run_cmd($interpro_cmd);
}
if (! -e $outfile_xml) {
$self->throw("Output file '$outfile_xml' was not created");
} elsif (-s $outfile_xml == 0) {
$self->throw("Output file '$outfile_xml' was zero size");
}
$self->param('outfile_xml', $outfile_xml);
$self->param('outfile_tsv', $outfile_tsv);
}
}
sub write_output {
my ($self) = @_;
my $applications = $self->param_required('interproscan_applications');
if (scalar(@$applications)) {
my $output_ids =
{
'outfile_xml' => $self->param('outfile_xml'),
'outfile_tsv' => $self->param('outfile_tsv'),
};
$self->dataflow_output_id($output_ids, 3);
}
}
1;
| {
"content_hash": "2fd18a7a2d1353bd3e2d37418349ae14",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 100,
"avg_line_length": 31.02654867256637,
"alnum_prop": 0.6195094124358242,
"repo_name": "Ensembl/ensembl-production",
"id": "0873bc372b0f831a1c6f625b4b6c98e51b3bd13e",
"size": "3506",
"binary": false,
"copies": "1",
"ref": "refs/heads/release/108",
"path": "modules/Bio/EnsEMBL/Production/Pipeline/ProteinFeatures/InterProScan.pm",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AngelScript",
"bytes": "1412"
},
{
"name": "Perl",
"bytes": "2213925"
},
{
"name": "Python",
"bytes": "85746"
},
{
"name": "Shell",
"bytes": "47944"
}
],
"symlink_target": ""
} |
A discord bot with a queueing system, plus a few other goodies.
This bot was designed to meet the requirements and desires of the Affinity
Coaching Discord group.
[](https://travis-ci.org/ewollesen/zenbot)
## Installation
go get github.com/ewollesen/zenbot/bin/zenbot
## Testing
go test github.com/ewollesen/zenbot/...
## Compilation
go build -o ./zenbot github.com/ewollesen/zenbot/bin/zenbot
## Running
### Discord Application Registration
Before the bot can join your Guild (Server), it needs a bot user token and a client id. So visit [your Discord applications page](https://discordapp.com/developers/applications/me) to get started. There you should:
1. Click "New Application".
1. Give your bot a name.
1. Specify a redirect URL (see More on OAuth Redirect URLs, below).
1. Click "Create a bot user".
1. Make a note of your App's Client Id, and the App Bot User's Token. These will be used later.
### Starting the Bot
$ zenbot -discord.client_id <your app's client id> \
-discord.token "Bot <your app bot user's token>" \
-discord.hostname "localhost" \
-discord.protocol "http"
Notice that we've added "Bot" before the token specified above. When you're ready to create a config file, see the [template](#config-file-template) below.
### Inviting the Bot to Join Your Guild
1. Visit <http://localhost:8080/discord>.
1. Follow the generated OAuth URL.
1. Select the Discord Guild on which you want the bot to run.
1. Dance!
Zenbot should now be visible to your guild. Further configuration options can be found by running the bot with the `--help-all` flag.
### More on OAuth Redirect URLs
Discord bots are authorized to join a Guild via [OAuth](https://discordapp.com/developers/docs/topics/oauth2). They do this by crafting a special URL which, when clicked on by a user authorized to add bots to a Guild, grants the bot authorization to join the Guild.
When Zenbot starts up, it creates a small HTTP server, by default on port 8080. Visiting this server's `/discord` endpoint, eg `http://localhost:8080/discord` will present you with an OAuth link that, when followed, will invite Zenbot to join a Guild for which you have access.
After you have authenticated the bot, Discord will try to redirect you back to the bot. So it's up to you to add a correct OAuth redirection URL (in step 1 under running) that is connected to Zenbot's HTTP server's Discord OAuth redirect endpoint, by default this is http://<your server's name or ip>:8080/discord/oauth/redirect. You can use the `discord.hostname` and `discord.protocol` options to modify the generated URLs to point to reverse proxy if you're using one.
<a name="config-file-template">
## Configuration File Template
</a>
Here's a basic configuration file to get you started. Defaults are commented out:
[main]
# If not specified, will default to in-memory caching and queueing.
# redis_addr =
# redis_db = 0
[discord]
client_id = <your app's client id>
token = Bot <your app bot user's token>
# The hostname used for generated OAuth redirect URLs.
# hostname =
# The protocol for generated OAuth redirect URLs.
# protocol = https
# command_prefix = !
# game = !queue help
# A prefix to use in front of redis keys, if using a redis server.
# redis_keyspace = discord
# Rate limits the enqueue command. Units can be specified as minutes (m),
# hours (h), or seconds (s).
# enqueue_rate_limit = 5m
# A comma separated list of channel ids that zenbot should listen in.
# To find channel ids, turn on debug logging, or use your client's developer
# mode, as detailed here:
# https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-server-ID-
# whitelisted_channels =
[httpapi]
address = :8080
[log]
level = info
You can use a configuration file by specifying the `-flagfile` option to zenbot, eg:
$ zenbot -flagfile ~/.zenbot/config
## License
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| {
"content_hash": "c56fff7607f16e30a8558eed05034481",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 477,
"avg_line_length": 39.483050847457626,
"alnum_prop": 0.7231165486155827,
"repo_name": "ewollesen/zenbot",
"id": "b77e832eb6ac77029f61e07dff848534cc65d87e",
"size": "4669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "157778"
}
],
"symlink_target": ""
} |
#include "BrokerInfo.h"
#include "qpid/amqp_0_10/Codecs.h"
#include "qpid/Exception.h"
#include "qpid/log/Statement.h"
#include "qpid/framing/FieldTable.h"
#include "qpid/framing/FieldValue.h"
#include <iostream>
#include <iterator>
#include <sstream>
namespace qpid {
namespace ha {
namespace {
const std::string SYSTEM_ID="system-id";
const std::string PROTOCOL="protocol";
const std::string HOST_NAME="host-name";
const std::string PORT="port";
const std::string STATUS="status";
}
using types::Uuid;
using types::Variant;
using framing::FieldTable;
BrokerInfo::BrokerInfo() : status(JOINING) {}
BrokerInfo::BrokerInfo(const types::Uuid& id, BrokerStatus s, const Address& a)
: address(a), systemId(id), status(s)
{}
FieldTable BrokerInfo::asFieldTable() const {
Variant::Map m = asMap();
FieldTable ft;
amqp_0_10::translate(m, ft);
return ft;
}
Variant::Map BrokerInfo::asMap() const {
Variant::Map m;
m[SYSTEM_ID] = systemId;
m[PROTOCOL] = address.protocol;
m[HOST_NAME] = address.host;
m[PORT] = address.port;
m[STATUS] = status;
return m;
}
void BrokerInfo::assign(const FieldTable& ft) {
Variant::Map m;
amqp_0_10::translate(ft, m);
assign(m);
}
namespace {
const Variant& get(const Variant::Map& m, const std::string& k) {
Variant::Map::const_iterator i = m.find(k);
if (i == m.end()) throw Exception(
QPID_MSG("Missing field '" << k << "' in broker information"));
return i->second;
}
const Address empty;
}
void BrokerInfo::assign(const Variant::Map& m) {
systemId = get(m, SYSTEM_ID).asUuid();
address = Address(get(m, PROTOCOL).asString(),
get(m, HOST_NAME).asString(),
get(m, PORT).asUint16());
status = BrokerStatus(get(m, STATUS).asUint8());
}
std::ostream& BrokerInfo::printId(std::ostream& o) const {
o << getSystemId().str().substr(0,8);
if (getAddress() != empty) o << "@" << getAddress();
return o;
}
std::ostream& operator<<(std::ostream& o, const BrokerInfo& b) {
return b.printId(o) << "(" << printable(b.getStatus()) << ")";
}
std::ostream& operator<<(std::ostream& o, const BrokerInfo::Set& infos) {
std::ostream_iterator<BrokerInfo> out(o, " ");
copy(infos.begin(), infos.end(), out);
return o;
}
std::ostream& operator<<(std::ostream& o, const BrokerInfo::Map::value_type& v) {
return o << v.second;
}
std::ostream& operator<<(std::ostream& o, const BrokerInfo::Map& infos) {
std::ostream_iterator<BrokerInfo::Map::value_type> out(o, " ");
copy(infos.begin(), infos.end(), out);
return o;
}
}}
| {
"content_hash": "58b3a79304b04e2c8e04289502a82cb3",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 81,
"avg_line_length": 25.93069306930693,
"alnum_prop": 0.639557082856052,
"repo_name": "gregerts/debian-qpid-cpp",
"id": "a13451e1792e91ba6c6fac9a6b89c8f9ad334772",
"size": "3432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qpid/ha/BrokerInfo.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
title: Memberdatabase
date: 2015-09-01
path: /projects/memberdatabase
tags:
- Web
- App
- Angular
tasks:
- Project Management
- Team Work
- Communication
- Design
- Development
- Usability
technologies:
- JavaScript
- Angular
- HTML
- Sass
- MySQL
pattern: shippo
background: rgb(147, 40, 145)
client: Pfadi Allschwil
end: 2016
team: 8
teaser: "The goal of this project was to get rid of an old and bloated piece of software and replace it with a new and efficient solution in order to help the scouts organisation of Allschwil reduce their administrative effort."
hero: hero.png
icon: icon.svg
---
I worked on this project in my second year at the FHNW. Just like in [Monomo](/projects/monomo/) we were working in a team of eight people over the course of a whole school year. This time, however, the client was not internal at the school, but rather an external, real world client. This of course meant some changes to our approach to the project, mainly concerning our communication with the client.
Right from the beginning it was clear that this was going to be an Angular app. Most of our team members had to learn a lot before they could even start developing parts of the product, so initially progress was a little slow. We separated the team into two groups, one of them working on the front end while the other one was working on the back end parts of the system.
Aside from the difficulties in working with Angular we had some initial struggles with understanding all the terminologies that are used in a regular scouts organisation. Because of this we had to spend some additional time with the old application and the client so that we could be sure which parts are still needed and how we could integrate them into the new system.
# Things I've learned
I was responsible for the project management discipline during the first half of the semester. While I've had some courses and the topic it was still the first time that I actually had to apply those learnings in a practical situation. Creating schedules and estimations seemed like a daunting task at the beginning, but once I got confident in my role as project manager, things started to seem a lot more clear.
Being a project leader for the first time lead to experiences in the disciplines of a project manager, but also in dealing with my team mates as both a fellow developer and the manager. I found it easiest to lay out a broad schedule for the project and then divide up the workload to the two groups and let them handle more detailed planning. This worked very well in this project.
# Technologies I've used
In the past I've worked with Angular on smaller sample projects, but never on an actual project. I found the framework surprisingly easy to learn with all its terminologies and best practices. Angular certainly has lots of benefits, but in the end I found React [far easier to work with](/projects/what-the-fuck-should-i-watch-tonight/).
| {
"content_hash": "f41597c03bb409902ccc24842f5b89ab",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 413,
"avg_line_length": 65.84444444444445,
"alnum_prop": 0.7840026999662504,
"repo_name": "RadLikeWhoa/radlikewhoa.github.io",
"id": "db9c9e866bbcc1c06303663e75616b0df293b012",
"size": "2967",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "src/pages/projects/memberdatabase/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "35113"
},
{
"name": "SCSS",
"bytes": "30492"
}
],
"symlink_target": ""
} |
(function(){
'use strict';
class NavbarAdminController {
constructor(authService) {
this.authService = authService;
}
}
angular.module('administracionRemotaApp')
.component('navbaradmin',{
templateUrl:'components/navbaradmin/navbaradmin.html',
controller: NavbarAdminController,
controllerAs: 'vm'
});
})();
| {
"content_hash": "1db0eacfd593ea6cad2d44825ff3bbda",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 58,
"avg_line_length": 21.6875,
"alnum_prop": 0.6887608069164265,
"repo_name": "jdmartinezrios/Admin_Remote_Frontend",
"id": "d0daa3c763b6aac1a5cc366bfd44256a2276dc76",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/navbaradmin/navbaradmin.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9907"
},
{
"name": "HTML",
"bytes": "18781"
},
{
"name": "JavaScript",
"bytes": "60082"
}
],
"symlink_target": ""
} |
class RemoveUserNotNullonTickets < ActiveRecord::Migration
def change
change_column :tickets, :user_id, :integer, :null => true
end
end
| {
"content_hash": "ed0b6941160ff80b62c9cd21447e8856",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 58,
"avg_line_length": 28.2,
"alnum_prop": 0.7588652482269503,
"repo_name": "pccsei/adit",
"id": "eb9ab5fffcb4ddab604e1d75626e290534aa8a65",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20140219015504_remove_user_not_nullon_tickets.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23736"
},
{
"name": "JavaScript",
"bytes": "63992"
},
{
"name": "Python",
"bytes": "69035"
},
{
"name": "Ruby",
"bytes": "1497493"
},
{
"name": "Shell",
"bytes": "198"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Fishcoin</source>
<translation>Sobre Fishcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Fishcoin</b> version</source>
<translation>Versão do <b>Fishcoin</b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este é um programa experimental.
Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php.
Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Fishcoin developers</source>
<translation>Os programadores Fishcoin</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Livro de endereços</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Clique duas vezes para editar o endereço ou o rótulo</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Criar um novo endereço</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copie o endereço selecionado para a área de transferência</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Novo Endereço</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Fishcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Estes são os seus endereços Fishcoin para receber pagamentos. Poderá enviar um endereço diferente para cada remetente para poder identificar os pagamentos.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copiar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar Código &QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Fishcoin address</source>
<translation>Assine uma mensagem para provar que é dono de um endereço Fishcoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Assinar &Mensagem</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Apagar o endereço selecionado da lista</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar os dados no separador actual para um ficheiro</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Fishcoin address</source>
<translation>Verifique a mensagem para assegurar que foi assinada com o endereço Fishcoin especificado</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verificar Mensagem</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>E&liminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Fishcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Estes são os seus endereços Fishcoin para enviar pagamentos. Verifique sempre o valor e a morada de envio antes de enviar moedas.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copiar &Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Enviar &Moedas</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exportar dados do Livro de Endereços</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgulas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Erro ao exportar</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Não foi possível escrever para o ficheiro %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(Sem rótulo)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de Frase-Passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Escreva a frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita a nova frase de segurança</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Escreva a nova frase de seguraça da sua carteira. <br/> Por favor, use uma frase de <b>10 ou mais caracteres aleatórios,</b> ou <b>oito ou mais palavras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desencriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Alterar frase de segurança</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar encriptação da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR FISHCOINS</b>!</source>
<translation>Atenção: Se encriptar a carteira e perder a sua senha irá <b>PERDER TODOS OS SEUS FISHCOINS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Tem a certeza que deseja encriptar a carteira?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenção: A tecla Caps Lock está activa!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Carteira encriptada</translation>
</message>
<message>
<location line="-56"/>
<source>Fishcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fishcoins from being stolen by malware infecting your computer.</source>
<translation>O cliente Fishcoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus fishcoins de serem roubados por programas maliciosos que infectem o seu computador.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>A encriptação da carteira falhou</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>As frases de segurança fornecidas não coincidem.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>O desbloqueio da carteira falhou</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>A desencriptação da carteira falhou</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>A frase de segurança da carteira foi alterada com êxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Assinar &mensagem...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando com a rede...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>Visã&o geral</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar visão geral da carteira</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transações</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Navegar pelo histórico de transações</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Editar a lista de endereços e rótulos</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Mostrar a lista de endereços para receber pagamentos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Fec&har</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sair da aplicação</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Fishcoin</source>
<translation>Mostrar informação sobre Fishcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Sobre &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar informação sobre Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opções...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>E&ncriptar Carteira...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Guardar Carteira...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Mudar &Palavra-passe...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importando blocos do disco...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexando blocos no disco...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Fishcoin address</source>
<translation>Enviar moedas para um endereço fishcoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Fishcoin</source>
<translation>Modificar opções de configuração para fishcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Faça uma cópia de segurança da carteira para outra localização</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Janela de &depuração</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir consola de diagnóstico e depuração</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verificar mensagem...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Fishcoin</source>
<translation>Fishcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Enviar</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Receber</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>E&ndereços</translation>
</message>
<message>
<location line="+22"/>
<source>&About Fishcoin</source>
<translation>&Sobre o Fishcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar / Ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Mostrar ou esconder a Janela principal</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encriptar as chaves privadas que pertencem à sua carteira</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Fishcoin addresses to prove you own them</source>
<translation>Assine mensagens com os seus endereços Fishcoin para provar que os controla</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Fishcoin addresses</source>
<translation>Verifique mensagens para assegurar que foram assinadas com o endereço Fishcoin especificado</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Ficheiro</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>Con&figurações</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>A&juda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de separadores</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[rede de testes]</translation>
</message>
<message>
<location line="+47"/>
<source>Fishcoin client</source>
<translation>Cliente Fishcoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Fishcoin network</source>
<translation><numerusform>%n ligação ativa à rede Fishcoin</numerusform><numerusform>%n ligações ativas à rede Fishcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Nenhum bloco fonto disponível</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Processados %1 dos %2 blocos (estimados) do histórico de transacções.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processados %1 blocos do histórico de transações.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 em atraso</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Último bloco recebido foi gerado há %1 atrás.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transações posteriores poderão não ser imediatamente visíveis.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informação</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Esta transação tem um tamanho superior ao limite máximo. Poderá enviá-la pagando uma taxa de %1, que será entregue ao nó que processar a sua transação e ajudará a suportar a rede. Deseja pagar a taxa?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Atualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirme a taxa de transação</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transação enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transação recebida</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Quantia: %2
Tipo: %3
Endereço: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Manuseamento URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Fishcoin address or malformed URI parameters.</source>
<translation>URI não foi lido correctamente! Isto pode ser causado por um endereço Fishcoin inválido ou por parâmetros URI malformados.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>desbloqueada</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>A carteira está <b>encriptada</b> e atualmente <b>bloqueada</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Fishcoin can no longer continue safely and will quit.</source>
<translation>Ocorreu um erro fatal. O Fishcoin não pode continuar com segurança e irá fechar.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Alerta da Rede</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Rótulo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>O rótulo a ser associado com esta entrada do livro de endereços</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>E&ndereço</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>O endereço associado com esta entrada do livro de endereços. Apenas poderá ser modificado para endereços de saída.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Novo endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Novo endereço de saída</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar endereço de entrada</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar endereço de saída</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Fishcoin address.</source>
<translation>O endereço introduzido "%1" não é um endereço fishcoin válido.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossível desbloquear carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Falha ao gerar nova chave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Fishcoin-Qt</source>
<translation>Fishcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versão</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>opções da linha de comandos</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Opções de UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Definir linguagem, por exemplo "pt_PT" (por defeito: linguagem do sistema)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Iniciar minimizado</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Mostrar animação ao iniciar (por defeito: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opções</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Taxa de transação opcional por KB que ajuda a assegurar que as suas transações serão processadas rapidamente. A maioria das transações tem 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pagar &taxa de transação</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Fishcoin after logging in to the system.</source>
<translation>Começar o Fishcoin automaticamente ao iniciar sessão no sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Fishcoin on system login</source>
<translation>&Começar o Fishcoin ao iniciar o sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Repôr todas as opções.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Repôr Opções</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Rede</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Fishcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abrir a porta do cliente fishcoin automaticamente no seu router. Isto penas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear porta usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Fishcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Ligar à rede Fishcoin através de um proxy SOCKS (p.ex. quando ligar através de Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>Ligar através de proxy SO&CKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP do proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Endereço IP do proxy (p.ex. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Porta:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Porta do proxy (p.ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versão SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versão do proxy SOCKS (p.ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Janela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar para a bandeja e não para a barra de ferramentas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar ao fechar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>Vis&ualização</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Linguagem da interface de utilizador:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Fishcoin.</source>
<translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o Fishcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidade a usar em quantias:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Fishcoin addresses in the transaction list or not.</source>
<translation>Se mostrar, ou não, os endereços Fishcoin na lista de transações.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Mostrar en&dereços na lista de transações</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Aplicar</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>padrão</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirme a reposição de opções</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Algumas opções requerem o reinício do programa para funcionar.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Deseja proceder?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Fishcoin.</source>
<translation>Esta opção entrará em efeito após reiniciar o Fishcoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>O endereço de proxy introduzido é inválido. </translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulário</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Fishcoin network after a connection is established, but this process has not completed yet.</source>
<translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede Fishcoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Não confirmado:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Carteira</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Imaturo:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>O saldo minado ainda não maturou</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transações recentes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>O seu saldo atual</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total de transações ainda não confirmadas, e que não estão contabilizadas ainda no seu saldo actual</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>fora de sincronia</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start fishcoin: click-to-pay handler</source>
<translation>Impossível começar o modo clicar-para-pagar com fishcoin:</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Diálogo de Código QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Requisitar Pagamento</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Rótulo:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensagem:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Salvar Como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Erro ao codificar URI em Código QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>A quantia introduzida é inválida, por favor verifique.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Guardar Código QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imagens PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nome do Cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versão do Cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informação</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Usando versão OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Tempo de início</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de ligações</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Em rede de testes</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadeia de blocos</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Total estimado de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tempo do último bloco</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Opções de linha de comandos</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Fishcoin-Qt help message to get a list with possible Fishcoin command-line options.</source>
<translation>Mostrar a mensagem de ajuda do Fishcoin-Qt para obter uma lista com possíveis opções a usar na linha de comandos.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>Mo&strar</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Data de construção</translation>
</message>
<message>
<location line="-104"/>
<source>Fishcoin - Debug window</source>
<translation>Fishcoin - Janela de depuração</translation>
</message>
<message>
<location line="+25"/>
<source>Fishcoin Core</source>
<translation>Núcleo Fishcoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Ficheiro de registo de depuração</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Fishcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Limpar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Fishcoin RPC console.</source>
<translation>Bem-vindo à consola RPC Fishcoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use as setas para cima e para baixo para navegar no histórico e <b>Ctrl-L</b> para limpar o ecrã.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Digite <b>help</b> para visualizar os comandos disponíveis.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar para múltiplos destinatários de uma vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Adicionar &Destinatário</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remover todos os campos da transação</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Limpar Tudo</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirme ação de envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> para %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirme envio de moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Tem a certeza que deseja enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> e </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>O endereço de destino não é válido, por favor verifique.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>A quantia a pagar deverá ser maior que 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>A quantia excede o seu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Erro: A criação da transacção falhou! </translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formulário</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Qu&antia:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar A:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>O endereço para onde enviar o pagamento (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>Rótu&lo:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Escolher endereço do livro de endereços</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Cole endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Remover este destinatário</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Fishcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduza um endereço Fishcoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Assinaturas - Assinar / Verificar uma Mensagem</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>A&ssinar Mensagem</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>O endereço a utilizar para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Escolher endereço do livro de endereços</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Cole endereço da área de transferência</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Escreva aqui a mensagem que deseja assinar</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Assinatura</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar a assinatura actual para a área de transferência</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Fishcoin address</source>
<translation>Assine uma mensagem para provar que é dono deste endereço Fishcoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Assinar &Mensagem</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Repôr todos os campos de assinatura de mensagem</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpar &Tudo</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verificar Mensagem</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>O endereço utilizado para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Fishcoin address</source>
<translation>Verifique a mensagem para assegurar que foi assinada com o endereço Fishcoin especificado</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verificar &Mensagem</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Repôr todos os campos de verificação de mensagem</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Fishcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduza um endereço Fishcoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Clique "Assinar mensagem" para gerar a assinatura</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Fishcoin signature</source>
<translation>Introduza assinatura Fishcoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>O endereço introduzido é inválido. </translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Por favor verifique o endereço e tente de novo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>O endereço introduzido não refere a chave alguma.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>O desbloqueio da carteira foi cancelado.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>A chave privada para o endereço introduzido não está disponível.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Assinatura de mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensagem assinada.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>A assinatura não pôde ser descodificada.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Por favor verifique a assinatura e tente de novo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>A assinatura não condiz com o conteúdo da mensagem.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verificação da mensagem falhou.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensagem verificada.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Fishcoin developers</source>
<translation>Os programadores Fishcoin</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[rede de testes]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/desligado</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/não confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmações</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Origem</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gerado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>endereço próprio</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>rótulo</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>não aceite</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Taxa de transação</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Valor líquido</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentário</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID da Transação</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Moedas geradas deverão maturar por 120 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, irá mudar o estado para "não aceite" e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informação de depuração</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transação</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadeiro</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ainda não foi transmitida com sucesso</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconhecido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalhes da transação</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta janela mostra uma descrição detalhada da transação</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Desligado (%1 confirmação)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Não confirmada (%1 de %2 confirmações)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmada (%1 confirmação)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n bloco</numerusform><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n blocos</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gerado mas não aceite</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recebido com</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recebido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado para</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagamento ao próprio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/d)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e hora a que esta transação foi recebida.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Endereço de destino da transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantia retirada ou adicionada ao saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todas</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoje</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mês</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mês passado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este ano</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Período...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recebida com</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviada para</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Para si</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minadas</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Outras</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Escreva endereço ou rótulo a procurar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Quantia mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalhes da transação</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar Dados das Transações</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Ficheiro separado por vírgula (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Erro ao exportar</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Impossível escrever para o ficheiro %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Período:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>até</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar Moedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar os dados no separador actual para um ficheiro</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Cópia de Segurança da Carteira</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Dados da Carteira (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Cópia de Segurança Falhou</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Ocorreu um erro ao tentar guardar os dados da carteira na nova localização.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Cópia de Segurança Bem Sucedida</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Os dados da carteira foram salvos com sucesso numa nova localização.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Fishcoin version</source>
<translation>Versão Fishcoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or fishcoind</source>
<translation>Enviar comando para -server ou fishcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Listar comandos</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Obter ajuda para um comando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opções:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: fishcoin.conf)</source>
<translation>Especificar ficheiro de configuração (por defeito: fishcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: fishcoind.pid)</source>
<translation>Especificar ficheiro pid (por defeito: fishcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar pasta de dados</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Escute por ligações em <port> (por defeito: 9333 ou testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manter no máximo <n> ligações a outros nós da rede (por defeito: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Especifique o seu endereço público</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Escutar por ligações JSON-RPC em <port> (por defeito: 9332 ou rede de testes: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceitar comandos da consola e JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr o processo como um daemon e aceitar comandos</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Utilizar a rede de testes - testnet</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=fishcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Fishcoin Alert" admin@foo.com
</source>
<translation>%s, deverá definir rpcpassword no ficheiro de configuração :
%s
É recomendado que use a seguinte palavra-passe aleatória:
rpcuser=fishcoinrpc
rpcpassword=%s
(não precisa recordar esta palavra-passe)
O nome de utilizador e password NÃO DEVEM ser iguais.
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.
Também é recomendado definir alertnotify para que seja alertado sobre problemas;
por exemplo: alertnotify=echo %%s | mail -s "Alerta Fishcoin" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Trancar a endereço específio e sempre escutar nele. Use a notação [anfitrião]:porta para IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Fishcoin is probably already running.</source>
<translation>Impossível trancar a pasta de dados %s. Provavelmente o Fishcoin já está a ser executado.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Erro: Esta transação requer uma taxa de transação mínima de %s devido á sua quantia, complexidade, ou uso de fundos recebidos recentemente! </translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Executar comando quando um alerta relevante for recebido (no comando, %s é substituído pela mensagem)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Definir tamanho máximo de transações de alta-/baixa-prioridade em bytes (por defeito: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Esta é uma versão de pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Atenção: As transações mostradas poderão não estar correctas! Poderá ter que atualizar ou outros nós poderão ter que atualizar.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Fishcoin will not work properly.</source>
<translation>Atenção: Por favor verifique que a data e hora do seu computador estão correctas! Se o seu relógio não estiver certo o Fishcoin não irá funcionar correctamente.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Opções de criação de bloco:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Apenas ligar ao(s) nó(s) especificado(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Cadeia de blocos corrompida detectada</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Deseja reconstruir agora a cadeia de blocos?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Erro ao inicializar a cadeia de blocos</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Erro ao inicializar o ambiente de base de dados da carteira %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Erro ao carregar cadeia de blocos</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Erro ao abrir a cadeia de blocos</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Erro: Pouco espaço em disco!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Erro: Carteira bloqueada, incapaz de criar transação! </translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Erro: erro do sistema:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Falha ao ler info do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Falha ao ler bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Falha ao sincronizar índice do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Falha ao escrever índice do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Falha ao escrever info do bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Falha ao escrever o bloco</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Falha ao escrever info do ficheiro</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Falha ao escrever na base de dados de moedas</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Falha ao escrever índice de transações</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Falha ao escrever histórico de modificações</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Encontrar pares usando procura DNS (por defeito: 1 excepto -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Gerar moedas (por defeito: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Quantos blocos verificar ao começar (por defeito: 288, 0 = todos)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Qual a minúcia na verificação de blocos (0-4, por defeito: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Descritores de ficheiros disponíveis são insuficientes.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Reconstruir a cadeia de blocos dos ficheiros blk000??.dat actuais</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Defina o número de processos para servir as chamadas RPC (por defeito: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verificando blocos...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verificando a carteira...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importar blocos de um ficheiro blk000??.dat externo</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Defina o número de processos de verificação (até 16, 0 = automático, <0 = disponibiliza esse número de núcleos livres, por defeito: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Informação</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Endereço -tor inválido: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Manter índice de transações completo (por defeito: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Armazenamento intermédio de recepção por ligação, <n>*1000 bytes (por defeito: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Armazenamento intermédio de envio por ligação, <n>*1000 bytes (por defeito: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Apenas aceitar cadeia de blocos coincidente com marcas de verificação internas (por defeito: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Apenas ligar a nós na rede <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Produzir informação de depuração extra. Implica todas as outras opções -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Produzir informação de depuração extraordinária</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Preceder informação de depuração com selo temporal</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Fishcoin Wiki for SSL setup instructions)</source>
<translation>Opções SSL: (ver a Wiki Fishcoin para instruções de configuração SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Selecione a versão do proxy socks a usar (4-5, padrão: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar informação de rastreio/depuração para o depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Definir tamanho máximo de um bloco em bytes (por defeito: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Falhou assinatura da transação</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Erro de sistema:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Quantia da transação é muito baixa</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Quantia da transação deverá ser positiva</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transação grande demais</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utilizar proxy para aceder a serviços escondidos Tor (por defeito: mesmo que -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome de utilizador para ligações JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Necessita reconstruir as bases de dados usando -reindex para mudar -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupta, recuperação falhou</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Palavra-passe para ligações JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir ligações JSON-RPC do endereço IP especificado</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comandos para o nó a correr em <ip> (por defeito: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atualize a carteira para o formato mais recente</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Definir o tamanho da memória de chaves para <n> (por defeito: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para ligações JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Chave privada do servidor (por defeito: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifras aceitáveis (por defeito: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Esta mensagem de ajuda</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Ligar através de um proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Carregar endereços...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erro ao carregar wallet.dat: Carteira danificada</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Fishcoin</source>
<translation>Erro ao carregar wallet.dat: A Carteira requer uma versão mais recente do Fishcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Fishcoin to complete</source>
<translation>A Carteira precisou ser reescrita: reinicie o Fishcoin para completar</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Erro ao carregar wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Endereço -proxy inválido: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rede desconhecida especificada em -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Versão desconhecida de proxy -socks requisitada: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Não conseguiu resolver endereço -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Não conseguiu resolver endereço -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Quantia inválida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fundos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Carregar índice de blocos...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Fishcoin is probably already running.</source>
<translation>Incapaz de vincular à porta %s neste computador. Provavelmente o Fishcoin já está a funcionar.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Taxa por KB a adicionar a transações enviadas</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Carregar carteira...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Impossível mudar a carteira para uma versão anterior</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Impossível escrever endereço por defeito</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Reexaminando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Carregamento completo</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Para usar a opção %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Deverá definir rpcpassword=<password> no ficheiro de configuração:
%s
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation>
</message>
</context>
</TS> | {
"content_hash": "94f8216f0cae59617e3542008492f251",
"timestamp": "",
"source": "github",
"line_count": 2938,
"max_line_length": 442,
"avg_line_length": 40.16473791695031,
"alnum_prop": 0.6340547778041422,
"repo_name": "fishcoin/fishcoin",
"id": "1d82aa3329734214c1fb6f8053187bc820232fb9",
"size": "118814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_pt_PT.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "103297"
},
{
"name": "C++",
"bytes": "2522848"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "14696"
},
{
"name": "Objective-C",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69714"
},
{
"name": "Shell",
"bytes": "9702"
},
{
"name": "TypeScript",
"bytes": "5236293"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>C++ Libraries: Class Hierarchy</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script src="http://www.mathjax.org/mathjax/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">C++ Libraries
</div>
<div id="projectbrief">C++ Libraries</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li class="current"><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Friends</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Class Hierarchy</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock">This inheritance list is sorted roughly, but not completely, alphabetically:</div><div class="directory">
<div class="levels">[detail level <span onclick="javascript:toggleLevel(1);">1</span><span onclick="javascript:toggleLevel(2);">2</span>]</div><table class="directory">
<tr id="row_0_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classBogoSort.html" target="_self">BogoSort< T ></a></td><td class="desc"></td></tr>
<tr id="row_1_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classdoublyLinkedList_1_1DoublyLinkedList.html" target="_self">doublyLinkedList::DoublyLinkedList< T ></a></td><td class="desc"></td></tr>
<tr id="row_2_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classmatrix_1_1Matrix.html" target="_self">matrix::Matrix< T ></a></td><td class="desc"><a class="el" href="classmatrix_1_1Matrix.html" title="Matrix class. ">Matrix</a> class </td></tr>
<tr id="row_3_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="structsinglyLinkedList_1_1Node.html" target="_self">singlyLinkedList::Node< T ></a></td><td class="desc"></td></tr>
<tr id="row_4_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="structbinaryTree_1_1Node.html" target="_self">binaryTree::Node< T ></a></td><td class="desc">Binary Tree <a class="el" href="structbinaryTree_1_1Node.html" title="Binary Tree Node. ">Node</a> </td></tr>
<tr id="row_5_"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="structdoublyLinkedList_1_1Node.html" target="_self">doublyLinkedList::Node< T ></a></td><td class="desc"></td></tr>
<tr id="row_6_" class="even"><td class="entry"><img src="ftv2node.png" alt="o" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classsinglyLinkedList_1_1SinglyLinkedList.html" target="_self">singlyLinkedList::SinglyLinkedList< T ></a></td><td class="desc"></td></tr>
<tr id="row_7_"><td class="entry"><img id="arr_7_" src="ftv2mlastnode.png" alt="\" width="16" height="22" onclick="toggleFolder('7_')"/><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classtree_1_1Tree.html" target="_self">tree::Tree</a></td><td class="desc"><a class="el" href="classtree_1_1Tree.html" title="Tree Class: ">Tree</a> Class: </td></tr>
<tr id="row_7_0_" class="even"><td class="entry"><img src="ftv2blank.png" alt=" " width="16" height="22" /><img src="ftv2lastnode.png" alt="\" width="16" height="22" /><img src="ftv2cl.png" alt="C" width="24" height="22" /><a class="el" href="classbinaryTree_1_1BinaryTree.html" target="_self">binaryTree::BinaryTree< T ></a></td><td class="desc">Binary Tree class </td></tr>
</table>
</div><!-- directory -->
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sat Jan 25 2014 16:39:57 for C++ Libraries by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
| {
"content_hash": "5dbb570895f088d37d63eabfb15d9803",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 959,
"avg_line_length": 71.77777777777777,
"alnum_prop": 0.6596808763991426,
"repo_name": "calebwherry/Cpp-Libraries",
"id": "1f0a2bafdb20dc381e3d74f49f21364d2d7adc00",
"size": "8398",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/hierarchy.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "52241"
},
{
"name": "CSS",
"bytes": "26451"
},
{
"name": "JavaScript",
"bytes": "44679"
},
{
"name": "Shell",
"bytes": "2291"
}
],
"symlink_target": ""
} |
import {Injectable, EventEmitter} from 'angular2/angular2'
import {Dispatcher as ChatAppDispatcher} from '../dispatcher/ChatAppDispatcher'
import {ChatConstants} from '../constants/ChatConstants'
import {ChatMessageUtils} from '../utils/ChatMessageUtils'
import {ThreadStore} from './ThreadStore'
import {MessageStore} from './MessageStore'
let ActionTypes = ChatConstants.ActionTypes;
let CHANGE_EVENT = 'change';
// Injectable service
@Injectable()
export class UnreadThreadStore extends EventEmitter<string> {
public dispatchToken: number;
constructor(private chatAppDispatcher: ChatAppDispatcher, private threadStore: ThreadStore, private messageStore: MessageStore) {
super()
this._register();
}
private emitChange() {
// this.emit(CHANGE_EVENT);
this.emit(CHANGE_EVENT)
}
// /**
// * @param {function} callback
// */
// addChangeListener(callback) {
// this.on(CHANGE_EVENT, callback);
// }
// /**
// * @param {function} callback
// */
// removeChangeListener(callback) {
// this.removeListener(CHANGE_EVENT, callback);
// }
getCount() {
var threads = this.threadStore.getAll();
var unreadCount = 0;
for (var id in threads) {
if (!threads[id].lastMessage.isRead) {
unreadCount++;
}
}
return unreadCount;
}
// Register with dispatcher
private _register() {
this.dispatchToken = this.chatAppDispatcher.register(this.onAction.bind(this));
}
// Listen for dispatch events
private onAction(action) {
this.chatAppDispatcher.waitFor([
this.threadStore.dispatchToken,
this.messageStore.dispatchToken
], () => {
switch (action.type) {
case ActionTypes.RECEIVE_MESSAGES:
case ActionTypes.RECEIVE_MESSAGE:
case ActionTypes.CLICK_THREAD:
this.emitChange();
break;
default:
// do nothing
}
});
}
} | {
"content_hash": "a7c5594ffba641b9982d2e7c1067e5c5",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 130,
"avg_line_length": 22.974683544303797,
"alnum_prop": 0.7002754820936639,
"repo_name": "vectorhacker/angular-flux",
"id": "7d4f7eb4230778a901e04b6ac76f2c0db67ba73d",
"size": "1815",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chat/src/app/stores/UnreadThreadStore.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1977"
},
{
"name": "HTML",
"bytes": "769"
},
{
"name": "TypeScript",
"bytes": "21810"
}
],
"symlink_target": ""
} |
/**\file
* The <tt>libdaala</tt> C decoding API.*/
#if !defined(_daala_daaladec_H)
# define _daala_daaladec_H (1)
# include "codec.h"
# if defined(__cplusplus)
extern "C" {
# endif
# if OD_GNUC_PREREQ(4, 0, 0)
# pragma GCC visibility push(default)
# endif
#define OD_DECCTL_SET_BSIZE_BUFFER (7001)
#define OD_DECCTL_SET_FLAGS_BUFFER (7003)
#define OD_DECCTL_SET_MV_BUFFER (7005)
/** Copy the motion compensated reference into a user supplied od_img.
* \param[in] <tt>od_img*</tt>: Pointer to the user supplied od_img.
* Image must be allocated by the caller, and must be the
* same format as the decoder output images. */
#define OD_DECCTL_SET_MC_IMG (7007)
#define OD_DECCTL_GET_ACCOUNTING (7009)
#define OD_DECCTL_SET_ACCOUNTING_ENABLED (7011)
#define OD_DECCTL_SET_DERING_BUFFER (7013)
#define OD_ACCT_FRAME (10)
#define OD_ACCT_MV (11)
typedef struct {
/** x position in units of 4x4 luma blocks for layers 0-3, or vx for
OD_ACCT_MV. Has no meaning for OD_ACCT_FRAME.*/
int16_t x;
/** y position in units of 4x4 luma blocks for layers 0-3, or vy for
OD_ACCT_MV. Has no meaning for OD_ACCT_FRAME.*/
int16_t y;
/** layers (0..NPLANES) for color plane coefficients, or one of
OD_ACCT_FRAME and OD_ACCT_MV. */
unsigned char layer;
/** For layers 0-3, 0 means 4x4, 1, means 8x8, and so on. For OD_ACCT_MV,
it is the motion vector level. Has no meaning for OD_ACCT_FRAME. */
unsigned char level;
/** Integer id in the dictionary. */
unsigned char id;
/** Number of bits in units of 1/8 bit. */
unsigned char bits_q3;
} od_acct_symbol;
/* Max number of entries for symbol types in the dictionary (increase as
necessary). */
#define MAX_SYMBOL_TYPES (256)
/** Dictionary for translating strings into id. */
typedef struct {
char *(str[MAX_SYMBOL_TYPES]);
int nb_str;
} od_accounting_dict;
typedef struct {
/** All recorded symbols decoded. */
od_acct_symbol *syms;
/** Number of symbols actually recorded. */
int nb_syms;
/** Dictionary for translating strings into id. */
od_accounting_dict dict;
} od_accounting;
/**\name Decoder state
The following data structures are opaque, and their contents are not
publicly defined by this API.
Referring to their internals directly is unsupported, and may break without
warning.*/
/*@{*/
/**The decoder context.*/
typedef struct daala_dec_ctx daala_dec_ctx;
/**Setup information.
This contains auxiliary information decoded from the setup header by
daala_decode_header_in() to be passed to daala_decode_alloc().
It can be re-used to initialize any number of decoders, and can be freed
via daala_setup_free() at any time.*/
typedef struct daala_setup_info daala_setup_info;
/*@}*/
/**\defgroup decfuncs Functions for Decoding*/
/*@{*/
/**\name Functions for decoding
* You must link to <tt>libdaalaadec</tt> if you use any of the functions in
* this section.
**/
/*@{*/
/**Parses the header packets from an Ogg Daala stream.
* To use this function:
* - Initialize a daala_info structure using daala_info_init().
* - Initialize a daala_comment structure using daala_comment_init().
* - Initialize a daala_setup_info pointer to NULL.
* - Call this function three times, passing in pointers to the same
* daala_info, daala_comment, and daala_setup_info pointer each time, and
* the three successive header packets.
* \param info The #daala_info structure to fill in.
* This must have been previously initialized with
daala_info_init().
The application may begin using the contents of this structure
after the first header is decoded, though it must continue to
be passed in unmodified on all subsequent calls.
* \param dc The #daala_comment structure to fill in.
This must have been previously initialized with
daala_comment_init().
The application may immediately begin using the contents of this
structure after the second header is decoded, though it must
continue to be passed in on all subsequent calls.
* \param ds A pointer to a daala_setup_info pointer to fill in.
The contents of this pointer must be initialized to <tt>NULL</tt>
on the first call, and the returned value must continue to be
passed in on all subsequent calls.
* \param dp The current header packet to process.
* \return A positive value indicates that a Daala header was successfully
processed and indicates the remaining number of headers to be read.
* \retval 0 The last header was processed and the next packet will
contain video.
* \retval OD_EFAULT One of \a info, \a dc, or \a ds was <tt>NULL</tt>, or
there was a memory allocation failure.
* \retval OD_EBADHEADER \a op was <tt>NULL</tt>, the packet was not the next
header packet in the expected sequence, or the
format fo the header data was invalid.
* \retval OD_EVERSION The packet data was a Daala header, but for a bitstream
version not decodable with this version of
<tt>libdaaladec</tt>.
* \retval OD_ENOTFORMAT The packet was not a Daala header.*/
int daala_decode_header_in(daala_info *info,
daala_comment *dc, daala_setup_info **ds, const daala_packet *dp);
/**Allocates a decoder instance.
* \param info A #daala_info struct filled via daala_decode_header_in().
* \param setup A #daala_setup_info handle returned via
* daala_decode_header_in().
* \return The initialized #daala_dec_ctx handle.
* \retval NULL If the decoding parameters were invalid.*/
daala_dec_ctx *daala_decode_alloc(const daala_info *info,
const daala_setup_info *setup);
/**Releases all storage used for the decoder setup information.
* This should be called after you no longer want to create any decoders for
* a stream whose headers you have parsed with daala_decode_header_in().
* \param setup The setup information to free.
* This can safely be <tt>NULL</tt>.*/
void daala_setup_free(daala_setup_info *setup);
/**Decoder control function.
* This is used to provide advanced control of the decoding process.
* \param dec A #daala_dec_ctx handle.
* \param req The control code to process.
* See \ref decctlcodes "the list of available control codes"
* for details.
* \param buf The parameters for this control code.
* \param buf_sz The size of the parameter buffer.*/
int daala_decode_ctl(daala_dec_ctx *dec,
int req, void *buf, size_t buf_sz);
/**Frees an allocated decoder instance.
* \param dec A #daala_dec_ctx handle.*/
void daala_decode_free(daala_dec_ctx *dec);
/**Retrieves decoded video data frames.
* \param dec A #daala_dec_ctx handle.
* \param img A buffer to receive the decoded image data.
* \param dp An incoming Daala packet.*/
int daala_decode_packet_in(daala_dec_ctx *dec, od_img *img,
const daala_packet *dp);
/*@}*/
/** \defgroup decctlcodes Configuration keys for the decoder ctl interface.
* Decoder CTL settings.
*
* These defines and macros are for altering the behaviour of the decoder
* through the \ref daala_decode_ctl interface.
*
* No keys are currently defined.
*/
/*@}*/
# if OD_GNUC_PREREQ(4, 0, 0)
# pragma GCC visibility pop
# endif
# if defined(__cplusplus)
}
# endif
#endif
| {
"content_hash": "4ad0ca13c2f26372d58bd72fc28d9fa4",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 79,
"avg_line_length": 39.48148148148148,
"alnum_prop": 0.6826588046100242,
"repo_name": "kodabb/daala",
"id": "cfa7ebe06cf355e1697937a85465ba4a962f1b4c",
"size": "8801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/daala/daaladec.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1369400"
},
{
"name": "C++",
"bytes": "12970"
},
{
"name": "HTML",
"bytes": "2415"
},
{
"name": "JavaScript",
"bytes": "119049"
},
{
"name": "Makefile",
"bytes": "14616"
},
{
"name": "Shell",
"bytes": "6348"
}
],
"symlink_target": ""
} |
package com.binacube.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.binacube.GdxGame;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width=GdxGame.WIDTH; // sets window width
config.height=GdxGame.HEIGHT; // sets window height
new LwjglApplication(new GdxGame(), config);
}
}
| {
"content_hash": "bbfb99de2ac1ad0446d53dce1012b57d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 77,
"avg_line_length": 36.357142857142854,
"alnum_prop": 0.7779960707269156,
"repo_name": "iwxfer/mononino",
"id": "7f0c015204bf65cd96c9b22dec62304c983f4b1b",
"size": "509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "desktop/src/com/binacube/desktop/DesktopLauncher.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5055"
}
],
"symlink_target": ""
} |
/**
* On-Deploy Scripts Framework.
*/
@org.osgi.annotation.versioning.Version("1.1.0")
package com.adobe.acs.commons.ondeploy; | {
"content_hash": "4eb4d5c528cc03adb8ebc55528f9f1d5",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 48,
"avg_line_length": 21.5,
"alnum_prop": 0.7286821705426356,
"repo_name": "SachinMali/acs-aem-commons",
"id": "8f630b6254c59df977779d32f97198d3e002470e",
"size": "773",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "bundle/src/main/java/com/adobe/acs/commons/ondeploy/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23257"
},
{
"name": "Groovy",
"bytes": "3122"
},
{
"name": "HTML",
"bytes": "84708"
},
{
"name": "Java",
"bytes": "7126646"
},
{
"name": "JavaScript",
"bytes": "436055"
},
{
"name": "Less",
"bytes": "41808"
},
{
"name": "Rich Text Format",
"bytes": "363"
},
{
"name": "Shell",
"bytes": "354"
}
],
"symlink_target": ""
} |
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from six import python_2_unicode_compatible
@python_2_unicode_compatible
class TModel(models.Model):
name = models.CharField(max_length=200)
test = RelatedObjectsDescriptor()
for_inline = models.ForeignKey(
'self',
models.CASCADE,
null=True,
blank=True,
related_name='inline_test_models'
)
def __str__(self):
return self.name
| {
"content_hash": "8714dbc14643d734e6bb266faf6aa8b1",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 54,
"avg_line_length": 21.08695652173913,
"alnum_prop": 0.6721649484536083,
"repo_name": "yourlabs/django-autocomplete-light",
"id": "a0542873a0610651d52b079d506b5e55631a4bc7",
"size": "485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test_project/select2_generic_m2m/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11205"
},
{
"name": "HTML",
"bytes": "5709"
},
{
"name": "JavaScript",
"bytes": "27379"
},
{
"name": "Python",
"bytes": "210537"
},
{
"name": "Shell",
"bytes": "1950"
}
],
"symlink_target": ""
} |
require 'json'
module Slurper
class Story
attr_accessor :attributes
def initialize(attrs={})
self.attributes = (attrs || {}).symbolize_keys
if attributes[:owned_by].present?
puts "DEPRECATION WARNING: `owned_by` is no longer a supported attribute. Please change to `requested_by`."
attributes[:requested_by] = attributes[:owned_by]
end
end
def to_json
{
name: name,
description: description,
story_type: story_type,
labels: labels,
estimate: estimate,
requested_by_id: requested_by_id
}.reject { |k,v| v.blank? }.to_json
end
def save
(@response = Slurper::Client.create(self)).success?
end
def error_message; @response.body end
def name; attributes[:name] end
def estimate; attributes[:estimate] end
def story_type; attributes[:story_type] end
def description
return nil unless attributes[:description].present?
attributes[:description].split("\n").map(&:strip).join("\n")
end
def labels
return [] unless attributes[:labels].present?
attributes[:labels].split(',').map do |tag|
{name: tag}
end
end
def requested_by
attributes[:requested_by].presence || Slurper::Config.requested_by
end
def requested_by_id
Slurper::User.find_by_name(requested_by).try(:id) if requested_by.present?
end
def valid?
if name.blank?
raise "Name is blank for story:\n#{to_json}"
elsif !requested_by_id
raise "Could not find requester \"#{requested_by}\" in project"
end
end
end
end
| {
"content_hash": "a697a65a2ed851d423807795a5b99978",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 115,
"avg_line_length": 25.151515151515152,
"alnum_prop": 0.613855421686747,
"repo_name": "hashrocket/slurper",
"id": "b6ee8cffa59fcc24db356c2a9c8c769eae420c37",
"size": "1660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/slurper/story.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "18280"
}
],
"symlink_target": ""
} |
/**
*** This is a simple implementation of a Mersenne Twister pseudo-random number generator.
**/
#pragma once
/** STL **/
#include <cstdint>
class MersenneTwister
{
public:
MersenneTwister();
MersenneTwister(uint32_t);
uint32_t operator()() {return get();}
uint32_t get();
private:
uint32_t MT[623];
uint32_t index;
void generateNumbers();
};
| {
"content_hash": "0ec1b858b45ba40e48dcd8ee4efc5378",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 89,
"avg_line_length": 16.782608695652176,
"alnum_prop": 0.6373056994818653,
"repo_name": "AdamKuziemski/toys-n-tools",
"id": "c16b6479e7e853d282d86570ecbdccf5926fd512",
"size": "386",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mersenne_twister/mersenne_twister.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "40489"
}
],
"symlink_target": ""
} |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Handles translation of callees as well as other call-related
* things. Callees are a superset of normal rust values and sometimes
* have different representations. In particular, top-level fn items
* and methods are represented as just a fn ptr and not a full
* closure.
*/
use std::vec;
use back::abi;
use driver::session;
use lib;
use lib::llvm::ValueRef;
use lib::llvm::llvm;
use metadata::csearch;
use middle::trans::base;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::closure;
use middle::trans::common;
use middle::trans::common::*;
use middle::trans::datum::*;
use middle::trans::datum::Datum;
use middle::trans::expr;
use middle::trans::glue;
use middle::trans::inline;
use middle::trans::meth;
use middle::trans::monomorphize;
use middle::trans::type_of;
use middle::ty;
use middle::subst::Subst;
use middle::typeck;
use middle::typeck::coherence::make_substs_for_receiver_types;
use util::ppaux::Repr;
use middle::trans::type_::Type;
use syntax::ast;
use syntax::ast_map;
use syntax::visit;
// Represents a (possibly monomorphized) top-level fn item or method
// item. Note that this is just the fn-ptr and is not a Rust closure
// value (which is a pair).
pub struct FnData {
llfn: ValueRef,
}
pub struct MethodData {
llfn: ValueRef,
llself: ValueRef,
temp_cleanup: Option<ValueRef>,
self_ty: ty::t,
self_mode: ty::SelfMode,
}
pub enum CalleeData {
Closure(Datum),
Fn(FnData),
Method(MethodData)
}
pub struct Callee {
bcx: block,
data: CalleeData
}
pub fn trans(bcx: block, expr: @ast::expr) -> Callee {
let _icx = push_ctxt("trans_callee");
debug!("callee::trans(expr=%s)", expr.repr(bcx.tcx()));
// pick out special kinds of expressions that can be called:
match expr.node {
ast::expr_path(_) => {
return trans_def(bcx, bcx.def(expr.id), expr);
}
_ => {}
}
// any other expressions are closures:
return datum_callee(bcx, expr);
fn datum_callee(bcx: block, expr: @ast::expr) -> Callee {
let DatumBlock {bcx, datum} = expr::trans_to_datum(bcx, expr);
match ty::get(datum.ty).sty {
ty::ty_bare_fn(*) => {
let llval = datum.to_appropriate_llval(bcx);
return Callee {bcx: bcx, data: Fn(FnData {llfn: llval})};
}
ty::ty_closure(*) => {
return Callee {bcx: bcx, data: Closure(datum)};
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
fmt!("Type of callee is neither bare-fn nor closure: %s",
bcx.ty_to_str(datum.ty)));
}
}
}
fn fn_callee(bcx: block, fd: FnData) -> Callee {
return Callee {bcx: bcx, data: Fn(fd)};
}
fn trans_def(bcx: block, def: ast::def, ref_expr: @ast::expr) -> Callee {
match def {
ast::def_fn(did, _) | ast::def_static_method(did, None, _) => {
fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id))
}
ast::def_static_method(impl_did, Some(trait_did), _) => {
fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
trait_did,
ref_expr.id))
}
ast::def_variant(tid, vid) => {
// nullary variants are not callable
assert!(ty::enum_variant_with_id(bcx.tcx(),
tid,
vid).args.len() > 0u);
fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id))
}
ast::def_struct(def_id) => {
fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id))
}
ast::def_arg(*) |
ast::def_local(*) |
ast::def_binding(*) |
ast::def_upvar(*) |
ast::def_self(*) => {
datum_callee(bcx, ref_expr)
}
ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_trait(*) |
ast::def_static(*) | ast::def_ty(*) | ast::def_prim_ty(*) |
ast::def_use(*) | ast::def_typaram_binder(*) |
ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) |
ast::def_self_ty(*) | ast::def_method(*) => {
bcx.tcx().sess.span_bug(
ref_expr.span,
fmt!("Cannot translate def %? \
to a callable thing!", def));
}
}
}
}
pub fn trans_fn_ref_to_callee(bcx: block,
def_id: ast::def_id,
ref_id: ast::node_id) -> Callee {
Callee {bcx: bcx,
data: Fn(trans_fn_ref(bcx, def_id, ref_id))}
}
pub fn trans_fn_ref(bcx: block,
def_id: ast::def_id,
ref_id: ast::node_id) -> FnData {
/*!
*
* Translates a reference (with id `ref_id`) to the fn/method
* with id `def_id` into a function pointer. This may require
* monomorphization or inlining. */
let _icx = push_ctxt("trans_fn_ref");
let type_params = node_id_type_params(bcx, ref_id);
let vtables = node_vtables(bcx, ref_id);
debug!("trans_fn_ref(def_id=%s, ref_id=%?, type_params=%s, vtables=%s)",
def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()),
vtables.repr(bcx.tcx()));
trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables)
}
pub fn trans_fn_ref_with_vtables_to_callee(
bcx: block,
def_id: ast::def_id,
ref_id: ast::node_id,
type_params: &[ty::t],
vtables: Option<typeck::vtable_res>)
-> Callee {
Callee {bcx: bcx,
data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id,
type_params, vtables))}
}
fn get_impl_resolutions(bcx: block,
impl_id: ast::def_id)
-> typeck::vtable_res {
if impl_id.crate == ast::local_crate {
*bcx.ccx().maps.vtable_map.get(&impl_id.node)
} else {
// XXX: This is a temporary hack to work around not properly
// exporting information about resolutions for impls.
// This doesn't actually work if the trait has param bounds,
// but it does allow us to survive the case when it does not.
let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get();
@vec::from_elem(trait_ref.substs.tps.len(), @~[])
}
}
fn resolve_default_method_vtables(bcx: block,
impl_id: ast::def_id,
method: &ty::Method,
substs: &ty::substs,
impl_vtables: Option<typeck::vtable_res>)
-> typeck::vtable_res {
// Get the vtables that the impl implements the trait at
let trait_vtables = get_impl_resolutions(bcx, impl_id);
// Build up a param_substs that we are going to resolve the
// trait_vtables under.
let param_substs = Some(@param_substs {
tys: copy substs.tps,
self_ty: substs.self_ty,
vtables: impl_vtables,
self_vtable: None
});
let trait_vtables_fixed = resolve_vtables_under_param_substs(
bcx.tcx(), param_substs, trait_vtables);
// Now we pull any vtables for parameters on the actual method.
let num_method_vtables = method.generics.type_param_defs.len();
let method_vtables = match impl_vtables {
Some(vtables) => {
let num_impl_type_parameters =
vtables.len() - num_method_vtables;
vtables.tailn(num_impl_type_parameters).to_owned()
},
None => vec::from_elem(num_method_vtables, @~[])
};
@(*trait_vtables_fixed + method_vtables)
}
pub fn trans_fn_ref_with_vtables(
bcx: block, //
def_id: ast::def_id, // def id of fn
ref_id: ast::node_id, // node id of use of fn; may be zero if N/A
type_params: &[ty::t], // values for fn's ty params
vtables: Option<typeck::vtable_res>)
-> FnData {
//!
//
// Translates a reference to a fn/method item, monomorphizing and
// inlining as it goes.
//
// # Parameters
//
// - `bcx`: the current block where the reference to the fn occurs
// - `def_id`: def id of the fn or method item being referenced
// - `ref_id`: node id of the reference to the fn/method, if applicable.
// This parameter may be zero; but, if so, the resulting value may not
// have the right type, so it must be cast before being used.
// - `type_params`: values for each of the fn/method's type parameters
// - `vtables`: values for each bound on each of the type parameters
let _icx = push_ctxt("trans_fn_ref_with_vtables");
let ccx = bcx.ccx();
let tcx = ccx.tcx;
debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \
type_params=%s, vtables=%s)",
bcx.to_str(),
def_id.repr(bcx.tcx()),
ref_id,
type_params.repr(bcx.tcx()),
vtables.repr(bcx.tcx()));
assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
// Polytype of the function item (may have type params)
let fn_tpt = ty::lookup_item_type(tcx, def_id);
// For simplicity, we want to use the Subst trait when composing
// substitutions for default methods. The subst trait does
// substitutions with regions, though, so we put a dummy self
// region parameter in to keep it from failing. This is a hack.
let substs = ty::substs { self_r: Some(ty::re_empty),
self_ty: None,
tps: /*bad*/ type_params.to_owned() };
// We need to do a bunch of special handling for default methods.
// We need to modify the def_id and our substs in order to monomorphize
// the function.
let (def_id, opt_impl_did, substs, self_vtable, vtables) =
match tcx.provided_method_sources.find(&def_id) {
None => (def_id, None, substs, None, vtables),
Some(source) => {
// There are two relevant substitutions when compiling
// default methods. First, there is the substitution for
// the type parameters of the impl we are using and the
// method we are calling. This substitution is the substs
// argument we already have.
// In order to compile a default method, though, we need
// to consider another substitution: the substitution for
// the type parameters on trait; the impl we are using
// implements the trait at some particular type
// parameters, and we need to substitute for those first.
// So, what we need to do is find this substitution and
// compose it with the one we already have.
let trait_ref = ty::impl_trait_ref(tcx, source.impl_id)
.expect("could not find trait_ref for impl with \
default methods");
let method = ty::method(tcx, source.method_id);
// Get all of the type params for the receiver
let param_defs = method.generics.type_param_defs;
let receiver_substs =
type_params.initn(param_defs.len()).to_owned();
let receiver_vtables = match vtables {
None => @~[],
Some(call_vtables) => {
@call_vtables.initn(param_defs.len()).to_owned()
}
};
let self_vtable =
typeck::vtable_static(source.impl_id, receiver_substs,
receiver_vtables);
// Compute the first substitution
let first_subst = make_substs_for_receiver_types(
tcx, source.impl_id, trait_ref, method);
// And compose them
let new_substs = first_subst.subst(tcx, &substs);
let vtables =
resolve_default_method_vtables(bcx, source.impl_id,
method, &new_substs, vtables);
debug!("trans_fn_with_vtables - default method: \
substs = %s, trait_subst = %s, \
first_subst = %s, new_subst = %s, \
self_vtable = %s, vtables = %s",
substs.repr(tcx), trait_ref.substs.repr(tcx),
first_subst.repr(tcx), new_substs.repr(tcx),
self_vtable.repr(tcx), vtables.repr(tcx));
(source.method_id, Some(source.impl_id),
new_substs, Some(self_vtable), Some(vtables))
}
};
// Check whether this fn has an inlined copy and, if so, redirect
// def_id to the local id of the inlined copy.
let def_id = {
if def_id.crate != ast::local_crate {
let may_translate = opt_impl_did.is_none();
inline::maybe_instantiate_inline(ccx, def_id, may_translate)
} else {
def_id
}
};
// We must monomorphise if the fn has type parameters, is a rust
// intrinsic, or is a default method. In particular, if we see an
// intrinsic that is inlined from a different crate, we want to reemit the
// intrinsic instead of trying to call it in the other crate.
let must_monomorphise;
if type_params.len() > 0 || opt_impl_did.is_some() {
must_monomorphise = true;
} else if def_id.crate == ast::local_crate {
let map_node = session::expect(
ccx.sess,
ccx.tcx.items.find(&def_id.node),
|| fmt!("local item should be in ast map"));
match *map_node {
ast_map::node_foreign_item(_, abis, _, _) => {
must_monomorphise = abis.is_intrinsic()
}
_ => {
must_monomorphise = false;
}
}
} else {
must_monomorphise = false;
}
// Create a monomorphic verison of generic functions
if must_monomorphise {
// Should be either intra-crate or inlined.
assert_eq!(def_id.crate, ast::local_crate);
let (val, must_cast) =
monomorphize::monomorphic_fn(ccx, def_id, &substs,
vtables, self_vtable,
opt_impl_did, Some(ref_id));
let mut val = val;
if must_cast && ref_id != 0 {
// Monotype of the REFERENCE to the function (type params
// are subst'd)
let ref_ty = common::node_id_type(bcx, ref_id);
val = PointerCast(
bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
}
return FnData {llfn: val};
}
// Find the actual function pointer.
let val = {
if def_id.crate == ast::local_crate {
// Internal reference.
get_item_val(ccx, def_id.node)
} else {
// External reference.
trans_external_path(ccx, def_id, fn_tpt.ty)
}
};
return FnData {llfn: val};
}
// ______________________________________________________________________
// Translating calls
pub fn trans_call(in_cx: block,
call_ex: @ast::expr,
f: @ast::expr,
args: CallArgs,
id: ast::node_id,
dest: expr::Dest)
-> block {
let _icx = push_ctxt("trans_call");
trans_call_inner(in_cx,
call_ex.info(),
expr_ty(in_cx, f),
node_id_type(in_cx, id),
|cx| trans(cx, f),
args,
dest,
DontAutorefArg)
}
pub fn trans_method_call(in_cx: block,
call_ex: @ast::expr,
callee_id: ast::node_id,
rcvr: @ast::expr,
args: CallArgs,
dest: expr::Dest)
-> block {
let _icx = push_ctxt("trans_method_call");
debug!("trans_method_call(call_ex=%s, rcvr=%s)",
call_ex.repr(in_cx.tcx()),
rcvr.repr(in_cx.tcx()));
trans_call_inner(
in_cx,
call_ex.info(),
node_id_type(in_cx, callee_id),
expr_ty(in_cx, call_ex),
|cx| {
match cx.ccx().maps.method_map.find_copy(&call_ex.id) {
Some(origin) => {
debug!("origin for %s: %s",
call_ex.repr(in_cx.tcx()),
origin.repr(in_cx.tcx()));
meth::trans_method_callee(cx,
callee_id,
rcvr,
origin)
}
None => {
cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map")
}
}
},
args,
dest,
DontAutorefArg)
}
pub fn trans_lang_call(bcx: block,
did: ast::def_id,
args: &[ValueRef],
dest: expr::Dest)
-> block {
let fty = if did.crate == ast::local_crate {
ty::node_id_to_type(bcx.ccx().tcx, did.node)
} else {
csearch::get_type(bcx.ccx().tcx, did).ty
};
let rty = ty::ty_fn_ret(fty);
callee::trans_call_inner(bcx,
None,
fty,
rty,
|bcx| {
trans_fn_ref_with_vtables_to_callee(bcx,
did,
0,
[],
None)
},
ArgVals(args),
dest,
DontAutorefArg)
}
pub fn trans_lang_call_with_type_params(bcx: block,
did: ast::def_id,
args: &[ValueRef],
type_params: &[ty::t],
dest: expr::Dest)
-> block {
let fty;
if did.crate == ast::local_crate {
fty = ty::node_id_to_type(bcx.tcx(), did.node);
} else {
fty = csearch::get_type(bcx.tcx(), did).ty;
}
let rty = ty::ty_fn_ret(fty);
return callee::trans_call_inner(
bcx, None, fty, rty,
|bcx| {
let callee =
trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
type_params,
None);
let new_llval;
match callee.data {
Fn(fn_data) => {
let substituted = ty::subst_tps(callee.bcx.tcx(),
type_params,
None,
fty);
let llfnty = type_of::type_of(callee.bcx.ccx(),
substituted);
new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty);
}
_ => fail!()
}
Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) }
},
ArgVals(args), dest, DontAutorefArg);
}
pub fn body_contains_ret(body: &ast::blk) -> bool {
let cx = @mut false;
visit::visit_block(body, (cx, visit::mk_vt(@visit::Visitor {
visit_item: |_i, (_cx, _v)| { },
visit_expr: |e: @ast::expr, (cx, v): (@mut bool, visit::vt<@mut bool>)| {
if !*cx {
match e.node {
ast::expr_ret(_) => *cx = true,
_ => visit::visit_expr(e, (cx, v)),
}
}
},
..*visit::default_visitor()
})));
*cx
}
// See [Note-arg-mode]
pub fn trans_call_inner(in_cx: block,
call_info: Option<NodeInfo>,
fn_expr_ty: ty::t,
ret_ty: ty::t,
get_callee: &fn(block) -> Callee,
args: CallArgs,
dest: expr::Dest,
autoref_arg: AutorefArg)
-> block {
do base::with_scope(in_cx, call_info, "call") |cx| {
let ret_in_loop = match args {
ArgExprs(args) => {
args.len() > 0u && match args.last().node {
ast::expr_loop_body(@ast::expr {
node: ast::expr_fn_block(_, ref body),
_
}) => body_contains_ret(body),
_ => false
}
}
_ => false
};
let callee = get_callee(cx);
let mut bcx = callee.bcx;
let ccx = cx.ccx();
let ret_flag = if ret_in_loop {
let flag = alloca(bcx, Type::bool());
Store(bcx, C_bool(false), flag);
Some(flag)
} else {
None
};
let (llfn, llenv) = unsafe {
match callee.data {
Fn(d) => {
(d.llfn, llvm::LLVMGetUndef(Type::opaque_box(ccx).ptr_to().to_ref()))
}
Method(d) => {
// Weird but true: we pass self in the *environment* slot!
(d.llfn, d.llself)
}
Closure(d) => {
// Closures are represented as (llfn, llclosure) pair:
// load the requisite values out.
let pair = d.to_ref_llval(bcx);
let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
let llfn = Load(bcx, llfn);
let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
let llenv = Load(bcx, llenv);
(llfn, llenv)
}
}
};
let llretslot = trans_ret_slot(bcx, fn_expr_ty, dest);
let mut llargs = ~[];
if !ty::type_is_immediate(bcx.tcx(), ret_ty) {
llargs.push(llretslot);
}
llargs.push(llenv);
bcx = trans_args(bcx, args, fn_expr_ty,
ret_flag, autoref_arg, &mut llargs);
// Now that the arguments have finished evaluating, we need to revoke
// the cleanup for the self argument
match callee.data {
Method(d) => {
for d.temp_cleanup.iter().advance |&v| {
revoke_clean(bcx, v);
}
}
_ => {}
}
// Uncomment this to debug calls.
/*
io::println(fmt!("calling: %s", bcx.val_to_str(llfn)));
for llargs.iter().advance |llarg| {
io::println(fmt!("arg: %s", bcx.val_to_str(*llarg)));
}
io::println("---");
*/
// If the block is terminated, then one or more of the args
// has type _|_. Since that means it diverges, the code for
// the call itself is unreachable.
let (llresult, new_bcx) = base::invoke(bcx, llfn, llargs);
bcx = new_bcx;
match dest {
expr::Ignore => {
// drop the value if it is not being saved.
unsafe {
if llvm::LLVMIsUndef(llretslot) != lib::llvm::True {
if ty::type_is_nil(ret_ty) {
// When implementing the for-loop sugar syntax, the
// type of the for-loop is nil, but the function
// it's invoking returns a bool. This is a special
// case to ignore instead of invoking the Store
// below into a scratch pointer of a mismatched
// type.
} else if ty::type_is_immediate(bcx.tcx(), ret_ty) {
let llscratchptr = alloc_ty(bcx, ret_ty);
Store(bcx, llresult, llscratchptr);
bcx = glue::drop_ty(bcx, llscratchptr, ret_ty);
} else {
bcx = glue::drop_ty(bcx, llretslot, ret_ty);
}
}
}
}
expr::SaveIn(lldest) => {
// If this is an immediate, store into the result location.
// (If this was not an immediate, the result will already be
// directly written into the output slot.)
if ty::type_is_immediate(bcx.tcx(), ret_ty) {
Store(bcx, llresult, lldest);
}
}
}
if ty::type_is_bot(ret_ty) {
Unreachable(bcx);
} else if ret_in_loop {
let ret_flag_result = bool_to_i1(bcx, Load(bcx, ret_flag.get()));
bcx = do with_cond(bcx, ret_flag_result) |bcx| {
{
let r = (copy bcx.fcx.loop_ret);
for r.iter().advance |&(flagptr, _)| {
Store(bcx, C_bool(true), flagptr);
Store(bcx, C_bool(false), bcx.fcx.llretptr.get());
}
}
base::cleanup_and_leave(bcx, None, Some(bcx.fcx.llreturn));
Unreachable(bcx);
bcx
}
}
bcx
}
}
pub enum CallArgs<'self> {
ArgExprs(&'self [@ast::expr]),
ArgVals(&'self [ValueRef])
}
pub fn trans_ret_slot(bcx: block, fn_ty: ty::t, dest: expr::Dest)
-> ValueRef {
let retty = ty::ty_fn_ret(fn_ty);
match dest {
expr::SaveIn(dst) => dst,
expr::Ignore => {
if ty::type_is_nil(retty) {
unsafe {
llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
}
} else {
alloc_ty(bcx, retty)
}
}
}
}
pub fn trans_args(cx: block,
args: CallArgs,
fn_ty: ty::t,
ret_flag: Option<ValueRef>,
autoref_arg: AutorefArg,
llargs: &mut ~[ValueRef]) -> block
{
let _icx = push_ctxt("trans_args");
let mut temp_cleanups = ~[];
let arg_tys = ty::ty_fn_args(fn_ty);
let mut bcx = cx;
// First we figure out the caller's view of the types of the arguments.
// This will be needed if this is a generic call, because the callee has
// to cast her view of the arguments to the caller's view.
match args {
ArgExprs(arg_exprs) => {
let last = arg_exprs.len() - 1u;
for arg_exprs.iter().enumerate().advance |(i, arg_expr)| {
let arg_val = unpack_result!(bcx, {
trans_arg_expr(bcx,
arg_tys[i],
ty::ByCopy,
*arg_expr,
&mut temp_cleanups,
if i == last { ret_flag } else { None },
autoref_arg)
});
llargs.push(arg_val);
}
}
ArgVals(vs) => {
llargs.push_all(vs);
}
}
// now that all arguments have been successfully built, we can revoke any
// temporary cleanups, as they are only needed if argument construction
// should fail (for example, cleanup of copy mode args).
for temp_cleanups.iter().advance |c| {
revoke_clean(bcx, *c)
}
bcx
}
pub enum AutorefArg {
DontAutorefArg,
DoAutorefArg
}
// temp_cleanups: cleanups that should run only if failure occurs before the
// call takes place:
pub fn trans_arg_expr(bcx: block,
formal_arg_ty: ty::t,
self_mode: ty::SelfMode,
arg_expr: @ast::expr,
temp_cleanups: &mut ~[ValueRef],
ret_flag: Option<ValueRef>,
autoref_arg: AutorefArg) -> Result {
let _icx = push_ctxt("trans_arg_expr");
let ccx = bcx.ccx();
debug!("trans_arg_expr(formal_arg_ty=(%s), self_mode=%?, arg_expr=%s, \
ret_flag=%?)",
formal_arg_ty.repr(bcx.tcx()),
self_mode,
arg_expr.repr(bcx.tcx()),
ret_flag.map(|v| bcx.val_to_str(*v)));
// translate the arg expr to a datum
let arg_datumblock = match ret_flag {
None => expr::trans_to_datum(bcx, arg_expr),
// If there is a ret_flag, this *must* be a loop body
Some(_) => {
match arg_expr.node {
ast::expr_loop_body(
blk @ @ast::expr {
node: ast::expr_fn_block(ref decl, ref body),
_
}) => {
let scratch_ty = expr_ty(bcx, arg_expr);
let scratch = alloc_ty(bcx, scratch_ty);
let arg_ty = expr_ty(bcx, arg_expr);
let sigil = ty::ty_closure_sigil(arg_ty);
let bcx = closure::trans_expr_fn(
bcx, sigil, decl, body, arg_expr.id,
blk.id, Some(ret_flag), expr::SaveIn(scratch));
DatumBlock {bcx: bcx,
datum: Datum {val: scratch,
ty: scratch_ty,
mode: ByRef(RevokeClean)}}
}
_ => {
bcx.sess().impossible_case(
arg_expr.span, "ret_flag with non-loop-body expr");
}
}
}
};
let arg_datum = arg_datumblock.datum;
let bcx = arg_datumblock.bcx;
debug!(" arg datum: %s", arg_datum.to_str(bcx.ccx()));
let mut val;
if ty::type_is_bot(arg_datum.ty) {
// For values of type _|_, we generate an
// "undef" value, as such a value should never
// be inspected. It's important for the value
// to have type lldestty (the callee's expected type).
let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
unsafe {
val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
}
} else {
// FIXME(#3548) use the adjustments table
match autoref_arg {
DoAutorefArg => {
assert!(!
bcx.ccx().maps.moves_map.contains(&arg_expr.id));
val = arg_datum.to_ref_llval(bcx);
}
DontAutorefArg => {
match self_mode {
ty::ByRef => {
// This assertion should really be valid, but because
// the explicit self code currently passes by-ref, it
// does not hold.
//
//assert !bcx.ccx().maps.moves_map.contains_key(
// &arg_expr.id);
debug!("by ref arg with type %s, storing to scratch",
bcx.ty_to_str(arg_datum.ty));
let scratch = scratch_datum(bcx, arg_datum.ty, false);
arg_datum.store_to_datum(bcx,
arg_expr.id,
INIT,
scratch);
// Technically, ownership of val passes to the callee.
// However, we must cleanup should we fail before the
// callee is actually invoked.
scratch.add_clean(bcx);
temp_cleanups.push(scratch.val);
val = scratch.to_ref_llval(bcx);
}
ty::ByCopy => {
if ty::type_needs_drop(bcx.tcx(), arg_datum.ty) ||
arg_datum.appropriate_mode(bcx.tcx()).is_by_ref() {
debug!("by copy arg with type %s, storing to scratch",
bcx.ty_to_str(arg_datum.ty));
let scratch = scratch_datum(bcx, arg_datum.ty, false);
arg_datum.store_to_datum(bcx,
arg_expr.id,
INIT,
scratch);
// Technically, ownership of val passes to the callee.
// However, we must cleanup should we fail before the
// callee is actually invoked.
scratch.add_clean(bcx);
temp_cleanups.push(scratch.val);
match scratch.appropriate_mode(bcx.tcx()) {
ByValue => val = Load(bcx, scratch.val),
ByRef(_) => val = scratch.val,
}
} else {
debug!("by copy arg with type %s", bcx.ty_to_str(arg_datum.ty));
match arg_datum.mode {
ByRef(_) => val = Load(bcx, arg_datum.val),
ByValue => val = arg_datum.val,
}
}
}
}
}
}
if formal_arg_ty != arg_datum.ty {
// this could happen due to e.g. subtyping
let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, &formal_arg_ty);
debug!("casting actual type (%s) to match formal (%s)",
bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
val = PointerCast(bcx, val, llformal_arg_ty);
}
}
debug!("--- trans_arg_expr passing %s", bcx.val_to_str(val));
return rslt(bcx, val);
}
| {
"content_hash": "19b593cc7baf699152d9435779d564c0",
"timestamp": "",
"source": "github",
"line_count": 944,
"max_line_length": 97,
"avg_line_length": 37.29449152542373,
"alnum_prop": 0.46642617735613245,
"repo_name": "j16r/rust",
"id": "05fe0bed3b6967e7d7a1147a8d8c87dd36f6ae2c",
"size": "35206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/librustc/middle/trans/callee.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "27165"
},
{
"name": "C",
"bytes": "910194"
},
{
"name": "C++",
"bytes": "354040"
},
{
"name": "Emacs Lisp",
"bytes": "20815"
},
{
"name": "JavaScript",
"bytes": "22357"
},
{
"name": "Objective-C",
"bytes": "580"
},
{
"name": "Perl",
"bytes": "173368"
},
{
"name": "Puppet",
"bytes": "5423"
},
{
"name": "Python",
"bytes": "39801"
},
{
"name": "Rust",
"bytes": "9584538"
},
{
"name": "Shell",
"bytes": "10985"
},
{
"name": "VimL",
"bytes": "9199"
},
{
"name": "XSLT",
"bytes": "303"
}
],
"symlink_target": ""
} |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jdtang@google.com (Jonathan Tang)
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "attribute.h"
#include "error.h"
#include "gumbo.h"
#include "insertion_mode.h"
#include "parser.h"
#include "tokenizer.h"
#include "tokenizer_states.h"
#include "utf8.h"
#include "util.h"
#include "vector.h"
#define AVOID_UNUSED_VARIABLE_WARNING(i) (void)(i)
#define GUMBO_STRING(literal) \
{ literal, sizeof(literal) - 1 }
#define TERMINATOR \
{ "", 0 }
typedef char gumbo_tagset[GUMBO_TAG_LAST];
#define TAG(tag) [GUMBO_TAG_##tag] = (1 << GUMBO_NAMESPACE_HTML)
#define TAG_SVG(tag) [GUMBO_TAG_##tag] = (1 << GUMBO_NAMESPACE_SVG)
#define TAG_MATHML(tag) [GUMBO_TAG_##tag] = (1 << GUMBO_NAMESPACE_MATHML)
#define TAGSET_INCLUDES(tagset, namespace, tag) \
(tag < GUMBO_TAG_LAST && tagset[(int) tag] == (1 << (int) namespace))
// selected forward declarations as it is getting hard to find
// an appropriate order
static bool node_html_tag_is(const GumboNode*, GumboTag);
static GumboInsertionMode get_current_template_insertion_mode(
const GumboParser*);
static bool handle_in_template(GumboParser*, GumboToken*);
static void destroy_node(GumboParser*, GumboNode*);
static void* malloc_wrapper(void* unused, size_t size) { return malloc(size); }
static void free_wrapper(void* unused, void* ptr) { free(ptr); }
const GumboOptions kGumboDefaultOptions = {&malloc_wrapper, &free_wrapper, NULL,
8, false, -1, GUMBO_TAG_LAST, GUMBO_NAMESPACE_HTML};
static const GumboStringPiece kDoctypeHtml = GUMBO_STRING("html");
static const GumboStringPiece kPublicIdHtml4_0 =
GUMBO_STRING("-//W3C//DTD HTML 4.0//EN");
static const GumboStringPiece kPublicIdHtml4_01 =
GUMBO_STRING("-//W3C//DTD HTML 4.01//EN");
static const GumboStringPiece kPublicIdXhtml1_0 =
GUMBO_STRING("-//W3C//DTD XHTML 1.0 Strict//EN");
static const GumboStringPiece kPublicIdXhtml1_1 =
GUMBO_STRING("-//W3C//DTD XHTML 1.1//EN");
static const GumboStringPiece kSystemIdRecHtml4_0 =
GUMBO_STRING("http://www.w3.org/TR/REC-html40/strict.dtd");
static const GumboStringPiece kSystemIdHtml4 =
GUMBO_STRING("http://www.w3.org/TR/html4/strict.dtd");
static const GumboStringPiece kSystemIdXhtmlStrict1_1 =
GUMBO_STRING("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
static const GumboStringPiece kSystemIdXhtml1_1 =
GUMBO_STRING("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
static const GumboStringPiece kSystemIdLegacyCompat =
GUMBO_STRING("about:legacy-compat");
// The doctype arrays have an explicit terminator because we want to pass them
// to a helper function, and passing them as a pointer discards sizeof
// information. The SVG arrays are used only by one-off functions, and so loops
// over them use sizeof directly instead of a terminator.
static const GumboStringPiece kQuirksModePublicIdPrefixes[] = {
GUMBO_STRING("+//Silmaril//dtd html Pro v0r11 19970101//"),
GUMBO_STRING("-//AdvaSoft Ltd//DTD HTML 3.0 asWedit + extensions//"),
GUMBO_STRING("-//AS//DTD HTML 3.0 asWedit + extensions//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0 Level 1//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0 Level 2//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0 Strict Level 1//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0 Strict Level 2//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0 Strict//"),
GUMBO_STRING("-//IETF//DTD HTML 2.0//"),
GUMBO_STRING("-//IETF//DTD HTML 2.1E//"),
GUMBO_STRING("-//IETF//DTD HTML 3.0//"),
GUMBO_STRING("-//IETF//DTD HTML 3.2 Final//"),
GUMBO_STRING("-//IETF//DTD HTML 3.2//"),
GUMBO_STRING("-//IETF//DTD HTML 3//"),
GUMBO_STRING("-//IETF//DTD HTML Level 0//"),
GUMBO_STRING("-//IETF//DTD HTML Level 1//"),
GUMBO_STRING("-//IETF//DTD HTML Level 2//"),
GUMBO_STRING("-//IETF//DTD HTML Level 3//"),
GUMBO_STRING("-//IETF//DTD HTML Strict Level 0//"),
GUMBO_STRING("-//IETF//DTD HTML Strict Level 1//"),
GUMBO_STRING("-//IETF//DTD HTML Strict Level 2//"),
GUMBO_STRING("-//IETF//DTD HTML Strict Level 3//"),
GUMBO_STRING("-//IETF//DTD HTML Strict//"),
GUMBO_STRING("-//IETF//DTD HTML//"),
GUMBO_STRING("-//Metrius//DTD Metrius Presentational//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 2.0 HTML Strict//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 2.0 HTML//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 2.0 Tables//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 3.0 HTML Strict//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 3.0 HTML//"),
GUMBO_STRING("-//Microsoft//DTD Internet Explorer 3.0 Tables//"),
GUMBO_STRING("-//Netscape Comm. Corp.//DTD HTML//"),
GUMBO_STRING("-//Netscape Comm. Corp.//DTD Strict HTML//"),
GUMBO_STRING("-//O'Reilly and Associates//DTD HTML 2.0//"),
GUMBO_STRING("-//O'Reilly and Associates//DTD HTML Extended 1.0//"),
GUMBO_STRING("-//O'Reilly and Associates//DTD HTML Extended Relaxed 1.0//"),
GUMBO_STRING(
"-//SoftQuad Software//DTD HoTMetaL PRO 6.0::19990601::)"
"extensions to HTML 4.0//"),
GUMBO_STRING(
"-//SoftQuad//DTD HoTMetaL PRO 4.0::19971010::"
"extensions to HTML 4.0//"),
GUMBO_STRING("-//Spyglass//DTD HTML 2.0 Extended//"),
GUMBO_STRING("-//SQ//DTD HTML 2.0 HoTMetaL + extensions//"),
GUMBO_STRING("-//Sun Microsystems Corp.//DTD HotJava HTML//"),
GUMBO_STRING("-//Sun Microsystems Corp.//DTD HotJava Strict HTML//"),
GUMBO_STRING("-//W3C//DTD HTML 3 1995-03-24//"),
GUMBO_STRING("-//W3C//DTD HTML 3.2 Draft//"),
GUMBO_STRING("-//W3C//DTD HTML 3.2 Final//"),
GUMBO_STRING("-//W3C//DTD HTML 3.2//"),
GUMBO_STRING("-//W3C//DTD HTML 3.2S Draft//"),
GUMBO_STRING("-//W3C//DTD HTML 4.0 Frameset//"),
GUMBO_STRING("-//W3C//DTD HTML 4.0 Transitional//"),
GUMBO_STRING("-//W3C//DTD HTML Experimental 19960712//"),
GUMBO_STRING("-//W3C//DTD HTML Experimental 970421//"),
GUMBO_STRING("-//W3C//DTD W3 HTML//"),
GUMBO_STRING("-//W3O//DTD W3 HTML 3.0//"),
GUMBO_STRING("-//WebTechs//DTD Mozilla HTML 2.0//"),
GUMBO_STRING("-//WebTechs//DTD Mozilla HTML//"), TERMINATOR};
static const GumboStringPiece kQuirksModePublicIdExactMatches[] = {
GUMBO_STRING("-//W3O//DTD W3 HTML Strict 3.0//EN//"),
GUMBO_STRING("-/W3C/DTD HTML 4.0 Transitional/EN"), GUMBO_STRING("HTML"),
TERMINATOR};
static const GumboStringPiece kQuirksModeSystemIdExactMatches[] = {
GUMBO_STRING("http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"),
TERMINATOR};
static const GumboStringPiece kLimitedQuirksPublicIdPrefixes[] = {
GUMBO_STRING("-//W3C//DTD XHTML 1.0 Frameset//"),
GUMBO_STRING("-//W3C//DTD XHTML 1.0 Transitional//"), TERMINATOR};
static const GumboStringPiece kLimitedQuirksRequiresSystemIdPublicIdPrefixes[] =
{GUMBO_STRING("-//W3C//DTD HTML 4.01 Frameset//"),
GUMBO_STRING("-//W3C//DTD HTML 4.01 Transitional//"), TERMINATOR};
// Indexed by GumboNamespaceEnum; keep in sync with that.
static const char* kLegalXmlns[] = {"http://www.w3.org/1999/xhtml",
"http://www.w3.org/2000/svg", "http://www.w3.org/1998/Math/MathML"};
typedef struct _ReplacementEntry {
const GumboStringPiece from;
const GumboStringPiece to;
} ReplacementEntry;
#define REPLACEMENT_ENTRY(from, to) \
{ GUMBO_STRING(from), GUMBO_STRING(to) }
// Static data for SVG attribute replacements.
// https://html.spec.whatwg.org/multipage/syntax.html#creating-and-inserting-nodes
static const ReplacementEntry kSvgAttributeReplacements[] = {
REPLACEMENT_ENTRY("attributename", "attributeName"),
REPLACEMENT_ENTRY("attributetype", "attributeType"),
REPLACEMENT_ENTRY("basefrequency", "baseFrequency"),
REPLACEMENT_ENTRY("baseprofile", "baseProfile"),
REPLACEMENT_ENTRY("calcmode", "calcMode"),
REPLACEMENT_ENTRY("clippathunits", "clipPathUnits"),
// REPLACEMENT_ENTRY("contentscripttype", "contentScriptType"),
// REPLACEMENT_ENTRY("contentstyletype", "contentStyleType"),
REPLACEMENT_ENTRY("diffuseconstant", "diffuseConstant"),
REPLACEMENT_ENTRY("edgemode", "edgeMode"),
// REPLACEMENT_ENTRY("externalresourcesrequired",
// "externalResourcesRequired"),
// REPLACEMENT_ENTRY("filterres", "filterRes"),
REPLACEMENT_ENTRY("filterunits", "filterUnits"),
REPLACEMENT_ENTRY("glyphref", "glyphRef"),
REPLACEMENT_ENTRY("gradienttransform", "gradientTransform"),
REPLACEMENT_ENTRY("gradientunits", "gradientUnits"),
REPLACEMENT_ENTRY("kernelmatrix", "kernelMatrix"),
REPLACEMENT_ENTRY("kernelunitlength", "kernelUnitLength"),
REPLACEMENT_ENTRY("keypoints", "keyPoints"),
REPLACEMENT_ENTRY("keysplines", "keySplines"),
REPLACEMENT_ENTRY("keytimes", "keyTimes"),
REPLACEMENT_ENTRY("lengthadjust", "lengthAdjust"),
REPLACEMENT_ENTRY("limitingconeangle", "limitingConeAngle"),
REPLACEMENT_ENTRY("markerheight", "markerHeight"),
REPLACEMENT_ENTRY("markerunits", "markerUnits"),
REPLACEMENT_ENTRY("markerwidth", "markerWidth"),
REPLACEMENT_ENTRY("maskcontentunits", "maskContentUnits"),
REPLACEMENT_ENTRY("maskunits", "maskUnits"),
REPLACEMENT_ENTRY("numoctaves", "numOctaves"),
REPLACEMENT_ENTRY("pathlength", "pathLength"),
REPLACEMENT_ENTRY("patterncontentunits", "patternContentUnits"),
REPLACEMENT_ENTRY("patterntransform", "patternTransform"),
REPLACEMENT_ENTRY("patternunits", "patternUnits"),
REPLACEMENT_ENTRY("pointsatx", "pointsAtX"),
REPLACEMENT_ENTRY("pointsaty", "pointsAtY"),
REPLACEMENT_ENTRY("pointsatz", "pointsAtZ"),
REPLACEMENT_ENTRY("preservealpha", "preserveAlpha"),
REPLACEMENT_ENTRY("preserveaspectratio", "preserveAspectRatio"),
REPLACEMENT_ENTRY("primitiveunits", "primitiveUnits"),
REPLACEMENT_ENTRY("refx", "refX"), REPLACEMENT_ENTRY("refy", "refY"),
REPLACEMENT_ENTRY("repeatcount", "repeatCount"),
REPLACEMENT_ENTRY("repeatdur", "repeatDur"),
REPLACEMENT_ENTRY("requiredextensions", "requiredExtensions"),
REPLACEMENT_ENTRY("requiredfeatures", "requiredFeatures"),
REPLACEMENT_ENTRY("specularconstant", "specularConstant"),
REPLACEMENT_ENTRY("specularexponent", "specularExponent"),
REPLACEMENT_ENTRY("spreadmethod", "spreadMethod"),
REPLACEMENT_ENTRY("startoffset", "startOffset"),
REPLACEMENT_ENTRY("stddeviation", "stdDeviation"),
REPLACEMENT_ENTRY("stitchtiles", "stitchTiles"),
REPLACEMENT_ENTRY("surfacescale", "surfaceScale"),
REPLACEMENT_ENTRY("systemlanguage", "systemLanguage"),
REPLACEMENT_ENTRY("tablevalues", "tableValues"),
REPLACEMENT_ENTRY("targetx", "targetX"),
REPLACEMENT_ENTRY("targety", "targetY"),
REPLACEMENT_ENTRY("textlength", "textLength"),
REPLACEMENT_ENTRY("viewbox", "viewBox"),
REPLACEMENT_ENTRY("viewtarget", "viewTarget"),
REPLACEMENT_ENTRY("xchannelselector", "xChannelSelector"),
REPLACEMENT_ENTRY("ychannelselector", "yChannelSelector"),
REPLACEMENT_ENTRY("zoomandpan", "zoomAndPan"),
};
static const ReplacementEntry kSvgTagReplacements[] = {
REPLACEMENT_ENTRY("altglyph", "altGlyph"),
REPLACEMENT_ENTRY("altglyphdef", "altGlyphDef"),
REPLACEMENT_ENTRY("altglyphitem", "altGlyphItem"),
REPLACEMENT_ENTRY("animatecolor", "animateColor"),
REPLACEMENT_ENTRY("animatemotion", "animateMotion"),
REPLACEMENT_ENTRY("animatetransform", "animateTransform"),
REPLACEMENT_ENTRY("clippath", "clipPath"),
REPLACEMENT_ENTRY("feblend", "feBlend"),
REPLACEMENT_ENTRY("fecolormatrix", "feColorMatrix"),
REPLACEMENT_ENTRY("fecomponenttransfer", "feComponentTransfer"),
REPLACEMENT_ENTRY("fecomposite", "feComposite"),
REPLACEMENT_ENTRY("feconvolvematrix", "feConvolveMatrix"),
REPLACEMENT_ENTRY("fediffuselighting", "feDiffuseLighting"),
REPLACEMENT_ENTRY("fedisplacementmap", "feDisplacementMap"),
REPLACEMENT_ENTRY("fedistantlight", "feDistantLight"),
REPLACEMENT_ENTRY("feflood", "feFlood"),
REPLACEMENT_ENTRY("fefunca", "feFuncA"),
REPLACEMENT_ENTRY("fefuncb", "feFuncB"),
REPLACEMENT_ENTRY("fefuncg", "feFuncG"),
REPLACEMENT_ENTRY("fefuncr", "feFuncR"),
REPLACEMENT_ENTRY("fegaussianblur", "feGaussianBlur"),
REPLACEMENT_ENTRY("feimage", "feImage"),
REPLACEMENT_ENTRY("femerge", "feMerge"),
REPLACEMENT_ENTRY("femergenode", "feMergeNode"),
REPLACEMENT_ENTRY("femorphology", "feMorphology"),
REPLACEMENT_ENTRY("feoffset", "feOffset"),
REPLACEMENT_ENTRY("fepointlight", "fePointLight"),
REPLACEMENT_ENTRY("fespecularlighting", "feSpecularLighting"),
REPLACEMENT_ENTRY("fespotlight", "feSpotLight"),
REPLACEMENT_ENTRY("fetile", "feTile"),
REPLACEMENT_ENTRY("feturbulence", "feTurbulence"),
REPLACEMENT_ENTRY("foreignobject", "foreignObject"),
REPLACEMENT_ENTRY("glyphref", "glyphRef"),
REPLACEMENT_ENTRY("lineargradient", "linearGradient"),
REPLACEMENT_ENTRY("radialgradient", "radialGradient"),
REPLACEMENT_ENTRY("textpath", "textPath"),
};
typedef struct _NamespacedAttributeReplacement {
const char* from;
const char* local_name;
const GumboAttributeNamespaceEnum attr_namespace;
} NamespacedAttributeReplacement;
static const NamespacedAttributeReplacement kForeignAttributeReplacements[] = {
{"xlink:actuate", "actuate", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:actuate", "actuate", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:href", "href", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:role", "role", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:show", "show", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:title", "title", GUMBO_ATTR_NAMESPACE_XLINK},
{"xlink:type", "type", GUMBO_ATTR_NAMESPACE_XLINK},
{"xml:base", "base", GUMBO_ATTR_NAMESPACE_XML},
{"xml:lang", "lang", GUMBO_ATTR_NAMESPACE_XML},
{"xml:space", "space", GUMBO_ATTR_NAMESPACE_XML},
{"xmlns", "xmlns", GUMBO_ATTR_NAMESPACE_XMLNS},
{"xmlns:xlink", "xlink", GUMBO_ATTR_NAMESPACE_XMLNS},
};
// The "scope marker" for the list of active formatting elements. We use a
// pointer to this as a generic marker element, since the particular element
// scope doesn't matter.
static const GumboNode kActiveFormattingScopeMarker;
// The tag_is and tag_in function use true & false to denote start & end tags,
// but for readability, we define constants for them here.
static const bool kStartTag = true;
static const bool kEndTag = false;
// Because GumboStringPieces are immutable, we can't insert a character directly
// into a text node. Instead, we accumulate all pending characters here and
// flush them out to a text node whenever a new element is inserted.
//
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#insert-a-character
typedef struct _TextNodeBufferState {
// The accumulated text to be inserted into the current text node.
GumboStringBuffer _buffer;
// A pointer to the original text represented by this text node. Note that
// because of foster parenting and other strange DOM manipulations, this may
// include other non-text HTML tags in it; it is defined as the span of
// original text from the first character in this text node to the last
// character in this text node.
const char* _start_original_text;
// The source position of the start of this text node.
GumboSourcePosition _start_position;
// The type of node that will be inserted (TEXT, CDATA, or WHITESPACE).
GumboNodeType _type;
} TextNodeBufferState;
typedef struct GumboInternalParserState {
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#insertion-mode
GumboInsertionMode _insertion_mode;
// Used for run_generic_parsing_algorithm, which needs to switch back to the
// original insertion mode at its conclusion.
GumboInsertionMode _original_insertion_mode;
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#the-stack-of-open-elements
GumboVector /*GumboNode*/ _open_elements;
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#the-list-of-active-formatting-elements
GumboVector /*GumboNode*/ _active_formatting_elements;
// The stack of template insertion modes.
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#the-insertion-mode
GumboVector /*InsertionMode*/ _template_insertion_modes;
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#the-element-pointers
GumboNode* _head_element;
GumboNode* _form_element;
// The element used as fragment context when parsing in fragment mode
GumboNode* _fragment_ctx;
// The flag for when the spec says "Reprocess the current token in..."
bool _reprocess_current_token;
// The flag for "acknowledge the token's self-closing flag".
bool _self_closing_flag_acknowledged;
// The "frameset-ok" flag from the spec.
bool _frameset_ok;
// The flag for "If the next token is a LINE FEED, ignore that token...".
bool _ignore_next_linefeed;
// The flag for "whenever a node would be inserted into the current node, it
// must instead be foster parented". This is used for misnested table
// content, which needs to be handled according to "in body" rules yet foster
// parented outside of the table.
// It would perhaps be more explicit to have this as a parameter to
// handle_in_body and insert_element, but given how special-purpose this is
// and the number of call-sites that would need to take the extra parameter,
// it's easier just to have a state flag.
bool _foster_parent_insertions;
// The accumulated text node buffer state.
TextNodeBufferState _text_node;
// The current token.
GumboToken* _current_token;
// The way that the spec is written, the </body> and </html> tags are *always*
// implicit, because encountering one of those tokens merely switches the
// insertion mode out of "in body". So we have individual state flags for
// those end tags that are then inspected by pop_current_node when the <body>
// and <html> nodes are popped to set the GUMBO_INSERTION_IMPLICIT_END_TAG
// flag appropriately.
bool _closed_body_tag;
bool _closed_html_tag;
} GumboParserState;
static bool token_has_attribute(const GumboToken* token, const char* name) {
assert(token->type == GUMBO_TOKEN_START_TAG);
return gumbo_get_attribute(&token->v.start_tag.attributes, name) != NULL;
}
// Checks if the value of the specified attribute is a case-insensitive match
// for the specified string.
static bool attribute_matches(
const GumboVector* attributes, const char* name, const char* value) {
const GumboAttribute* attr = gumbo_get_attribute(attributes, name);
return attr ? strcasecmp(value, attr->value) == 0 : false;
}
// Checks if the value of the specified attribute is a case-sensitive match
// for the specified string.
static bool attribute_matches_case_sensitive(
const GumboVector* attributes, const char* name, const char* value) {
const GumboAttribute* attr = gumbo_get_attribute(attributes, name);
return attr ? strcmp(value, attr->value) == 0 : false;
}
// Checks if the specified attribute vectors are identical.
static bool all_attributes_match(
const GumboVector* attr1, const GumboVector* attr2) {
unsigned int num_unmatched_attr2_elements = attr2->length;
for (unsigned int i = 0; i < attr1->length; ++i) {
const GumboAttribute* attr = attr1->data[i];
if (attribute_matches_case_sensitive(attr2, attr->name, attr->value)) {
--num_unmatched_attr2_elements;
} else {
return false;
}
}
return num_unmatched_attr2_elements == 0;
}
static void set_frameset_not_ok(GumboParser* parser) {
gumbo_debug("Setting frameset_ok to false.\n");
parser->_parser_state->_frameset_ok = false;
}
static GumboNode* create_node(GumboParser* parser, GumboNodeType type) {
GumboNode* node = gumbo_parser_allocate(parser, sizeof(GumboNode));
node->parent = NULL;
node->index_within_parent = -1;
node->type = type;
node->parse_flags = GUMBO_INSERTION_NORMAL;
return node;
}
static GumboNode* new_document_node(GumboParser* parser) {
GumboNode* document_node = create_node(parser, GUMBO_NODE_DOCUMENT);
document_node->parse_flags = GUMBO_INSERTION_BY_PARSER;
gumbo_vector_init(parser, 1, &document_node->v.document.children);
// Must be initialized explicitly, as there's no guarantee that we'll see a
// doc type token.
GumboDocument* document = &document_node->v.document;
document->has_doctype = false;
document->name = NULL;
document->public_identifier = NULL;
document->system_identifier = NULL;
return document_node;
}
static void output_init(GumboParser* parser) {
GumboOutput* output = gumbo_parser_allocate(parser, sizeof(GumboOutput));
output->root = NULL;
output->document = new_document_node(parser);
parser->_output = output;
gumbo_init_errors(parser);
}
static void parser_state_init(GumboParser* parser) {
GumboParserState* parser_state =
gumbo_parser_allocate(parser, sizeof(GumboParserState));
parser_state->_insertion_mode = GUMBO_INSERTION_MODE_INITIAL;
parser_state->_reprocess_current_token = false;
parser_state->_frameset_ok = true;
parser_state->_ignore_next_linefeed = false;
parser_state->_foster_parent_insertions = false;
parser_state->_text_node._type = GUMBO_NODE_WHITESPACE;
gumbo_string_buffer_init(parser, &parser_state->_text_node._buffer);
gumbo_vector_init(parser, 10, &parser_state->_open_elements);
gumbo_vector_init(parser, 5, &parser_state->_active_formatting_elements);
gumbo_vector_init(parser, 5, &parser_state->_template_insertion_modes);
parser_state->_head_element = NULL;
parser_state->_form_element = NULL;
parser_state->_fragment_ctx = NULL;
parser_state->_current_token = NULL;
parser_state->_closed_body_tag = false;
parser_state->_closed_html_tag = false;
parser->_parser_state = parser_state;
}
static void parser_state_destroy(GumboParser* parser) {
GumboParserState* state = parser->_parser_state;
if (state->_fragment_ctx) {
destroy_node(parser, state->_fragment_ctx);
}
gumbo_vector_destroy(parser, &state->_active_formatting_elements);
gumbo_vector_destroy(parser, &state->_open_elements);
gumbo_vector_destroy(parser, &state->_template_insertion_modes);
gumbo_string_buffer_destroy(parser, &state->_text_node._buffer);
gumbo_parser_deallocate(parser, state);
}
static GumboNode* get_document_node(GumboParser* parser) {
return parser->_output->document;
}
static bool is_fragment_parser(const GumboParser* parser) {
return !!parser->_parser_state->_fragment_ctx;
}
// Returns the node at the bottom of the stack of open elements, or NULL if no
// elements have been added yet.
static GumboNode* get_current_node(GumboParser* parser) {
GumboVector* open_elements = &parser->_parser_state->_open_elements;
if (open_elements->length == 0) {
assert(!parser->_output->root);
return NULL;
}
assert(open_elements->length > 0);
assert(open_elements->data != NULL);
return open_elements->data[open_elements->length - 1];
}
static GumboNode* get_adjusted_current_node(GumboParser* parser) {
GumboParserState* state = parser->_parser_state;
if (state->_open_elements.length == 1 && state->_fragment_ctx) {
return state->_fragment_ctx;
}
return get_current_node(parser);
}
// Returns true if the given needle is in the given array of literal
// GumboStringPieces. If exact_match is true, this requires that they match
// exactly; otherwise, this performs a prefix match to check if any of the
// elements in haystack start with needle. This always performs a
// case-insensitive match.
static bool is_in_static_list(
const char* needle, const GumboStringPiece* haystack, bool exact_match) {
for (unsigned int i = 0; haystack[i].length > 0; ++i) {
if ((exact_match && !strcmp(needle, haystack[i].data)) ||
(!exact_match && !strcasecmp(needle, haystack[i].data))) {
return true;
}
}
return false;
}
static void set_insertion_mode(GumboParser* parser, GumboInsertionMode mode) {
parser->_parser_state->_insertion_mode = mode;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#reset-the-insertion-mode-appropriately
// This is a helper function that returns the appropriate insertion mode instead
// of setting it. Returns GUMBO_INSERTION_MODE_INITIAL as a sentinel value to
// indicate that there is no appropriate insertion mode, and the loop should
// continue.
static GumboInsertionMode get_appropriate_insertion_mode(
const GumboParser* parser, int index) {
const GumboVector* open_elements = &parser->_parser_state->_open_elements;
const GumboNode* node = open_elements->data[index];
const bool is_last = index == 0;
if (is_last && is_fragment_parser(parser)) {
node = parser->_parser_state->_fragment_ctx;
}
assert(node->type == GUMBO_NODE_ELEMENT || node->type == GUMBO_NODE_TEMPLATE);
switch (node->v.element.tag) {
case GUMBO_TAG_SELECT: {
if (is_last) {
return GUMBO_INSERTION_MODE_IN_SELECT;
}
for (int i = index; i > 0; --i) {
const GumboNode* ancestor = open_elements->data[i];
if (node_html_tag_is(ancestor, GUMBO_TAG_TEMPLATE)) {
return GUMBO_INSERTION_MODE_IN_SELECT;
}
if (node_html_tag_is(ancestor, GUMBO_TAG_TABLE)) {
return GUMBO_INSERTION_MODE_IN_SELECT_IN_TABLE;
}
}
return GUMBO_INSERTION_MODE_IN_SELECT;
}
case GUMBO_TAG_TD:
case GUMBO_TAG_TH:
if (!is_last) return GUMBO_INSERTION_MODE_IN_CELL;
break;
case GUMBO_TAG_TR:
return GUMBO_INSERTION_MODE_IN_ROW;
case GUMBO_TAG_TBODY:
case GUMBO_TAG_THEAD:
case GUMBO_TAG_TFOOT:
return GUMBO_INSERTION_MODE_IN_TABLE_BODY;
case GUMBO_TAG_CAPTION:
return GUMBO_INSERTION_MODE_IN_CAPTION;
case GUMBO_TAG_COLGROUP:
return GUMBO_INSERTION_MODE_IN_COLUMN_GROUP;
case GUMBO_TAG_TABLE:
return GUMBO_INSERTION_MODE_IN_TABLE;
case GUMBO_TAG_TEMPLATE:
return get_current_template_insertion_mode(parser);
case GUMBO_TAG_HEAD:
if (!is_last) return GUMBO_INSERTION_MODE_IN_HEAD;
break;
case GUMBO_TAG_BODY:
return GUMBO_INSERTION_MODE_IN_BODY;
case GUMBO_TAG_FRAMESET:
return GUMBO_INSERTION_MODE_IN_FRAMESET;
case GUMBO_TAG_HTML:
return parser->_parser_state->_head_element
? GUMBO_INSERTION_MODE_AFTER_HEAD
: GUMBO_INSERTION_MODE_BEFORE_HEAD;
default:
break;
}
return is_last ? GUMBO_INSERTION_MODE_IN_BODY : GUMBO_INSERTION_MODE_INITIAL;
}
// This performs the actual "reset the insertion mode" loop.
static void reset_insertion_mode_appropriately(GumboParser* parser) {
const GumboVector* open_elements = &parser->_parser_state->_open_elements;
for (int i = open_elements->length; --i >= 0;) {
GumboInsertionMode mode = get_appropriate_insertion_mode(parser, i);
if (mode != GUMBO_INSERTION_MODE_INITIAL) {
set_insertion_mode(parser, mode);
return;
}
}
// Should never get here, because is_last will be set on the last iteration
// and will force GUMBO_INSERTION_MODE_IN_BODY.
assert(0);
}
static GumboError* parser_add_parse_error(
GumboParser* parser, const GumboToken* token) {
gumbo_debug("Adding parse error.\n");
GumboError* error = gumbo_add_error(parser);
if (!error) {
return NULL;
}
error->type = GUMBO_ERR_PARSER;
error->position = token->position;
error->original_text = token->original_text.data;
GumboParserError* extra_data = &error->v.parser;
extra_data->input_type = token->type;
extra_data->input_tag = GUMBO_TAG_UNKNOWN;
if (token->type == GUMBO_TOKEN_START_TAG) {
extra_data->input_tag = token->v.start_tag.tag;
} else if (token->type == GUMBO_TOKEN_END_TAG) {
extra_data->input_tag = token->v.end_tag;
}
GumboParserState* state = parser->_parser_state;
extra_data->parser_state = state->_insertion_mode;
gumbo_vector_init(
parser, state->_open_elements.length, &extra_data->tag_stack);
for (unsigned int i = 0; i < state->_open_elements.length; ++i) {
const GumboNode* node = state->_open_elements.data[i];
assert(
node->type == GUMBO_NODE_ELEMENT || node->type == GUMBO_NODE_TEMPLATE);
gumbo_vector_add(
parser, (void*) node->v.element.tag, &extra_data->tag_stack);
}
return error;
}
// Returns true if the specified token is either a start or end tag (specified
// by is_start) with one of the tag types in the varargs list. Terminate the
// list with GUMBO_TAG_LAST; this functions as a sentinel since no portion of
// the spec references tags that are not in the spec.
static bool tag_in(
const GumboToken* token, bool is_start, const gumbo_tagset tags) {
GumboTag token_tag;
if (is_start && token->type == GUMBO_TOKEN_START_TAG) {
token_tag = token->v.start_tag.tag;
} else if (!is_start && token->type == GUMBO_TOKEN_END_TAG) {
token_tag = token->v.end_tag;
} else {
return false;
}
return (token_tag < GUMBO_TAG_LAST && tags[(int) token_tag] != 0);
}
// Like tag_in, but for the single-tag case.
static bool tag_is(const GumboToken* token, bool is_start, GumboTag tag) {
if (is_start && token->type == GUMBO_TOKEN_START_TAG) {
return token->v.start_tag.tag == tag;
} else if (!is_start && token->type == GUMBO_TOKEN_END_TAG) {
return token->v.end_tag == tag;
} else {
return false;
}
}
// Like tag_in, but checks for the tag of a node, rather than a token.
static bool node_tag_in_set(const GumboNode* node, const gumbo_tagset tags) {
assert(node != NULL);
if (node->type != GUMBO_NODE_ELEMENT && node->type != GUMBO_NODE_TEMPLATE) {
return false;
}
return TAGSET_INCLUDES(
tags, node->v.element.tag_namespace, node->v.element.tag);
}
// Like node_tag_in, but for the single-tag case.
static bool node_qualified_tag_is(
const GumboNode* node, GumboNamespaceEnum ns, GumboTag tag) {
assert(node);
return (node->type == GUMBO_NODE_ELEMENT ||
node->type == GUMBO_NODE_TEMPLATE) &&
node->v.element.tag == tag && node->v.element.tag_namespace == ns;
}
// Like node_tag_in, but for the single-tag case in the HTML namespace
static bool node_html_tag_is(const GumboNode* node, GumboTag tag) {
return node_qualified_tag_is(node, GUMBO_NAMESPACE_HTML, tag);
}
static void push_template_insertion_mode(
GumboParser* parser, GumboInsertionMode mode) {
gumbo_vector_add(
parser, (void*) mode, &parser->_parser_state->_template_insertion_modes);
}
static void pop_template_insertion_mode(GumboParser* parser) {
gumbo_vector_pop(parser, &parser->_parser_state->_template_insertion_modes);
}
// Returns the current template insertion mode. If the stack of template
// insertion modes is empty, this returns GUMBO_INSERTION_MODE_INITIAL.
static GumboInsertionMode get_current_template_insertion_mode(
const GumboParser* parser) {
GumboVector* template_insertion_modes =
&parser->_parser_state->_template_insertion_modes;
if (template_insertion_modes->length == 0) {
return GUMBO_INSERTION_MODE_INITIAL;
}
return (GumboInsertionMode)
template_insertion_modes->data[(template_insertion_modes->length - 1)];
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#mathml-text-integration-point
static bool is_mathml_integration_point(const GumboNode* node) {
return node_tag_in_set(
node, (gumbo_tagset){TAG_MATHML(MI), TAG_MATHML(MO), TAG_MATHML(MN),
TAG_MATHML(MS), TAG_MATHML(MTEXT)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#html-integration-point
static bool is_html_integration_point(const GumboNode* node) {
return node_tag_in_set(node, (gumbo_tagset){TAG_SVG(FOREIGNOBJECT),
TAG_SVG(DESC), TAG_SVG(TITLE)}) ||
(node_qualified_tag_is(
node, GUMBO_NAMESPACE_MATHML, GUMBO_TAG_ANNOTATION_XML) &&
(attribute_matches(
&node->v.element.attributes, "encoding", "text/html") ||
attribute_matches(&node->v.element.attributes, "encoding",
"application/xhtml+xml")));
}
// This represents a place to insert a node, consisting of a target parent and a
// child index within that parent. If the node should be inserted at the end of
// the parent's child, index will be -1.
typedef struct {
GumboNode* target;
int index;
} InsertionLocation;
InsertionLocation get_appropriate_insertion_location(
GumboParser* parser, GumboNode* override_target) {
InsertionLocation retval = {override_target, -1};
if (retval.target == NULL) {
// No override target; default to the current node, but special-case the
// root node since get_current_node() assumes the stack of open elements is
// non-empty.
retval.target = parser->_output->root != NULL ? get_current_node(parser)
: get_document_node(parser);
}
if (!parser->_parser_state->_foster_parent_insertions ||
!node_tag_in_set(retval.target, (gumbo_tagset){TAG(TABLE), TAG(TBODY),
TAG(TFOOT), TAG(THEAD), TAG(TR)})) {
return retval;
}
// Foster-parenting case.
int last_template_index = -1;
int last_table_index = -1;
GumboVector* open_elements = &parser->_parser_state->_open_elements;
for (unsigned int i = 0; i < open_elements->length; ++i) {
if (node_html_tag_is(open_elements->data[i], GUMBO_TAG_TEMPLATE)) {
last_template_index = i;
}
if (node_html_tag_is(open_elements->data[i], GUMBO_TAG_TABLE)) {
last_table_index = i;
}
}
if (last_template_index != -1 &&
(last_table_index == -1 || last_template_index > last_table_index)) {
retval.target = open_elements->data[last_template_index];
return retval;
}
if (last_table_index == -1) {
retval.target = open_elements->data[0];
return retval;
}
GumboNode* last_table = open_elements->data[last_table_index];
if (last_table->parent != NULL) {
retval.target = last_table->parent;
retval.index = (int)last_table->index_within_parent;
return retval;
}
retval.target = open_elements->data[last_table_index - 1];
return retval;
}
// Appends a node to the end of its parent, setting the "parent" and
// "index_within_parent" fields appropriately.
static void append_node(
GumboParser* parser, GumboNode* parent, GumboNode* node) {
assert(node->parent == NULL);
assert(node->index_within_parent == -1);
GumboVector* children;
if (parent->type == GUMBO_NODE_ELEMENT ||
parent->type == GUMBO_NODE_TEMPLATE) {
children = &parent->v.element.children;
} else {
assert(parent->type == GUMBO_NODE_DOCUMENT);
children = &parent->v.document.children;
}
node->parent = parent;
node->index_within_parent = children->length;
gumbo_vector_add(parser, (void*) node, children);
assert(node->index_within_parent < children->length);
}
// Inserts a node at the specified InsertionLocation, updating the
// "parent" and "index_within_parent" fields of it and all its siblings.
// If the index of the location is -1, this calls append_node.
static void insert_node(
GumboParser* parser, GumboNode* node, InsertionLocation location) {
assert(node->parent == NULL);
assert(node->index_within_parent == -1);
GumboNode* parent = location.target;
int index = location.index;
if (index != -1) {
GumboVector* children = NULL;
if (parent->type == GUMBO_NODE_ELEMENT ||
parent->type == GUMBO_NODE_TEMPLATE) {
children = &parent->v.element.children;
} else if (parent->type == GUMBO_NODE_DOCUMENT) {
children = &parent->v.document.children;
assert(children->length == 0);
} else {
assert(0);
}
assert(index >= 0);
assert((unsigned int) index < children->length);
node->parent = parent;
node->index_within_parent = index;
gumbo_vector_insert_at(parser, (void*) node, index, children);
assert(node->index_within_parent < children->length);
for (unsigned int i = index + 1; i < children->length; ++i) {
GumboNode* sibling = children->data[i];
sibling->index_within_parent = i;
assert(sibling->index_within_parent < children->length);
}
} else {
append_node(parser, parent, node);
}
}
static void maybe_flush_text_node_buffer(GumboParser* parser) {
GumboParserState* state = parser->_parser_state;
TextNodeBufferState* buffer_state = &state->_text_node;
if (buffer_state->_buffer.length == 0) {
return;
}
assert(buffer_state->_type == GUMBO_NODE_WHITESPACE ||
buffer_state->_type == GUMBO_NODE_TEXT ||
buffer_state->_type == GUMBO_NODE_CDATA);
GumboNode* text_node = create_node(parser, buffer_state->_type);
GumboText* text_node_data = &text_node->v.text;
text_node_data->text =
gumbo_string_buffer_to_string(parser, &buffer_state->_buffer);
text_node_data->original_text.data = buffer_state->_start_original_text;
text_node_data->original_text.length =
state->_current_token->original_text.data -
buffer_state->_start_original_text;
text_node_data->start_pos = buffer_state->_start_position;
gumbo_debug("Flushing text node buffer of %.*s.\n",
(int) buffer_state->_buffer.length, buffer_state->_buffer.data);
InsertionLocation location = get_appropriate_insertion_location(parser, NULL);
if (location.target->type == GUMBO_NODE_DOCUMENT) {
// The DOM does not allow Document nodes to have Text children, so per the
// spec, they are dropped on the floor.
destroy_node(parser, text_node);
} else {
insert_node(parser, text_node, location);
}
gumbo_string_buffer_clear(parser, &buffer_state->_buffer);
buffer_state->_type = GUMBO_NODE_WHITESPACE;
assert(buffer_state->_buffer.length == 0);
}
static void record_end_of_element(
GumboToken* current_token, GumboElement* element) {
element->end_pos = current_token->position;
element->original_end_tag = current_token->type == GUMBO_TOKEN_END_TAG
? current_token->original_text
: kGumboEmptyString;
}
static GumboNode* pop_current_node(GumboParser* parser) {
GumboParserState* state = parser->_parser_state;
maybe_flush_text_node_buffer(parser);
if (state->_open_elements.length > 0) {
assert(node_html_tag_is(state->_open_elements.data[0], GUMBO_TAG_HTML));
gumbo_debug("Popping %s node.\n",
gumbo_normalized_tagname(get_current_node(parser)->v.element.tag));
}
GumboNode* current_node = gumbo_vector_pop(parser, &state->_open_elements);
if (!current_node) {
assert(state->_open_elements.length == 0);
return NULL;
}
assert(current_node->type == GUMBO_NODE_ELEMENT ||
current_node->type == GUMBO_NODE_TEMPLATE);
bool is_closed_body_or_html_tag =
(node_html_tag_is(current_node, GUMBO_TAG_BODY) &&
state->_closed_body_tag) ||
(node_html_tag_is(current_node, GUMBO_TAG_HTML) &&
state->_closed_html_tag);
if ((state->_current_token->type != GUMBO_TOKEN_END_TAG ||
!node_html_tag_is(current_node, state->_current_token->v.end_tag)) &&
!is_closed_body_or_html_tag) {
current_node->parse_flags |= GUMBO_INSERTION_IMPLICIT_END_TAG;
}
if (!is_closed_body_or_html_tag) {
record_end_of_element(state->_current_token, ¤t_node->v.element);
}
return current_node;
}
static void append_comment_node(
GumboParser* parser, GumboNode* node, const GumboToken* token) {
maybe_flush_text_node_buffer(parser);
GumboNode* comment = create_node(parser, GUMBO_NODE_COMMENT);
comment->type = GUMBO_NODE_COMMENT;
comment->parse_flags = GUMBO_INSERTION_NORMAL;
comment->v.text.text = token->v.text;
comment->v.text.original_text = token->original_text;
comment->v.text.start_pos = token->position;
append_node(parser, node, comment);
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#clear-the-stack-back-to-a-table-row-context
static void clear_stack_to_table_row_context(GumboParser* parser) {
while (!node_tag_in_set(get_current_node(parser),
(gumbo_tagset){TAG(HTML), TAG(TR), TAG(TEMPLATE)})) {
pop_current_node(parser);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#clear-the-stack-back-to-a-table-context
static void clear_stack_to_table_context(GumboParser* parser) {
while (!node_tag_in_set(get_current_node(parser),
(gumbo_tagset){TAG(HTML), TAG(TABLE), TAG(TEMPLATE)})) {
pop_current_node(parser);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#clear-the-stack-back-to-a-table-body-context
void clear_stack_to_table_body_context(GumboParser* parser) {
while (!node_tag_in_set(get_current_node(parser),
(gumbo_tagset){TAG(HTML), TAG(TBODY), TAG(TFOOT), TAG(THEAD),
TAG(TEMPLATE)})) {
pop_current_node(parser);
}
}
// Creates a parser-inserted element in the HTML namespace and returns it.
static GumboNode* create_element(GumboParser* parser, GumboTag tag) {
GumboNode* node = create_node(parser, GUMBO_NODE_ELEMENT);
GumboElement* element = &node->v.element;
gumbo_vector_init(parser, 1, &element->children);
gumbo_vector_init(parser, 0, &element->attributes);
element->tag = tag;
element->tag_namespace = GUMBO_NAMESPACE_HTML;
element->original_tag = kGumboEmptyString;
element->original_end_tag = kGumboEmptyString;
element->start_pos = (parser->_parser_state->_current_token)
? parser->_parser_state->_current_token->position
: kGumboEmptySourcePosition;
element->end_pos = kGumboEmptySourcePosition;
return node;
}
// Constructs an element from the given start tag token.
static GumboNode* create_element_from_token(
GumboParser* parser, GumboToken* token, GumboNamespaceEnum tag_namespace) {
assert(token->type == GUMBO_TOKEN_START_TAG);
GumboTokenStartTag* start_tag = &token->v.start_tag;
GumboNodeType type = (tag_namespace == GUMBO_NAMESPACE_HTML &&
start_tag->tag == GUMBO_TAG_TEMPLATE)
? GUMBO_NODE_TEMPLATE
: GUMBO_NODE_ELEMENT;
GumboNode* node = create_node(parser, type);
GumboElement* element = &node->v.element;
gumbo_vector_init(parser, 1, &element->children);
element->attributes = start_tag->attributes;
element->tag = start_tag->tag;
element->tag_namespace = tag_namespace;
assert(token->original_text.length >= 2);
assert(token->original_text.data[0] == '<');
assert(token->original_text.data[token->original_text.length - 1] == '>');
element->original_tag = token->original_text;
element->start_pos = token->position;
element->original_end_tag = kGumboEmptyString;
element->end_pos = kGumboEmptySourcePosition;
// The element takes ownership of the attributes from the token, so any
// allocated-memory fields should be nulled out.
start_tag->attributes = kGumboEmptyVector;
return node;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#insert-an-html-element
static void insert_element(GumboParser* parser, GumboNode* node,
bool is_reconstructing_formatting_elements) {
GumboParserState* state = parser->_parser_state;
// NOTE(jdtang): The text node buffer must always be flushed before inserting
// a node, otherwise we're handling nodes in a different order than the spec
// mandated. However, one clause of the spec (character tokens in the body)
// requires that we reconstruct the active formatting elements *before* adding
// the character, and reconstructing the active formatting elements may itself
// result in the insertion of new elements (which should be pushed onto the
// stack of open elements before the buffer is flushed). We solve this (for
// the time being, the spec has been rewritten for <template> and the new
// version may be simpler here) with a boolean flag to this method.
if (!is_reconstructing_formatting_elements) {
maybe_flush_text_node_buffer(parser);
}
InsertionLocation location = get_appropriate_insertion_location(parser, NULL);
insert_node(parser, node, location);
gumbo_vector_add(parser, (void*) node, &state->_open_elements);
}
// Convenience method that combines create_element_from_token and
// insert_element, inserting the generated element directly into the current
// node. Returns the node inserted.
static GumboNode* insert_element_from_token(
GumboParser* parser, GumboToken* token) {
GumboNode* element =
create_element_from_token(parser, token, GUMBO_NAMESPACE_HTML);
insert_element(parser, element, false);
gumbo_debug("Inserting <%s> element (@%x) from token.\n",
gumbo_normalized_tagname(element->v.element.tag), element);
return element;
}
// Convenience method that combines create_element and insert_element, inserting
// a parser-generated element of a specific tag type. Returns the node
// inserted.
static GumboNode* insert_element_of_tag_type(
GumboParser* parser, GumboTag tag, GumboParseFlags reason) {
GumboNode* element = create_element(parser, tag);
element->parse_flags |= GUMBO_INSERTION_BY_PARSER | reason;
insert_element(parser, element, false);
gumbo_debug("Inserting %s element (@%x) from tag type.\n",
gumbo_normalized_tagname(tag), element);
return element;
}
// Convenience method for creating foreign namespaced element. Returns the node
// inserted.
static GumboNode* insert_foreign_element(
GumboParser* parser, GumboToken* token, GumboNamespaceEnum tag_namespace) {
assert(token->type == GUMBO_TOKEN_START_TAG);
GumboNode* element = create_element_from_token(parser, token, tag_namespace);
insert_element(parser, element, false);
if (token_has_attribute(token, "xmlns") &&
!attribute_matches_case_sensitive(&token->v.start_tag.attributes, "xmlns",
kLegalXmlns[tag_namespace])) {
// TODO(jdtang): Since there're multiple possible error codes here, we
// eventually need reason codes to differentiate them.
parser_add_parse_error(parser, token);
}
if (token_has_attribute(token, "xmlns:xlink") &&
!attribute_matches_case_sensitive(&token->v.start_tag.attributes,
"xmlns:xlink", "http://www.w3.org/1999/xlink")) {
parser_add_parse_error(parser, token);
}
return element;
}
static void insert_text_token(GumboParser* parser, GumboToken* token) {
assert(token->type == GUMBO_TOKEN_WHITESPACE ||
token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_NULL || token->type == GUMBO_TOKEN_CDATA);
TextNodeBufferState* buffer_state = &parser->_parser_state->_text_node;
if (buffer_state->_buffer.length == 0) {
// Initialize position fields.
buffer_state->_start_original_text = token->original_text.data;
buffer_state->_start_position = token->position;
}
gumbo_string_buffer_append_codepoint(
parser, token->v.character, &buffer_state->_buffer);
if (token->type == GUMBO_TOKEN_CHARACTER) {
buffer_state->_type = GUMBO_NODE_TEXT;
} else if (token->type == GUMBO_TOKEN_CDATA) {
buffer_state->_type = GUMBO_NODE_CDATA;
}
gumbo_debug("Inserting text token '%c'.\n", token->v.character);
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#generic-rcdata-element-parsing-algorithm
static void run_generic_parsing_algorithm(
GumboParser* parser, GumboToken* token, GumboTokenizerEnum lexer_state) {
insert_element_from_token(parser, token);
gumbo_tokenizer_set_state(parser, lexer_state);
parser->_parser_state->_original_insertion_mode =
parser->_parser_state->_insertion_mode;
parser->_parser_state->_insertion_mode = GUMBO_INSERTION_MODE_TEXT;
}
static void acknowledge_self_closing_tag(GumboParser* parser) {
parser->_parser_state->_self_closing_flag_acknowledged = true;
}
// Returns true if there's an anchor tag in the list of active formatting
// elements, and fills in its index if so.
static bool find_last_anchor_index(GumboParser* parser, int* anchor_index) {
GumboVector* elements = &parser->_parser_state->_active_formatting_elements;
for (int i = elements->length; --i >= 0;) {
GumboNode* node = elements->data[i];
if (node == &kActiveFormattingScopeMarker) {
return false;
}
if (node_html_tag_is(node, GUMBO_TAG_A)) {
*anchor_index = i;
return true;
}
}
return false;
}
// Counts the number of open formatting elements in the list of active
// formatting elements (after the last active scope marker) that have a specific
// tag. If this is > 0, then earliest_matching_index will be filled in with the
// index of the first such element.
static int count_formatting_elements_of_tag(GumboParser* parser,
const GumboNode* desired_node, int* earliest_matching_index) {
const GumboElement* desired_element = &desired_node->v.element;
GumboVector* elements = &parser->_parser_state->_active_formatting_elements;
int num_identical_elements = 0;
for (int i = elements->length; --i >= 0;) {
GumboNode* node = elements->data[i];
if (node == &kActiveFormattingScopeMarker) {
break;
}
assert(node->type == GUMBO_NODE_ELEMENT);
if (node_qualified_tag_is(
node, desired_element->tag_namespace, desired_element->tag) &&
all_attributes_match(
&node->v.element.attributes, &desired_element->attributes)) {
num_identical_elements++;
*earliest_matching_index = i;
}
}
return num_identical_elements;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#reconstruct-the-active-formatting-elements
static void add_formatting_element(GumboParser* parser, const GumboNode* node) {
assert(node == &kActiveFormattingScopeMarker ||
node->type == GUMBO_NODE_ELEMENT);
GumboVector* elements = &parser->_parser_state->_active_formatting_elements;
if (node == &kActiveFormattingScopeMarker) {
gumbo_debug("Adding a scope marker.\n");
} else {
gumbo_debug("Adding a formatting element.\n");
}
// Hunt for identical elements.
int earliest_identical_element = elements->length;
int num_identical_elements = count_formatting_elements_of_tag(
parser, node, &earliest_identical_element);
// Noah's Ark clause: if there're at least 3, remove the earliest.
if (num_identical_elements >= 3) {
gumbo_debug("Noah's ark clause: removing element at %d.\n",
earliest_identical_element);
gumbo_vector_remove_at(parser, earliest_identical_element, elements);
}
gumbo_vector_add(parser, (void*) node, elements);
}
static bool is_open_element(GumboParser* parser, const GumboNode* node) {
GumboVector* open_elements = &parser->_parser_state->_open_elements;
for (unsigned int i = 0; i < open_elements->length; ++i) {
if (open_elements->data[i] == node) {
return true;
}
}
return false;
}
// Clones attributes, tags, etc. of a node, but does not copy the content. The
// clone shares no structure with the original node: all owned strings and
// values are fresh copies.
GumboNode* clone_node(
GumboParser* parser, GumboNode* node, GumboParseFlags reason) {
assert(node->type == GUMBO_NODE_ELEMENT || node->type == GUMBO_NODE_TEMPLATE);
GumboNode* new_node = gumbo_parser_allocate(parser, sizeof(GumboNode));
*new_node = *node;
new_node->parent = NULL;
new_node->index_within_parent = -1;
// Clear the GUMBO_INSERTION_IMPLICIT_END_TAG flag, as the cloned node may
// have a separate end tag.
new_node->parse_flags &= ~GUMBO_INSERTION_IMPLICIT_END_TAG;
new_node->parse_flags |= reason | GUMBO_INSERTION_BY_PARSER;
GumboElement* element = &new_node->v.element;
gumbo_vector_init(parser, 1, &element->children);
const GumboVector* old_attributes = &node->v.element.attributes;
gumbo_vector_init(parser, old_attributes->length, &element->attributes);
for (unsigned int i = 0; i < old_attributes->length; ++i) {
const GumboAttribute* old_attr = old_attributes->data[i];
GumboAttribute* attr =
gumbo_parser_allocate(parser, sizeof(GumboAttribute));
*attr = *old_attr;
attr->name = gumbo_copy_stringz(parser, old_attr->name);
attr->value = gumbo_copy_stringz(parser, old_attr->value);
gumbo_vector_add(parser, attr, &element->attributes);
}
return new_node;
}
// "Reconstruct active formatting elements" part of the spec.
// This implementation is based on the html5lib translation from the mess of
// GOTOs in the spec to reasonably structured programming.
// http://code.google.com/p/html5lib/source/browse/python/html5lib/treebuilders/_base.py
static void reconstruct_active_formatting_elements(GumboParser* parser) {
GumboVector* elements = &parser->_parser_state->_active_formatting_elements;
// Step 1
if (elements->length == 0) {
return;
}
// Step 2 & 3
unsigned int i = elements->length - 1;
GumboNode* element = elements->data[i];
if (element == &kActiveFormattingScopeMarker ||
is_open_element(parser, element)) {
return;
}
// Step 6
do {
if (i == 0) {
// Step 4
i = -1; // Incremented to 0 below.
break;
}
// Step 5
element = elements->data[--i];
} while (element != &kActiveFormattingScopeMarker &&
!is_open_element(parser, element));
++i;
gumbo_debug("Reconstructing elements from %d on %s parent.\n", i,
gumbo_normalized_tagname(get_current_node(parser)->v.element.tag));
for (; i < elements->length; ++i) {
// Step 7 & 8.
assert(elements->length > 0);
assert(i < elements->length);
element = elements->data[i];
assert(element != &kActiveFormattingScopeMarker);
GumboNode* clone = clone_node(
parser, element, GUMBO_INSERTION_RECONSTRUCTED_FORMATTING_ELEMENT);
// Step 9.
InsertionLocation location =
get_appropriate_insertion_location(parser, NULL);
insert_node(parser, clone, location);
gumbo_vector_add(
parser, (void*) clone, &parser->_parser_state->_open_elements);
// Step 10.
elements->data[i] = clone;
gumbo_debug("Reconstructed %s element at %d.\n",
gumbo_normalized_tagname(clone->v.element.tag), i);
}
}
static void clear_active_formatting_elements(GumboParser* parser) {
GumboVector* elements = &parser->_parser_state->_active_formatting_elements;
int num_elements_cleared = 0;
const GumboNode* node;
do {
node = gumbo_vector_pop(parser, elements);
++num_elements_cleared;
} while (node && node != &kActiveFormattingScopeMarker);
gumbo_debug("Cleared %d elements from active formatting list.\n",
num_elements_cleared);
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-initial-insertion-mode
static GumboQuirksModeEnum compute_quirks_mode(
const GumboTokenDocType* doctype) {
if (doctype->force_quirks || strcmp(doctype->name, kDoctypeHtml.data) ||
is_in_static_list(
doctype->public_identifier, kQuirksModePublicIdPrefixes, false) ||
is_in_static_list(
doctype->public_identifier, kQuirksModePublicIdExactMatches, true) ||
is_in_static_list(
doctype->system_identifier, kQuirksModeSystemIdExactMatches, true) ||
(is_in_static_list(doctype->public_identifier,
kLimitedQuirksRequiresSystemIdPublicIdPrefixes, false) &&
!doctype->has_system_identifier)) {
return GUMBO_DOCTYPE_QUIRKS;
} else if (is_in_static_list(doctype->public_identifier,
kLimitedQuirksPublicIdPrefixes, false) ||
(is_in_static_list(doctype->public_identifier,
kLimitedQuirksRequiresSystemIdPublicIdPrefixes, false) &&
doctype->has_system_identifier)) {
return GUMBO_DOCTYPE_LIMITED_QUIRKS;
}
return GUMBO_DOCTYPE_NO_QUIRKS;
}
// The following functions are all defined by the "has an element in __ scope"
// sections of the HTML5 spec:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-the-specific-scope
// The basic idea behind them is that they check for an element of the given
// qualified name, contained within a scope formed by a set of other qualified
// names. For example, "has an element in list scope" looks for an element of
// the given qualified name within the nearest enclosing <ol> or <ul>, along
// with a bunch of generic element types that serve to "firewall" their content
// from the rest of the document. Note that because of the way the spec is
// written,
// all elements are expected to be in the HTML namespace
static bool has_an_element_in_specific_scope(GumboParser* parser,
int expected_size, const GumboTag* expected, bool negate,
const gumbo_tagset tags) {
GumboVector* open_elements = &parser->_parser_state->_open_elements;
for (int i = open_elements->length; --i >= 0;) {
const GumboNode* node = open_elements->data[i];
if (node->type != GUMBO_NODE_ELEMENT && node->type != GUMBO_NODE_TEMPLATE)
continue;
GumboTag node_tag = node->v.element.tag;
GumboNamespaceEnum node_ns = node->v.element.tag_namespace;
for (int j = 0; j < expected_size; ++j) {
if (node_tag == expected[j] && node_ns == GUMBO_NAMESPACE_HTML)
return true;
}
bool found = TAGSET_INCLUDES(tags, node_ns, node_tag);
if (negate != found) return false;
}
return false;
}
// Checks for the presence of an open element of the specified tag type.
static bool has_open_element(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(
parser, 1, &tag, false, (gumbo_tagset){TAG(HTML)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-scope
static bool has_an_element_in_scope(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(parser, 1, &tag, false,
(gumbo_tagset){TAG(APPLET), TAG(CAPTION), TAG(HTML), TAG(TABLE), TAG(TD),
TAG(TH), TAG(MARQUEE), TAG(OBJECT), TAG(TEMPLATE), TAG_MATHML(MI),
TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS), TAG_MATHML(MTEXT),
TAG_MATHML(ANNOTATION_XML), TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC),
TAG_SVG(TITLE)});
}
// Like "has an element in scope", but for the specific case of looking for a
// unique target node, not for any node with a given tag name. This duplicates
// much of the algorithm from has_an_element_in_specific_scope because the
// predicate is different when checking for an exact node, and it's easier &
// faster just to duplicate the code for this one case than to try and
// parameterize it.
static bool has_node_in_scope(GumboParser* parser, const GumboNode* node) {
GumboVector* open_elements = &parser->_parser_state->_open_elements;
for (int i = open_elements->length; --i >= 0;) {
const GumboNode* current = open_elements->data[i];
if (current == node) {
return true;
}
if (current->type != GUMBO_NODE_ELEMENT &&
current->type != GUMBO_NODE_TEMPLATE) {
continue;
}
if (node_tag_in_set(current,
(gumbo_tagset){TAG(APPLET), TAG(CAPTION), TAG(HTML), TAG(TABLE),
TAG(TD), TAG(TH), TAG(MARQUEE), TAG(OBJECT), TAG(TEMPLATE),
TAG_MATHML(MI), TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS),
TAG_MATHML(MTEXT), TAG_MATHML(ANNOTATION_XML),
TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC), TAG_SVG(TITLE)})) {
return false;
}
}
assert(false);
return false;
}
// Like has_an_element_in_scope, but restricts the expected qualified name to a
// range of possible qualified names instead of just a single one.
static bool has_an_element_in_scope_with_tagname(
GumboParser* parser, int expected_len, const GumboTag expected[]) {
return has_an_element_in_specific_scope(parser, expected_len, expected, false,
(gumbo_tagset){TAG(APPLET), TAG(CAPTION), TAG(HTML), TAG(TABLE), TAG(TD),
TAG(TH), TAG(MARQUEE), TAG(OBJECT), TAG(TEMPLATE), TAG_MATHML(MI),
TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS), TAG_MATHML(MTEXT),
TAG_MATHML(ANNOTATION_XML), TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC),
TAG_SVG(TITLE)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-list-item-scope
static bool has_an_element_in_list_scope(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(parser, 1, &tag, false,
(gumbo_tagset){TAG(APPLET), TAG(CAPTION), TAG(HTML), TAG(TABLE), TAG(TD),
TAG(TH), TAG(MARQUEE), TAG(OBJECT), TAG(TEMPLATE), TAG_MATHML(MI),
TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS), TAG_MATHML(MTEXT),
TAG_MATHML(ANNOTATION_XML), TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC),
TAG_SVG(TITLE), TAG(OL), TAG(UL)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-button-scope
static bool has_an_element_in_button_scope(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(parser, 1, &tag, false,
(gumbo_tagset){TAG(APPLET), TAG(CAPTION), TAG(HTML), TAG(TABLE), TAG(TD),
TAG(TH), TAG(MARQUEE), TAG(OBJECT), TAG(TEMPLATE), TAG_MATHML(MI),
TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS), TAG_MATHML(MTEXT),
TAG_MATHML(ANNOTATION_XML), TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC),
TAG_SVG(TITLE), TAG(BUTTON)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-table-scope
static bool has_an_element_in_table_scope(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(parser, 1, &tag, false,
(gumbo_tagset){TAG(HTML), TAG(TABLE), TAG(TEMPLATE)});
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#has-an-element-in-select-scope
static bool has_an_element_in_select_scope(GumboParser* parser, GumboTag tag) {
return has_an_element_in_specific_scope(
parser, 1, &tag, true, (gumbo_tagset){TAG(OPTGROUP), TAG(OPTION)});
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#generate-implied-end-tags
// "exception" is the "element to exclude from the process" listed in the spec.
// Pass GUMBO_TAG_LAST to not exclude any of them.
static void generate_implied_end_tags(GumboParser* parser, GumboTag exception) {
for (; node_tag_in_set(get_current_node(parser),
(gumbo_tagset){TAG(DD), TAG(DT), TAG(LI), TAG(OPTION),
TAG(OPTGROUP), TAG(P), TAG(RP), TAG(RB), TAG(RT), TAG(RTC)}) &&
!node_html_tag_is(get_current_node(parser), exception);
pop_current_node(parser))
;
}
// This is the "generate all implied end tags thoroughly" clause of the spec.
// https://html.spec.whatwg.org/multipage/syntax.html#closing-elements-that-have-implied-end-tags
static void generate_all_implied_end_tags_thoroughly(GumboParser* parser) {
for (
; node_tag_in_set(get_current_node(parser),
(gumbo_tagset){TAG(CAPTION), TAG(COLGROUP), TAG(DD), TAG(DT), TAG(LI),
TAG(OPTION), TAG(OPTGROUP), TAG(P), TAG(RP), TAG(RT), TAG(RTC),
TAG(TBODY), TAG(TD), TAG(TFOOT), TAG(TH), TAG(HEAD), TAG(TR)});
pop_current_node(parser))
;
}
// This factors out the clauses relating to "act as if an end tag token with tag
// name "table" had been seen. Returns true if there's a table element in table
// scope which was successfully closed, false if not and the token should be
// ignored. Does not add parse errors; callers should handle that.
static bool close_table(GumboParser* parser) {
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_TABLE)) {
return false;
}
GumboNode* node = pop_current_node(parser);
while (!node_html_tag_is(node, GUMBO_TAG_TABLE)) {
node = pop_current_node(parser);
}
reset_insertion_mode_appropriately(parser);
return true;
}
// This factors out the clauses relating to "act as if an end tag token with tag
// name `cell_tag` had been seen".
static bool close_table_cell(
GumboParser* parser, const GumboToken* token, GumboTag cell_tag) {
bool result = true;
generate_implied_end_tags(parser, GUMBO_TAG_LAST);
const GumboNode* node = get_current_node(parser);
if (!node_html_tag_is(node, cell_tag)) {
parser_add_parse_error(parser, token);
result = false;
}
do {
node = pop_current_node(parser);
} while (!node_html_tag_is(node, cell_tag));
clear_active_formatting_elements(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_ROW);
return result;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#close-the-cell
// This holds the logic to determine whether we should close a <td> or a <th>.
static bool close_current_cell(GumboParser* parser, const GumboToken* token) {
if (has_an_element_in_table_scope(parser, GUMBO_TAG_TD)) {
assert(!has_an_element_in_table_scope(parser, GUMBO_TAG_TH));
return close_table_cell(parser, token, GUMBO_TAG_TD);
} else {
assert(has_an_element_in_table_scope(parser, GUMBO_TAG_TH));
return close_table_cell(parser, token, GUMBO_TAG_TH);
}
}
// This factors out the "act as if an end tag of tag name 'select' had been
// seen" clause of the spec, since it's referenced in several places. It pops
// all nodes from the stack until the current <select> has been closed, then
// resets the insertion mode appropriately.
static void close_current_select(GumboParser* parser) {
GumboNode* node = pop_current_node(parser);
while (!node_html_tag_is(node, GUMBO_TAG_SELECT)) {
node = pop_current_node(parser);
}
reset_insertion_mode_appropriately(parser);
}
// The list of nodes in the "special" category:
// http://www.whatwg.org/specs/web-apps/current-work/complete/parsing.html#special
static bool is_special_node(const GumboNode* node) {
assert(node->type == GUMBO_NODE_ELEMENT || node->type == GUMBO_NODE_TEMPLATE);
return node_tag_in_set(node,
(gumbo_tagset){TAG(ADDRESS), TAG(APPLET), TAG(AREA), TAG(ARTICLE),
TAG(ASIDE), TAG(BASE), TAG(BASEFONT), TAG(BGSOUND), TAG(BLOCKQUOTE),
TAG(BODY), TAG(BR), TAG(BUTTON), TAG(CAPTION), TAG(CENTER), TAG(COL),
TAG(COLGROUP), TAG(MENUITEM), TAG(DD), TAG(DETAILS), TAG(DIR),
TAG(DIV), TAG(DL), TAG(DT), TAG(EMBED), TAG(FIELDSET),
TAG(FIGCAPTION), TAG(FIGURE), TAG(FOOTER), TAG(FORM), TAG(FRAME),
TAG(FRAMESET), TAG(H1), TAG(H2), TAG(H3), TAG(H4), TAG(H5), TAG(H6),
TAG(HEAD), TAG(HEADER), TAG(HGROUP), TAG(HR), TAG(HTML), TAG(IFRAME),
TAG(IMG), TAG(INPUT), TAG(ISINDEX), TAG(LI), TAG(LINK), TAG(LISTING),
TAG(MARQUEE), TAG(MENU), TAG(META), TAG(NAV), TAG(NOEMBED),
TAG(NOFRAMES), TAG(NOSCRIPT), TAG(OBJECT), TAG(OL), TAG(P),
TAG(PARAM), TAG(PLAINTEXT), TAG(PRE), TAG(SCRIPT), TAG(SECTION),
TAG(SELECT), TAG(STYLE), TAG(SUMMARY), TAG(TABLE), TAG(TBODY),
TAG(TD), TAG(TEMPLATE), TAG(TEXTAREA), TAG(TFOOT), TAG(TH),
TAG(THEAD), TAG(TITLE), TAG(TR), TAG(UL), TAG(WBR), TAG(XMP),
TAG_MATHML(MI), TAG_MATHML(MO), TAG_MATHML(MN), TAG_MATHML(MS),
TAG_MATHML(MTEXT), TAG_MATHML(ANNOTATION_XML),
TAG_SVG(FOREIGNOBJECT), TAG_SVG(DESC)});
}
// Implicitly closes currently open elements until it reaches an element with
// the
// specified qualified name. If the elements closed are in the set handled by
// generate_implied_end_tags, this is normal operation and this function returns
// true. Otherwise, a parse error is recorded and this function returns false.
static bool implicitly_close_tags(GumboParser* parser, GumboToken* token,
GumboNamespaceEnum target_ns, GumboTag target) {
bool result = true;
generate_implied_end_tags(parser, target);
if (!node_qualified_tag_is(get_current_node(parser), target_ns, target)) {
parser_add_parse_error(parser, token);
while (
!node_qualified_tag_is(get_current_node(parser), target_ns, target)) {
pop_current_node(parser);
}
result = false;
}
assert(node_qualified_tag_is(get_current_node(parser), target_ns, target));
pop_current_node(parser);
return result;
}
// If the stack of open elements has a <p> tag in button scope, this acts as if
// a </p> tag was encountered, implicitly closing tags. Returns false if a
// parse error occurs. This is a convenience function because this particular
// clause appears several times in the spec.
static bool maybe_implicitly_close_p_tag(
GumboParser* parser, GumboToken* token) {
if (has_an_element_in_button_scope(parser, GUMBO_TAG_P)) {
return implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, GUMBO_TAG_P);
}
return true;
}
// Convenience function to encapsulate the logic for closing <li> or <dd>/<dt>
// tags. Pass true to is_li for handling <li> tags, false for <dd> and <dt>.
static void maybe_implicitly_close_list_tag(
GumboParser* parser, GumboToken* token, bool is_li) {
GumboParserState* state = parser->_parser_state;
state->_frameset_ok = false;
for (int i = state->_open_elements.length; --i >= 0;) {
const GumboNode* node = state->_open_elements.data[i];
bool is_list_tag =
is_li ? node_html_tag_is(node, GUMBO_TAG_LI)
: node_tag_in_set(node, (gumbo_tagset){TAG(DD), TAG(DT)});
if (is_list_tag) {
implicitly_close_tags(
parser, token, node->v.element.tag_namespace, node->v.element.tag);
return;
}
if (is_special_node(node) &&
!node_tag_in_set(
node, (gumbo_tagset){TAG(ADDRESS), TAG(DIV), TAG(P)})) {
return;
}
}
}
static void merge_attributes(
GumboParser* parser, GumboToken* token, GumboNode* node) {
assert(token->type == GUMBO_TOKEN_START_TAG);
assert(node->type == GUMBO_NODE_ELEMENT);
const GumboVector* token_attr = &token->v.start_tag.attributes;
GumboVector* node_attr = &node->v.element.attributes;
for (unsigned int i = 0; i < token_attr->length; ++i) {
GumboAttribute* attr = token_attr->data[i];
if (!gumbo_get_attribute(node_attr, attr->name)) {
// Ownership of the attribute is transferred by this gumbo_vector_add,
// so it has to be nulled out of the original token so it doesn't get
// double-deleted.
gumbo_vector_add(parser, attr, node_attr);
token_attr->data[i] = NULL;
}
}
// When attributes are merged, it means the token has been ignored and merged
// with another token, so we need to free its memory. The attributes that are
// transferred need to be nulled-out in the vector above so that they aren't
// double-deleted.
gumbo_token_destroy(parser, token);
#ifndef NDEBUG
// Mark this sentinel so the assertion in the main loop knows it's been
// destroyed.
token->v.start_tag.attributes = kGumboEmptyVector;
#endif
}
const char* gumbo_normalize_svg_tagname(const GumboStringPiece* tag) {
for (size_t i = 0; i < sizeof(kSvgTagReplacements) / sizeof(ReplacementEntry);
++i) {
const ReplacementEntry* entry = &kSvgTagReplacements[i];
if (gumbo_string_equals_ignore_case(tag, &entry->from)) {
return entry->to.data;
}
}
return NULL;
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adjust-foreign-attributes
// This destructively modifies any matching attributes on the token and sets the
// namespace appropriately.
static void adjust_foreign_attributes(GumboParser* parser, GumboToken* token) {
assert(token->type == GUMBO_TOKEN_START_TAG);
const GumboVector* attributes = &token->v.start_tag.attributes;
for (size_t i = 0; i < sizeof(kForeignAttributeReplacements) /
sizeof(NamespacedAttributeReplacement);
++i) {
const NamespacedAttributeReplacement* entry =
&kForeignAttributeReplacements[i];
GumboAttribute* attr = gumbo_get_attribute(attributes, entry->from);
if (!attr) {
continue;
}
gumbo_parser_deallocate(parser, (void*) attr->name);
attr->attr_namespace = entry->attr_namespace;
attr->name = gumbo_copy_stringz(parser, entry->local_name);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#adjust-svg-attributes
// This destructively modifies any matching attributes on the token.
static void adjust_svg_attributes(GumboParser* parser, GumboToken* token) {
assert(token->type == GUMBO_TOKEN_START_TAG);
const GumboVector* attributes = &token->v.start_tag.attributes;
for (size_t i = 0;
i < sizeof(kSvgAttributeReplacements) / sizeof(ReplacementEntry); ++i) {
const ReplacementEntry* entry = &kSvgAttributeReplacements[i];
GumboAttribute* attr = gumbo_get_attribute(attributes, entry->from.data);
if (!attr) {
continue;
}
gumbo_parser_deallocate(parser, (void*) attr->name);
attr->name = gumbo_copy_stringz(parser, entry->to.data);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#adjust-mathml-attributes
// Note that this may destructively modify the token with the new attribute
// value.
static void adjust_mathml_attributes(GumboParser* parser, GumboToken* token) {
assert(token->type == GUMBO_TOKEN_START_TAG);
GumboAttribute* attr =
gumbo_get_attribute(&token->v.start_tag.attributes, "definitionurl");
if (!attr) {
return;
}
gumbo_parser_deallocate(parser, (void*) attr->name);
attr->name = gumbo_copy_stringz(parser, "definitionURL");
}
static bool doctype_matches(const GumboTokenDocType* doctype,
const GumboStringPiece* public_id, const GumboStringPiece* system_id,
bool allow_missing_system_id) {
return !strcmp(doctype->public_identifier, public_id->data) &&
(allow_missing_system_id || doctype->has_system_identifier) &&
!strcmp(doctype->system_identifier, system_id->data);
}
static bool maybe_add_doctype_error(
GumboParser* parser, const GumboToken* token) {
const GumboTokenDocType* doctype = &token->v.doc_type;
bool html_doctype = !strcmp(doctype->name, kDoctypeHtml.data);
if ((!html_doctype || doctype->has_public_identifier ||
(doctype->has_system_identifier &&
!strcmp(
doctype->system_identifier, kSystemIdLegacyCompat.data))) &&
!(html_doctype && (doctype_matches(doctype, &kPublicIdHtml4_0,
&kSystemIdRecHtml4_0, true) ||
doctype_matches(doctype, &kPublicIdHtml4_01,
&kSystemIdHtml4, true) ||
doctype_matches(doctype, &kPublicIdXhtml1_0,
&kSystemIdXhtmlStrict1_1, false) ||
doctype_matches(doctype, &kPublicIdXhtml1_1,
&kSystemIdXhtml1_1, false)))) {
parser_add_parse_error(parser, token);
return false;
}
return true;
}
static void remove_from_parent(GumboParser* parser, GumboNode* node) {
if (!node->parent) {
// The node may not have a parent if, for example, it is a newly-cloned copy
// of an active formatting element. DOM manipulations continue with the
// orphaned fragment of the DOM tree until it's appended/foster-parented to
// the common ancestor at the end of the adoption agency algorithm.
return;
}
assert(node->parent->type == GUMBO_NODE_ELEMENT);
GumboVector* children = &node->parent->v.element.children;
int index = gumbo_vector_index_of(children, node);
assert(index != -1);
gumbo_vector_remove_at(parser, index, children);
node->parent = NULL;
node->index_within_parent = -1;
for (unsigned int i = index; i < children->length; ++i) {
GumboNode* child = children->data[i];
child->index_within_parent = i;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#an-introduction-to-error-handling-and-strange-cases-in-the-parser
// Also described in the "in body" handling for end formatting tags.
static bool adoption_agency_algorithm(
GumboParser* parser, GumboToken* token, GumboTag subject) {
GumboParserState* state = parser->_parser_state;
gumbo_debug("Entering adoption agency algorithm.\n");
// Step 1.
GumboNode* current_node = get_current_node(parser);
if (current_node->v.element.tag_namespace == GUMBO_NAMESPACE_HTML &&
current_node->v.element.tag == subject &&
gumbo_vector_index_of(
&state->_active_formatting_elements, current_node) == -1) {
pop_current_node(parser);
return false;
}
// Steps 2-4 & 20:
for (unsigned int i = 0; i < 8; ++i) {
// Step 5.
GumboNode* formatting_node = NULL;
int formatting_node_in_open_elements = -1;
for (int j = state->_active_formatting_elements.length; --j >= 0;) {
GumboNode* current_node = state->_active_formatting_elements.data[j];
if (current_node == &kActiveFormattingScopeMarker) {
gumbo_debug("Broke on scope marker; aborting.\n");
// Last scope marker; abort the algorithm.
return false;
}
if (node_html_tag_is(current_node, subject)) {
// Found it.
formatting_node = current_node;
formatting_node_in_open_elements =
gumbo_vector_index_of(&state->_open_elements, formatting_node);
gumbo_debug("Formatting element of tag %s at %d.\n",
gumbo_normalized_tagname(subject),
formatting_node_in_open_elements);
break;
}
}
if (!formatting_node) {
// No matching tag; not a parse error outright, but fall through to the
// "any other end tag" clause (which may potentially add a parse error,
// but not always).
gumbo_debug("No active formatting elements; aborting.\n");
return false;
}
// Step 6
if (formatting_node_in_open_elements == -1) {
gumbo_debug("Formatting node not on stack of open elements.\n");
parser_add_parse_error(parser, token);
gumbo_vector_remove(
parser, formatting_node, &state->_active_formatting_elements);
return false;
}
// Step 7
if (!has_an_element_in_scope(parser, formatting_node->v.element.tag)) {
parser_add_parse_error(parser, token);
gumbo_debug("Element not in scope.\n");
return false;
}
// Step 8
if (formatting_node != get_current_node(parser)) {
parser_add_parse_error(parser, token); // But continue onwards.
}
assert(formatting_node);
assert(!node_html_tag_is(formatting_node, GUMBO_TAG_HTML));
assert(!node_html_tag_is(formatting_node, GUMBO_TAG_BODY));
// Step 9 & 10
GumboNode* furthest_block = NULL;
for (unsigned int j = formatting_node_in_open_elements;
j < state->_open_elements.length; ++j) {
assert(j > 0);
GumboNode* current = state->_open_elements.data[j];
if (is_special_node(current)) {
// Step 9.
furthest_block = current;
break;
}
}
if (!furthest_block) {
// Step 10.
while (get_current_node(parser) != formatting_node) {
pop_current_node(parser);
}
// And the formatting element itself.
pop_current_node(parser);
gumbo_vector_remove(
parser, formatting_node, &state->_active_formatting_elements);
return false;
}
assert(!node_html_tag_is(furthest_block, GUMBO_TAG_HTML));
assert(furthest_block);
// Step 11.
// Elements may be moved and reparented by this algorithm, so
// common_ancestor is not necessarily the same as formatting_node->parent.
GumboNode* common_ancestor =
state->_open_elements.data[gumbo_vector_index_of(&state->_open_elements,
formatting_node) -
1];
gumbo_debug("Common ancestor tag = %s, furthest block tag = %s.\n",
gumbo_normalized_tagname(common_ancestor->v.element.tag),
gumbo_normalized_tagname(furthest_block->v.element.tag));
// Step 12.
int bookmark = gumbo_vector_index_of(
&state->_active_formatting_elements, formatting_node) +
1;
gumbo_debug("Bookmark at %d.\n", bookmark);
// Step 13.
GumboNode* node = furthest_block;
GumboNode* last_node = furthest_block;
// Must be stored explicitly, in case node is removed from the stack of open
// elements, to handle step 9.4.
int saved_node_index = gumbo_vector_index_of(&state->_open_elements, node);
assert(saved_node_index > 0);
// Step 13.1.
for (int j = 0;;) {
// Step 13.2.
++j;
// Step 13.3.
int node_index = gumbo_vector_index_of(&state->_open_elements, node);
gumbo_debug(
"Current index: %d, last index: %d.\n", node_index, saved_node_index);
if (node_index == -1) {
node_index = saved_node_index;
}
saved_node_index = --node_index;
assert(node_index > 0);
assert((unsigned int) node_index < state->_open_elements.capacity);
node = state->_open_elements.data[node_index];
assert(node->parent);
if (node == formatting_node) {
// Step 13.4.
break;
}
int formatting_index =
gumbo_vector_index_of(&state->_active_formatting_elements, node);
if (j > 3 && formatting_index != -1) {
// Step 13.5.
gumbo_debug("Removing formatting element at %d.\n", formatting_index);
gumbo_vector_remove_at(
parser, formatting_index, &state->_active_formatting_elements);
// Removing the element shifts all indices over by one, so we may need
// to move the bookmark.
if (formatting_index < bookmark) {
--bookmark;
gumbo_debug("Moving bookmark to %d.\n", bookmark);
}
continue;
}
if (formatting_index == -1) {
// Step 13.6.
gumbo_vector_remove_at(parser, node_index, &state->_open_elements);
continue;
}
// Step 13.7.
// "common ancestor as the intended parent" doesn't actually mean insert
// it into the common ancestor; that happens below.
node = clone_node(parser, node, GUMBO_INSERTION_ADOPTION_AGENCY_CLONED);
assert(formatting_index >= 0);
state->_active_formatting_elements.data[formatting_index] = node;
assert(node_index >= 0);
state->_open_elements.data[node_index] = node;
// Step 13.8.
if (last_node == furthest_block) {
bookmark = formatting_index + 1;
gumbo_debug("Bookmark moved to %d.\n", bookmark);
assert((unsigned int) bookmark <= state->_active_formatting_elements.length);
}
// Step 13.9.
last_node->parse_flags |= GUMBO_INSERTION_ADOPTION_AGENCY_MOVED;
remove_from_parent(parser, last_node);
append_node(parser, node, last_node);
// Step 13.10.
last_node = node;
} // Step 13.11.
// Step 14.
gumbo_debug("Removing %s node from parent ",
gumbo_normalized_tagname(last_node->v.element.tag));
remove_from_parent(parser, last_node);
last_node->parse_flags |= GUMBO_INSERTION_ADOPTION_AGENCY_MOVED;
InsertionLocation location =
get_appropriate_insertion_location(parser, common_ancestor);
gumbo_debug("and inserting it into %s.\n",
gumbo_normalized_tagname(location.target->v.element.tag));
insert_node(parser, last_node, location);
// Step 15.
GumboNode* new_formatting_node = clone_node(
parser, formatting_node, GUMBO_INSERTION_ADOPTION_AGENCY_CLONED);
formatting_node->parse_flags |= GUMBO_INSERTION_IMPLICIT_END_TAG;
// Step 16. Instead of appending nodes one-by-one, we swap the children
// vector of furthest_block with the empty children of new_formatting_node,
// reducing memory traffic and allocations. We still have to reset their
// parent pointers, though.
GumboVector temp = new_formatting_node->v.element.children;
new_formatting_node->v.element.children =
furthest_block->v.element.children;
furthest_block->v.element.children = temp;
temp = new_formatting_node->v.element.children;
for (unsigned int i = 0; i < temp.length; ++i) {
GumboNode* child = temp.data[i];
child->parent = new_formatting_node;
}
// Step 17.
append_node(parser, furthest_block, new_formatting_node);
// Step 18.
// If the formatting node was before the bookmark, it may shift over all
// indices after it, so we need to explicitly find the index and possibly
// adjust the bookmark.
int formatting_node_index = gumbo_vector_index_of(
&state->_active_formatting_elements, formatting_node);
assert(formatting_node_index != -1);
if (formatting_node_index < bookmark) {
gumbo_debug(
"Formatting node at %d is before bookmark at %d; decrementing.\n",
formatting_node_index, bookmark);
--bookmark;
}
gumbo_vector_remove_at(
parser, formatting_node_index, &state->_active_formatting_elements);
assert(bookmark >= 0);
assert((unsigned int) bookmark <= state->_active_formatting_elements.length);
gumbo_vector_insert_at(parser, new_formatting_node, bookmark,
&state->_active_formatting_elements);
// Step 19.
gumbo_vector_remove(parser, formatting_node, &state->_open_elements);
int insert_at =
gumbo_vector_index_of(&state->_open_elements, furthest_block) + 1;
assert(insert_at >= 0);
assert((unsigned int) insert_at <= state->_open_elements.length);
gumbo_vector_insert_at(
parser, new_formatting_node, insert_at, &state->_open_elements);
} // Step 20.
return true;
}
// This is here to clean up memory when the spec says "Ignore current token."
static void ignore_token(GumboParser* parser) {
GumboToken* token = parser->_parser_state->_current_token;
// Ownership of the token's internal buffers are normally transferred to the
// element, but if no element is emitted (as happens in non-verbatim-mode
// when a token is ignored), we need to free it here to prevent a memory
// leak.
gumbo_token_destroy(parser, token);
#ifndef NDEBUG
if (token->type == GUMBO_TOKEN_START_TAG) {
// Mark this sentinel so the assertion in the main loop knows it's been
// destroyed.
token->v.start_tag.attributes = kGumboEmptyVector;
}
#endif
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/the-end.html
static void finish_parsing(GumboParser* parser) {
gumbo_debug("Finishing parsing");
maybe_flush_text_node_buffer(parser);
GumboParserState* state = parser->_parser_state;
for (GumboNode* node = pop_current_node(parser); node;
node = pop_current_node(parser)) {
if ((node_html_tag_is(node, GUMBO_TAG_BODY) && state->_closed_body_tag) ||
(node_html_tag_is(node, GUMBO_TAG_HTML) && state->_closed_html_tag)) {
continue;
}
node->parse_flags |= GUMBO_INSERTION_IMPLICIT_END_TAG;
}
while (pop_current_node(parser))
; // Pop them all.
}
static bool handle_initial(GumboParser* parser, GumboToken* token) {
GumboDocument* document = &get_document_node(parser)->v.document;
if (token->type == GUMBO_TOKEN_WHITESPACE) {
ignore_token(parser);
return true;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_document_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
document->has_doctype = true;
document->name = token->v.doc_type.name;
document->public_identifier = token->v.doc_type.public_identifier;
document->system_identifier = token->v.doc_type.system_identifier;
document->doc_type_quirks_mode = compute_quirks_mode(&token->v.doc_type);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_BEFORE_HTML);
return maybe_add_doctype_error(parser, token);
}
parser_add_parse_error(parser, token);
document->doc_type_quirks_mode = GUMBO_DOCTYPE_QUIRKS;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_BEFORE_HTML);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-before-html-insertion-mode
static bool handle_before_html(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_document_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_WHITESPACE) {
ignore_token(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
GumboNode* html_node = insert_element_from_token(parser, token);
parser->_output->root = html_node;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_BEFORE_HEAD);
return true;
} else if (token->type == GUMBO_TOKEN_END_TAG &&
!tag_in(token, false,
(gumbo_tagset){TAG(HEAD), TAG(BODY), TAG(HTML), TAG(BR)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
GumboNode* html_node = insert_element_of_tag_type(
parser, GUMBO_TAG_HTML, GUMBO_INSERTION_IMPLIED);
assert(html_node);
parser->_output->root = html_node;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_BEFORE_HEAD);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-before-head-insertion-mode
static bool handle_before_head(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_WHITESPACE) {
ignore_token(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HEAD)) {
GumboNode* node = insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_HEAD);
parser->_parser_state->_head_element = node;
return true;
} else if (token->type == GUMBO_TOKEN_END_TAG &&
!tag_in(token, false,
(gumbo_tagset){TAG(HEAD), TAG(BODY), TAG(HTML), TAG(BR)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
GumboNode* node = insert_element_of_tag_type(
parser, GUMBO_TAG_HEAD, GUMBO_INSERTION_IMPLIED);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_HEAD);
parser->_parser_state->_head_element = node;
parser->_parser_state->_reprocess_current_token = true;
return true;
}
}
// Forward declarations because of mutual dependencies.
static bool handle_token(GumboParser* parser, GumboToken* token);
static bool handle_in_body(GumboParser* parser, GumboToken* token);
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inhead
static bool handle_in_head(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(BASE), TAG(BASEFONT), TAG(BGSOUND),
TAG(MENUITEM), TAG(LINK)})) {
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_META)) {
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
// NOTE(jdtang): Gumbo handles only UTF-8, so the encoding clause of the
// spec doesn't apply. If clients want to handle meta-tag re-encoding, they
// should specifically look for that string in the document and re-encode it
// before passing to Gumbo.
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TITLE)) {
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RCDATA);
return true;
} else if (tag_in(
token, kStartTag, (gumbo_tagset){TAG(NOFRAMES), TAG(STYLE)})) {
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RAWTEXT);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOSCRIPT)) {
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_HEAD_NOSCRIPT);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_SCRIPT)) {
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_SCRIPT);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_HEAD)) {
GumboNode* head = pop_current_node(parser);
AVOID_UNUSED_VARIABLE_WARNING(head);
assert(node_html_tag_is(head, GUMBO_TAG_HEAD));
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_HEAD);
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(HTML), TAG(BR)})) {
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_HEAD);
parser->_parser_state->_reprocess_current_token = true;
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TEMPLATE)) {
insert_element_from_token(parser, token);
add_formatting_element(parser, &kActiveFormattingScopeMarker);
parser->_parser_state->_frameset_ok = false;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TEMPLATE);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TEMPLATE);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
if (!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
generate_all_implied_end_tags_thoroughly(parser);
bool success = true;
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_TEMPLATE)) {
parser_add_parse_error(parser, token);
success = false;
}
while (!node_html_tag_is(pop_current_node(parser), GUMBO_TAG_TEMPLATE))
;
clear_active_formatting_elements(parser);
pop_template_insertion_mode(parser);
reset_insertion_mode_appropriately(parser);
return success;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HEAD) ||
(token->type == GUMBO_TOKEN_END_TAG)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_HEAD);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
return true;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inheadnoscript
static bool handle_in_head_noscript(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kEndTag, GUMBO_TAG_NOSCRIPT)) {
const GumboNode* node = pop_current_node(parser);
assert(node_html_tag_is(node, GUMBO_TAG_NOSCRIPT));
AVOID_UNUSED_VARIABLE_WARNING(node);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_HEAD);
return true;
} else if (token->type == GUMBO_TOKEN_WHITESPACE ||
token->type == GUMBO_TOKEN_COMMENT ||
tag_in(token, kStartTag,
(gumbo_tagset){TAG(BASEFONT), TAG(BGSOUND), TAG(LINK),
TAG(META), TAG(NOFRAMES), TAG(STYLE)})) {
return handle_in_head(parser, token);
} else if (tag_in(
token, kStartTag, (gumbo_tagset){TAG(HEAD), TAG(NOSCRIPT)}) ||
(token->type == GUMBO_TOKEN_END_TAG &&
!tag_is(token, kEndTag, GUMBO_TAG_BR))) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
parser_add_parse_error(parser, token);
const GumboNode* node = pop_current_node(parser);
assert(node_html_tag_is(node, GUMBO_TAG_NOSCRIPT));
AVOID_UNUSED_VARIABLE_WARNING(node);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_HEAD);
parser->_parser_state->_reprocess_current_token = true;
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-after-head-insertion-mode
static bool handle_after_head(GumboParser* parser, GumboToken* token) {
GumboParserState* state = parser->_parser_state;
if (token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_BODY)) {
insert_element_from_token(parser, token);
state->_frameset_ok = false;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_FRAMESET)) {
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_FRAMESET);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(BASE), TAG(BASEFONT), TAG(BGSOUND),
TAG(LINK), TAG(META), TAG(NOFRAMES), TAG(SCRIPT),
TAG(STYLE), TAG(TEMPLATE), TAG(TITLE)})) {
parser_add_parse_error(parser, token);
assert(state->_head_element != NULL);
// This must be flushed before we push the head element on, as there may be
// pending character tokens that should be attached to the root.
maybe_flush_text_node_buffer(parser);
gumbo_vector_add(parser, state->_head_element, &state->_open_elements);
bool result = handle_in_head(parser, token);
gumbo_vector_remove(parser, state->_head_element, &state->_open_elements);
return result;
} else if (tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
return handle_in_head(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_HEAD) ||
(token->type == GUMBO_TOKEN_END_TAG &&
!tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(HTML), TAG(BR)}))) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
insert_element_of_tag_type(parser, GUMBO_TAG_BODY, GUMBO_INSERTION_IMPLIED);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
state->_reprocess_current_token = true;
return true;
}
}
static void destroy_node(GumboParser* parser, GumboNode* node) {
switch (node->type) {
case GUMBO_NODE_DOCUMENT: {
GumboDocument* doc = &node->v.document;
for (unsigned int i = 0; i < doc->children.length; ++i) {
destroy_node(parser, doc->children.data[i]);
}
gumbo_parser_deallocate(parser, (void*) doc->children.data);
gumbo_parser_deallocate(parser, (void*) doc->name);
gumbo_parser_deallocate(parser, (void*) doc->public_identifier);
gumbo_parser_deallocate(parser, (void*) doc->system_identifier);
} break;
case GUMBO_NODE_TEMPLATE:
case GUMBO_NODE_ELEMENT:
for (unsigned int i = 0; i < node->v.element.attributes.length; ++i) {
gumbo_destroy_attribute(parser, node->v.element.attributes.data[i]);
}
gumbo_parser_deallocate(parser, node->v.element.attributes.data);
for (unsigned int i = 0; i < node->v.element.children.length; ++i) {
destroy_node(parser, node->v.element.children.data[i]);
}
gumbo_parser_deallocate(parser, node->v.element.children.data);
break;
case GUMBO_NODE_TEXT:
case GUMBO_NODE_CDATA:
case GUMBO_NODE_COMMENT:
case GUMBO_NODE_WHITESPACE:
gumbo_parser_deallocate(parser, (void*) node->v.text.text);
break;
}
gumbo_parser_deallocate(parser, node);
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inbody
static bool handle_in_body(GumboParser* parser, GumboToken* token) {
GumboParserState* state = parser->_parser_state;
assert(state->_open_elements.length > 0);
if (token->type == GUMBO_TOKEN_NULL) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_WHITESPACE) {
reconstruct_active_formatting_elements(parser);
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_CDATA) {
reconstruct_active_formatting_elements(parser);
insert_text_token(parser, token);
set_frameset_not_ok(parser);
return true;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
parser_add_parse_error(parser, token);
if (has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
ignore_token(parser);
return false;
}
assert(parser->_output->root != NULL);
assert(parser->_output->root->type == GUMBO_NODE_ELEMENT);
merge_attributes(parser, token, parser->_output->root);
return false;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(BASE), TAG(BASEFONT), TAG(BGSOUND),
TAG(MENUITEM), TAG(LINK), TAG(META), TAG(NOFRAMES),
TAG(SCRIPT), TAG(STYLE), TAG(TEMPLATE), TAG(TITLE)}) ||
tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
return handle_in_head(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_BODY)) {
parser_add_parse_error(parser, token);
if (state->_open_elements.length < 2 ||
!node_html_tag_is(state->_open_elements.data[1], GUMBO_TAG_BODY) ||
has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
ignore_token(parser);
return false;
}
state->_frameset_ok = false;
merge_attributes(parser, token, state->_open_elements.data[1]);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_FRAMESET)) {
parser_add_parse_error(parser, token);
if (state->_open_elements.length < 2 ||
!node_html_tag_is(state->_open_elements.data[1], GUMBO_TAG_BODY) ||
!state->_frameset_ok) {
ignore_token(parser);
return false;
}
// Save the body node for later removal.
GumboNode* body_node = state->_open_elements.data[1];
// Pop all nodes except root HTML element.
GumboNode* node;
do {
node = pop_current_node(parser);
} while (node != state->_open_elements.data[1]);
// Removing & destroying the body node is going to kill any nodes that have
// been added to the list of active formatting elements, and so we should
// clear it to prevent a use-after-free if the list of active formatting
// elements is reconstructed afterwards. This may happen if whitespace
// follows the </frameset>.
clear_active_formatting_elements(parser);
// Remove the body node. We may want to factor this out into a generic
// helper, but right now this is the only code that needs to do this.
GumboVector* children = &parser->_output->root->v.element.children;
for (unsigned int i = 0; i < children->length; ++i) {
if (children->data[i] == body_node) {
gumbo_vector_remove_at(parser, i, children);
break;
}
}
destroy_node(parser, body_node);
// Insert the <frameset>, and switch the insertion mode.
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_FRAMESET);
return true;
} else if (token->type == GUMBO_TOKEN_EOF) {
for (unsigned int i = 0; i < state->_open_elements.length; ++i) {
if (!node_tag_in_set(state->_open_elements.data[i],
(gumbo_tagset){TAG(DD), TAG(DT), TAG(LI), TAG(P), TAG(TBODY),
TAG(TD), TAG(TFOOT), TAG(TH), TAG(THEAD), TAG(TR), TAG(BODY),
TAG(HTML)})) {
parser_add_parse_error(parser, token);
}
}
if (get_current_template_insertion_mode(parser) !=
GUMBO_INSERTION_MODE_INITIAL) {
return handle_in_template(parser, token);
}
return true;
} else if (tag_in(token, kEndTag, (gumbo_tagset){TAG(BODY), TAG(HTML)})) {
if (!has_an_element_in_scope(parser, GUMBO_TAG_BODY)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
bool success = true;
for (unsigned int i = 0; i < state->_open_elements.length; ++i) {
if (!node_tag_in_set(state->_open_elements.data[i],
(gumbo_tagset){TAG(DD), TAG(DT), TAG(LI), TAG(OPTGROUP),
TAG(OPTION), TAG(P), TAG(RB), TAG(RP), TAG(RT), TAG(RTC),
TAG(TBODY), TAG(TD), TAG(TFOOT), TAG(TH), TAG(THEAD), TAG(TR),
TAG(BODY), TAG(HTML)})) {
parser_add_parse_error(parser, token);
success = false;
break;
}
}
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_BODY);
if (tag_is(token, kEndTag, GUMBO_TAG_HTML)) {
parser->_parser_state->_reprocess_current_token = true;
} else {
GumboNode* body = state->_open_elements.data[1];
assert(node_html_tag_is(body, GUMBO_TAG_BODY));
record_end_of_element(state->_current_token, &body->v.element);
}
return success;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(ADDRESS), TAG(ARTICLE), TAG(ASIDE),
TAG(BLOCKQUOTE), TAG(CENTER), TAG(DETAILS), TAG(DIR),
TAG(DIV), TAG(DL), TAG(FIELDSET), TAG(FIGCAPTION),
TAG(FIGURE), TAG(FOOTER), TAG(HEADER), TAG(HGROUP),
TAG(MENU), TAG(MAIN), TAG(NAV), TAG(OL), TAG(P),
TAG(SECTION), TAG(SUMMARY), TAG(UL)})) {
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
return result;
} else if (tag_in(token, kStartTag, (gumbo_tagset){TAG(H1), TAG(H2), TAG(H3),
TAG(H4), TAG(H5), TAG(H6)})) {
bool result = maybe_implicitly_close_p_tag(parser, token);
if (node_tag_in_set(
get_current_node(parser), (gumbo_tagset){TAG(H1), TAG(H2), TAG(H3),
TAG(H4), TAG(H5), TAG(H6)})) {
parser_add_parse_error(parser, token);
pop_current_node(parser);
result = false;
}
insert_element_from_token(parser, token);
return result;
} else if (tag_in(token, kStartTag, (gumbo_tagset){TAG(PRE), TAG(LISTING)})) {
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
state->_ignore_next_linefeed = true;
state->_frameset_ok = false;
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_FORM)) {
if (state->_form_element != NULL &&
!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
gumbo_debug("Ignoring nested form.\n");
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
bool result = maybe_implicitly_close_p_tag(parser, token);
GumboNode* form_element = insert_element_from_token(parser, token);
if (!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
state->_form_element = form_element;
}
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_LI)) {
maybe_implicitly_close_list_tag(parser, token, true);
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
return result;
} else if (tag_in(token, kStartTag, (gumbo_tagset){TAG(DD), TAG(DT)})) {
maybe_implicitly_close_list_tag(parser, token, false);
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_PLAINTEXT)) {
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
gumbo_tokenizer_set_state(parser, GUMBO_LEX_PLAINTEXT);
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_BUTTON)) {
if (has_an_element_in_scope(parser, GUMBO_TAG_BUTTON)) {
parser_add_parse_error(parser, token);
implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, GUMBO_TAG_BUTTON);
state->_reprocess_current_token = true;
return false;
}
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
state->_frameset_ok = false;
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(ADDRESS), TAG(ARTICLE), TAG(ASIDE),
TAG(BLOCKQUOTE), TAG(BUTTON), TAG(CENTER), TAG(DETAILS),
TAG(DIR), TAG(DIV), TAG(DL), TAG(FIELDSET),
TAG(FIGCAPTION), TAG(FIGURE), TAG(FOOTER), TAG(HEADER),
TAG(HGROUP), TAG(LISTING), TAG(MAIN), TAG(MENU), TAG(NAV),
TAG(OL), TAG(PRE), TAG(SECTION), TAG(SUMMARY), TAG(UL)})) {
GumboTag tag = token->v.end_tag;
if (!has_an_element_in_scope(parser, tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, token->v.end_tag);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_FORM)) {
if (has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
if (!has_an_element_in_scope(parser, GUMBO_TAG_FORM)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
bool success = true;
generate_implied_end_tags(parser, GUMBO_TAG_LAST);
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_FORM)) {
parser_add_parse_error(parser, token);
return false;
}
while (!node_html_tag_is(pop_current_node(parser), GUMBO_TAG_FORM))
;
return success;
} else {
bool result = true;
const GumboNode* node = state->_form_element;
assert(!node || node->type == GUMBO_NODE_ELEMENT);
state->_form_element = NULL;
if (!node || !has_node_in_scope(parser, node)) {
gumbo_debug("Closing an unopened form.\n");
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
// This differs from implicitly_close_tags because we remove *only* the
// <form> element; other nodes are left in scope.
generate_implied_end_tags(parser, GUMBO_TAG_LAST);
if (get_current_node(parser) != node) {
parser_add_parse_error(parser, token);
result = false;
}
GumboVector* open_elements = &state->_open_elements;
int index = gumbo_vector_index_of(open_elements, node);
assert(index >= 0);
gumbo_vector_remove_at(parser, index, open_elements);
return result;
}
} else if (tag_is(token, kEndTag, GUMBO_TAG_P)) {
if (!has_an_element_in_button_scope(parser, GUMBO_TAG_P)) {
parser_add_parse_error(parser, token);
// reconstruct_active_formatting_elements(parser);
insert_element_of_tag_type(
parser, GUMBO_TAG_P, GUMBO_INSERTION_CONVERTED_FROM_END_TAG);
state->_reprocess_current_token = true;
return false;
}
return implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, GUMBO_TAG_P);
} else if (tag_is(token, kEndTag, GUMBO_TAG_LI)) {
if (!has_an_element_in_list_scope(parser, GUMBO_TAG_LI)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
return implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, GUMBO_TAG_LI);
} else if (tag_in(token, kEndTag, (gumbo_tagset){TAG(DD), TAG(DT)})) {
assert(token->type == GUMBO_TOKEN_END_TAG);
GumboTag token_tag = token->v.end_tag;
if (!has_an_element_in_scope(parser, token_tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
return implicitly_close_tags(
parser, token, GUMBO_NAMESPACE_HTML, token_tag);
} else if (tag_in(token, kEndTag, (gumbo_tagset){TAG(H1), TAG(H2), TAG(H3),
TAG(H4), TAG(H5), TAG(H6)})) {
if (!has_an_element_in_scope_with_tagname(
parser, 6, (GumboTag[]){GUMBO_TAG_H1, GUMBO_TAG_H2, GUMBO_TAG_H3,
GUMBO_TAG_H4, GUMBO_TAG_H5, GUMBO_TAG_H6})) {
// No heading open; ignore the token entirely.
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
generate_implied_end_tags(parser, GUMBO_TAG_LAST);
const GumboNode* current_node = get_current_node(parser);
bool success = node_html_tag_is(current_node, token->v.end_tag);
if (!success) {
// There're children of the heading currently open; close them below and
// record a parse error.
// TODO(jdtang): Add a way to distinguish this error case from the one
// above.
parser_add_parse_error(parser, token);
}
do {
current_node = pop_current_node(parser);
} while (!node_tag_in_set(
current_node, (gumbo_tagset){TAG(H1), TAG(H2), TAG(H3),
TAG(H4), TAG(H5), TAG(H6)}));
return success;
}
} else if (tag_is(token, kStartTag, GUMBO_TAG_A)) {
bool success = true;
int last_a;
int has_matching_a = find_last_anchor_index(parser, &last_a);
if (has_matching_a) {
assert(has_matching_a == 1);
parser_add_parse_error(parser, token);
adoption_agency_algorithm(parser, token, GUMBO_TAG_A);
// The adoption agency algorithm usually removes all instances of <a>
// from the list of active formatting elements, but in case it doesn't,
// we're supposed to do this. (The conditions where it might not are
// listed in the spec.)
if (find_last_anchor_index(parser, &last_a)) {
void* last_element = gumbo_vector_remove_at(
parser, last_a, &state->_active_formatting_elements);
gumbo_vector_remove(parser, last_element, &state->_open_elements);
}
success = false;
}
reconstruct_active_formatting_elements(parser);
add_formatting_element(parser, insert_element_from_token(parser, token));
return success;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(B), TAG(BIG), TAG(CODE), TAG(EM), TAG(FONT),
TAG(I), TAG(S), TAG(SMALL), TAG(STRIKE), TAG(STRONG),
TAG(TT), TAG(U)})) {
reconstruct_active_formatting_elements(parser);
add_formatting_element(parser, insert_element_from_token(parser, token));
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOBR)) {
bool result = true;
reconstruct_active_formatting_elements(parser);
if (has_an_element_in_scope(parser, GUMBO_TAG_NOBR)) {
result = false;
parser_add_parse_error(parser, token);
adoption_agency_algorithm(parser, token, GUMBO_TAG_NOBR);
reconstruct_active_formatting_elements(parser);
}
insert_element_from_token(parser, token);
add_formatting_element(parser, get_current_node(parser));
return result;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(A), TAG(B), TAG(BIG), TAG(CODE), TAG(EM),
TAG(FONT), TAG(I), TAG(NOBR), TAG(S), TAG(SMALL),
TAG(STRIKE), TAG(STRONG), TAG(TT), TAG(U)})) {
return adoption_agency_algorithm(parser, token, token->v.end_tag);
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(APPLET), TAG(MARQUEE), TAG(OBJECT)})) {
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
add_formatting_element(parser, &kActiveFormattingScopeMarker);
set_frameset_not_ok(parser);
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(APPLET), TAG(MARQUEE), TAG(OBJECT)})) {
GumboTag token_tag = token->v.end_tag;
if (!has_an_element_in_table_scope(parser, token_tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
implicitly_close_tags(parser, token, GUMBO_NAMESPACE_HTML, token_tag);
clear_active_formatting_elements(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TABLE)) {
if (get_document_node(parser)->v.document.doc_type_quirks_mode !=
GUMBO_DOCTYPE_QUIRKS) {
maybe_implicitly_close_p_tag(parser, token);
}
insert_element_from_token(parser, token);
set_frameset_not_ok(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(AREA), TAG(BR), TAG(EMBED), TAG(IMG),
TAG(IMAGE), TAG(KEYGEN), TAG(WBR)})) {
bool success = true;
if (tag_is(token, kStartTag, GUMBO_TAG_IMAGE)) {
success = false;
parser_add_parse_error(parser, token);
token->v.start_tag.tag = GUMBO_TAG_IMG;
}
reconstruct_active_formatting_elements(parser);
GumboNode* node = insert_element_from_token(parser, token);
if (tag_is(token, kStartTag, GUMBO_TAG_IMAGE)) {
success = false;
parser_add_parse_error(parser, token);
node->v.element.tag = GUMBO_TAG_IMG;
node->parse_flags |= GUMBO_INSERTION_FROM_IMAGE;
}
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
set_frameset_not_ok(parser);
return success;
} else if (tag_is(token, kStartTag, GUMBO_TAG_INPUT)) {
if (!attribute_matches(&token->v.start_tag.attributes, "type", "hidden")) {
// Must be before the element is inserted, as that takes ownership of the
// token's attribute vector.
set_frameset_not_ok(parser);
}
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(PARAM), TAG(SOURCE), TAG(TRACK)})) {
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HR)) {
bool result = maybe_implicitly_close_p_tag(parser, token);
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
set_frameset_not_ok(parser);
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_ISINDEX)) {
parser_add_parse_error(parser, token);
if (parser->_parser_state->_form_element != NULL &&
!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
ignore_token(parser);
return false;
}
acknowledge_self_closing_tag(parser);
maybe_implicitly_close_p_tag(parser, token);
set_frameset_not_ok(parser);
GumboVector* token_attrs = &token->v.start_tag.attributes;
GumboAttribute* prompt_attr = gumbo_get_attribute(token_attrs, "prompt");
GumboAttribute* action_attr = gumbo_get_attribute(token_attrs, "action");
GumboAttribute* name_attr = gumbo_get_attribute(token_attrs, "name");
GumboNode* form = insert_element_of_tag_type(
parser, GUMBO_TAG_FORM, GUMBO_INSERTION_FROM_ISINDEX);
if (!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
parser->_parser_state->_form_element = form;
}
if (action_attr) {
gumbo_vector_add(parser, action_attr, &form->v.element.attributes);
}
insert_element_of_tag_type(
parser, GUMBO_TAG_HR, GUMBO_INSERTION_FROM_ISINDEX);
pop_current_node(parser); // <hr>
insert_element_of_tag_type(
parser, GUMBO_TAG_LABEL, GUMBO_INSERTION_FROM_ISINDEX);
TextNodeBufferState* text_state = &parser->_parser_state->_text_node;
text_state->_start_original_text = token->original_text.data;
text_state->_start_position = token->position;
text_state->_type = GUMBO_NODE_TEXT;
if (prompt_attr) {
size_t prompt_attr_length = strlen(prompt_attr->value);
gumbo_string_buffer_destroy(parser, &text_state->_buffer);
text_state->_buffer.data = gumbo_copy_stringz(parser, prompt_attr->value);
text_state->_buffer.length = prompt_attr_length;
text_state->_buffer.capacity = prompt_attr_length + 1;
gumbo_destroy_attribute(parser, prompt_attr);
} else {
GumboStringPiece prompt_text =
GUMBO_STRING("This is a searchable index. Enter search keywords: ");
gumbo_string_buffer_append_string(
parser, &prompt_text, &text_state->_buffer);
}
GumboNode* input = insert_element_of_tag_type(
parser, GUMBO_TAG_INPUT, GUMBO_INSERTION_FROM_ISINDEX);
for (unsigned int i = 0; i < token_attrs->length; ++i) {
GumboAttribute* attr = token_attrs->data[i];
if (attr != prompt_attr && attr != action_attr && attr != name_attr) {
gumbo_vector_add(parser, attr, &input->v.element.attributes);
}
token_attrs->data[i] = NULL;
}
// All attributes have been successfully transferred and nulled out at this
// point, so the call to ignore_token will free the memory for it without
// touching the attributes.
ignore_token(parser);
// The name attribute, if present, should be destroyed since it's ignored
// when copying over. The action attribute should be kept since it's moved
// to the form.
if (name_attr) {
gumbo_destroy_attribute(parser, name_attr);
}
GumboAttribute* name =
gumbo_parser_allocate(parser, sizeof(GumboAttribute));
GumboStringPiece name_str = GUMBO_STRING("name");
GumboStringPiece isindex_str = GUMBO_STRING("isindex");
name->attr_namespace = GUMBO_ATTR_NAMESPACE_NONE;
name->name = gumbo_copy_stringz(parser, "name");
name->value = gumbo_copy_stringz(parser, "isindex");
name->original_name = name_str;
name->original_value = isindex_str;
name->name_start = kGumboEmptySourcePosition;
name->name_end = kGumboEmptySourcePosition;
name->value_start = kGumboEmptySourcePosition;
name->value_end = kGumboEmptySourcePosition;
gumbo_vector_add(parser, name, &input->v.element.attributes);
pop_current_node(parser); // <input>
pop_current_node(parser); // <label>
insert_element_of_tag_type(
parser, GUMBO_TAG_HR, GUMBO_INSERTION_FROM_ISINDEX);
pop_current_node(parser); // <hr>
pop_current_node(parser); // <form>
if (!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
parser->_parser_state->_form_element = NULL;
}
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TEXTAREA)) {
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RCDATA);
parser->_parser_state->_ignore_next_linefeed = true;
set_frameset_not_ok(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_XMP)) {
bool result = maybe_implicitly_close_p_tag(parser, token);
reconstruct_active_formatting_elements(parser);
set_frameset_not_ok(parser);
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RAWTEXT);
return result;
} else if (tag_is(token, kStartTag, GUMBO_TAG_IFRAME)) {
set_frameset_not_ok(parser);
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RAWTEXT);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOEMBED)) {
run_generic_parsing_algorithm(parser, token, GUMBO_LEX_RAWTEXT);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_SELECT)) {
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
set_frameset_not_ok(parser);
GumboInsertionMode state = parser->_parser_state->_insertion_mode;
if (state == GUMBO_INSERTION_MODE_IN_TABLE ||
state == GUMBO_INSERTION_MODE_IN_CAPTION ||
state == GUMBO_INSERTION_MODE_IN_TABLE_BODY ||
state == GUMBO_INSERTION_MODE_IN_ROW ||
state == GUMBO_INSERTION_MODE_IN_CELL) {
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_SELECT_IN_TABLE);
} else {
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_SELECT);
}
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(OPTION), TAG(OPTGROUP)})) {
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTION)) {
pop_current_node(parser);
}
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(RB), TAG(RP), TAG(RT), TAG(RTC)})) {
bool success = true;
GumboTag exception =
tag_in(token, kStartTag, (gumbo_tagset){TAG(RT), TAG(RP)})
? GUMBO_TAG_RTC
: GUMBO_TAG_LAST;
if (has_an_element_in_scope(parser, GUMBO_TAG_RUBY)) {
generate_implied_end_tags(parser, exception);
}
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_RUBY) &&
!(exception == GUMBO_TAG_LAST ||
node_html_tag_is(get_current_node(parser), GUMBO_TAG_RTC))) {
parser_add_parse_error(parser, token);
success = false;
}
insert_element_from_token(parser, token);
return success;
} else if (tag_is(token, kEndTag, GUMBO_TAG_BR)) {
parser_add_parse_error(parser, token);
reconstruct_active_formatting_elements(parser);
insert_element_of_tag_type(
parser, GUMBO_TAG_BR, GUMBO_INSERTION_CONVERTED_FROM_END_TAG);
pop_current_node(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_MATH)) {
reconstruct_active_formatting_elements(parser);
adjust_mathml_attributes(parser, token);
adjust_foreign_attributes(parser, token);
insert_foreign_element(parser, token, GUMBO_NAMESPACE_MATHML);
if (token->v.start_tag.is_self_closing) {
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
}
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_SVG)) {
reconstruct_active_formatting_elements(parser);
adjust_svg_attributes(parser, token);
adjust_foreign_attributes(parser, token);
insert_foreign_element(parser, token, GUMBO_NAMESPACE_SVG);
if (token->v.start_tag.is_self_closing) {
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
}
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(COL), TAG(COLGROUP),
TAG(FRAME), TAG(HEAD), TAG(TBODY), TAG(TD), TAG(TFOOT),
TAG(TH), TAG(THEAD), TAG(TR)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_START_TAG) {
reconstruct_active_formatting_elements(parser);
insert_element_from_token(parser, token);
return true;
} else {
assert(token->type == GUMBO_TOKEN_END_TAG);
GumboTag end_tag = token->v.end_tag;
assert(state->_open_elements.length > 0);
assert(node_html_tag_is(state->_open_elements.data[0], GUMBO_TAG_HTML));
// Walk up the stack of open elements until we find one that either:
// a) Matches the tag name we saw
// b) Is in the "special" category.
// If we see a), implicitly close everything up to and including it. If we
// see b), then record a parse error, don't close anything (except the
// implied end tags) and ignore the end tag token.
for (int i = state->_open_elements.length; --i >= 0;) {
const GumboNode* node = state->_open_elements.data[i];
if (node_html_tag_is(node, end_tag)) {
generate_implied_end_tags(parser, end_tag);
// TODO(jdtang): Do I need to add a parse error here? The condition in
// the spec seems like it's the inverse of the loop condition above, and
// so would never fire.
while (node != pop_current_node(parser))
; // Pop everything.
return true;
} else if (is_special_node(node)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
}
// <html> is in the special category, so we should never get here.
assert(0);
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-incdata
static bool handle_text(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
} else {
// We provide only bare-bones script handling that doesn't involve any of
// the parser-pause/already-started/script-nesting flags or re-entrant
// invocations of the tokenizer. Because the intended usage of this library
// is mostly for templating, refactoring, and static-analysis libraries, we
// provide the script body as a text-node child of the <script> element.
// This behavior doesn't support document.write of partial HTML elements,
// but should be adequate for almost all other scripting support.
if (token->type == GUMBO_TOKEN_EOF) {
parser_add_parse_error(parser, token);
parser->_parser_state->_reprocess_current_token = true;
}
pop_current_node(parser);
set_insertion_mode(parser, parser->_parser_state->_original_insertion_mode);
}
return true;
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-intable
static bool handle_in_table(GumboParser* parser, GumboToken* token) {
GumboParserState* state = parser->_parser_state;
if (token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_WHITESPACE) {
// The "pending table character tokens" list described in the spec is
// nothing more than the TextNodeBufferState. We accumulate text tokens as
// normal, except that when we go to flush them in the handle_in_table_text,
// we set _foster_parent_insertions if there're non-whitespace characters in
// the buffer.
assert(state->_text_node._buffer.length == 0);
state->_original_insertion_mode = state->_insertion_mode;
state->_reprocess_current_token = true;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_TEXT);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_CAPTION)) {
clear_stack_to_table_context(parser);
add_formatting_element(parser, &kActiveFormattingScopeMarker);
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_CAPTION);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_COLGROUP)) {
clear_stack_to_table_context(parser);
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_COLUMN_GROUP);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_COL)) {
clear_stack_to_table_context(parser);
insert_element_of_tag_type(
parser, GUMBO_TAG_COLGROUP, GUMBO_INSERTION_IMPLIED);
parser->_parser_state->_reprocess_current_token = true;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_COLUMN_GROUP);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(TBODY), TAG(TFOOT), TAG(THEAD), TAG(TD),
TAG(TH), TAG(TR)})) {
clear_stack_to_table_context(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
if (tag_in(token, kStartTag, (gumbo_tagset){TAG(TD), TAG(TH), TAG(TR)})) {
insert_element_of_tag_type(
parser, GUMBO_TAG_TBODY, GUMBO_INSERTION_IMPLIED);
state->_reprocess_current_token = true;
} else {
insert_element_from_token(parser, token);
}
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TABLE)) {
parser_add_parse_error(parser, token);
if (close_table(parser)) {
parser->_parser_state->_reprocess_current_token = true;
} else {
ignore_token(parser);
}
return false;
} else if (tag_is(token, kEndTag, GUMBO_TAG_TABLE)) {
if (!close_table(parser)) {
parser_add_parse_error(parser, token);
return false;
}
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(CAPTION), TAG(COL),
TAG(COLGROUP), TAG(HTML), TAG(TBODY), TAG(TD), TAG(TFOOT),
TAG(TH), TAG(THEAD), TAG(TR)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(STYLE), TAG(SCRIPT), TAG(TEMPLATE)}) ||
(tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE))) {
return handle_in_head(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_INPUT) &&
attribute_matches(
&token->v.start_tag.attributes, "type", "hidden")) {
parser_add_parse_error(parser, token);
insert_element_from_token(parser, token);
pop_current_node(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_FORM)) {
parser_add_parse_error(parser, token);
if (state->_form_element || has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
ignore_token(parser);
return false;
}
state->_form_element = insert_element_from_token(parser, token);
pop_current_node(parser);
return false;
} else if (token->type == GUMBO_TOKEN_EOF) {
return handle_in_body(parser, token);
} else {
parser_add_parse_error(parser, token);
state->_foster_parent_insertions = true;
bool result = handle_in_body(parser, token);
state->_foster_parent_insertions = false;
return result;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-intabletext
static bool handle_in_table_text(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_NULL) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else {
GumboParserState* state = parser->_parser_state;
GumboStringBuffer* buffer = &state->_text_node._buffer;
// Can't use strspn for this because GumboStringBuffers are not
// null-terminated.
// Note that TextNodeBuffer may contain UTF-8 characters, but the presence
// of any one byte that is not whitespace means we flip the flag, so this
// loop is still valid.
for (unsigned int i = 0; i < buffer->length; ++i) {
if (!isspace((unsigned char) buffer->data[i]) ||
buffer->data[i] == '\v') {
state->_foster_parent_insertions = true;
reconstruct_active_formatting_elements(parser);
break;
}
}
maybe_flush_text_node_buffer(parser);
state->_foster_parent_insertions = false;
state->_reprocess_current_token = true;
state->_insertion_mode = state->_original_insertion_mode;
return true;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-incaption
static bool handle_in_caption(GumboParser* parser, GumboToken* token) {
if (tag_is(token, kEndTag, GUMBO_TAG_CAPTION)) {
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_CAPTION)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
generate_implied_end_tags(parser, GUMBO_TAG_LAST);
bool result = true;
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_CAPTION)) {
parser_add_parse_error(parser, token);
}
while (!node_html_tag_is(pop_current_node(parser), GUMBO_TAG_CAPTION))
;
clear_active_formatting_elements(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
return result;
}
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(COL), TAG(COLGROUP),
TAG(TBODY), TAG(TD), TAG(TFOOT), TAG(TH), TAG(THEAD),
TAG(TR)}) ||
(tag_is(token, kEndTag, GUMBO_TAG_TABLE))) {
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_CAPTION)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
while (!node_html_tag_is(pop_current_node(parser), GUMBO_TAG_CAPTION))
;
clear_active_formatting_elements(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
parser->_parser_state->_reprocess_current_token = true;
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(COL), TAG(COLGROUP), TAG(HTML),
TAG(TBODY), TAG(TD), TAG(TFOOT), TAG(TH), TAG(THEAD),
TAG(TR)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
return handle_in_body(parser, token);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-incolgroup
static bool handle_in_column_group(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_COL)) {
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_COLGROUP)) {
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_COLGROUP)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
return false;
} else if (tag_is(token, kEndTag, GUMBO_TAG_COL)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TEMPLATE) ||
tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
return handle_in_head(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
return handle_in_body(parser, token);
} else {
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_COLGROUP)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-intbody
static bool handle_in_table_body(GumboParser* parser, GumboToken* token) {
if (tag_is(token, kStartTag, GUMBO_TAG_TR)) {
clear_stack_to_table_body_context(parser);
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_ROW);
return true;
} else if (tag_in(token, kStartTag, (gumbo_tagset){TAG(TD), TAG(TH)})) {
parser_add_parse_error(parser, token);
clear_stack_to_table_body_context(parser);
insert_element_of_tag_type(parser, GUMBO_TAG_TR, GUMBO_INSERTION_IMPLIED);
parser->_parser_state->_reprocess_current_token = true;
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_ROW);
return false;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(TBODY), TAG(TFOOT), TAG(THEAD)})) {
if (!has_an_element_in_table_scope(parser, token->v.end_tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
clear_stack_to_table_body_context(parser);
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
return true;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(COL), TAG(COLGROUP),
TAG(TBODY), TAG(TFOOT), TAG(THEAD)}) ||
tag_is(token, kEndTag, GUMBO_TAG_TABLE)) {
if (!(has_an_element_in_table_scope(parser, GUMBO_TAG_TBODY) ||
has_an_element_in_table_scope(parser, GUMBO_TAG_THEAD) ||
has_an_element_in_table_scope(parser, GUMBO_TAG_TFOOT))) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
clear_stack_to_table_body_context(parser);
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
parser->_parser_state->_reprocess_current_token = true;
return true;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(CAPTION), TAG(COL), TAG(TR),
TAG(COLGROUP), TAG(HTML), TAG(TD), TAG(TH)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
return handle_in_table(parser, token);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-intr
static bool handle_in_row(GumboParser* parser, GumboToken* token) {
if (tag_in(token, kStartTag, (gumbo_tagset){TAG(TH), TAG(TD)})) {
clear_stack_to_table_row_context(parser);
insert_element_from_token(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_CELL);
add_formatting_element(parser, &kActiveFormattingScopeMarker);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_TR)) {
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_TR)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
clear_stack_to_table_row_context(parser);
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
return true;
}
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(COL), TAG(COLGROUP),
TAG(TBODY), TAG(TFOOT), TAG(THEAD), TAG(TR)}) ||
tag_is(token, kEndTag, GUMBO_TAG_TABLE)) {
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_TR)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
clear_stack_to_table_row_context(parser);
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(TBODY), TAG(TFOOT), TAG(THEAD)})) {
if (!has_an_element_in_table_scope(parser, token->v.end_tag) ||
(!has_an_element_in_table_scope(parser, GUMBO_TAG_TR))) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
clear_stack_to_table_row_context(parser);
pop_current_node(parser);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
parser->_parser_state->_reprocess_current_token = true;
return true;
}
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(BODY), TAG(CAPTION), TAG(COL),
TAG(COLGROUP), TAG(HTML), TAG(TD), TAG(TH)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else {
return handle_in_table(parser, token);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-intd
static bool handle_in_cell(GumboParser* parser, GumboToken* token) {
if (tag_in(token, kEndTag, (gumbo_tagset){TAG(TD), TAG(TH)})) {
GumboTag token_tag = token->v.end_tag;
if (!has_an_element_in_table_scope(parser, token_tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
return close_table_cell(parser, token, token_tag);
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(COL), TAG(COLGROUP),
TAG(TBODY), TAG(TD), TAG(TFOOT), TAG(TH), TAG(THEAD),
TAG(TR)})) {
gumbo_debug("Handling <td> in cell.\n");
if (!has_an_element_in_table_scope(parser, GUMBO_TAG_TH) &&
!has_an_element_in_table_scope(parser, GUMBO_TAG_TD)) {
gumbo_debug("Bailing out because there's no <td> or <th> in scope.\n");
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
parser->_parser_state->_reprocess_current_token = true;
return close_current_cell(parser, token);
} else if (tag_in(token, kEndTag, (gumbo_tagset){TAG(BODY), TAG(CAPTION),
TAG(COL), TAG(COLGROUP), TAG(HTML)})) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_in(token, kEndTag, (gumbo_tagset){TAG(TABLE), TAG(TBODY),
TAG(TFOOT), TAG(THEAD), TAG(TR)})) {
if (!has_an_element_in_table_scope(parser, token->v.end_tag)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
parser->_parser_state->_reprocess_current_token = true;
return close_current_cell(parser, token);
} else {
return handle_in_body(parser, token);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inselect
static bool handle_in_select(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_NULL) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_OPTION)) {
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTION)) {
pop_current_node(parser);
}
insert_element_from_token(parser, token);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_OPTGROUP)) {
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTION)) {
pop_current_node(parser);
}
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTGROUP)) {
pop_current_node(parser);
}
insert_element_from_token(parser, token);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_OPTGROUP)) {
GumboVector* open_elements = &parser->_parser_state->_open_elements;
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTION) &&
node_html_tag_is(open_elements->data[open_elements->length - 2],
GUMBO_TAG_OPTGROUP)) {
pop_current_node(parser);
}
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTGROUP)) {
pop_current_node(parser);
return true;
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
} else if (tag_is(token, kEndTag, GUMBO_TAG_OPTION)) {
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_OPTION)) {
pop_current_node(parser);
return true;
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
} else if (tag_is(token, kEndTag, GUMBO_TAG_SELECT)) {
if (!has_an_element_in_select_scope(parser, GUMBO_TAG_SELECT)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
close_current_select(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_SELECT)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
if (has_an_element_in_select_scope(parser, GUMBO_TAG_SELECT)) {
close_current_select(parser);
}
return false;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(INPUT), TAG(KEYGEN), TAG(TEXTAREA)})) {
parser_add_parse_error(parser, token);
if (!has_an_element_in_select_scope(parser, GUMBO_TAG_SELECT)) {
ignore_token(parser);
} else {
close_current_select(parser);
parser->_parser_state->_reprocess_current_token = true;
}
return false;
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(SCRIPT), TAG(TEMPLATE)}) ||
tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
return handle_in_head(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
return handle_in_body(parser, token);
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inselectintable
static bool handle_in_select_in_table(GumboParser* parser, GumboToken* token) {
if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(CAPTION), TAG(TABLE), TAG(TBODY), TAG(TFOOT),
TAG(THEAD), TAG(TR), TAG(TD), TAG(TH)})) {
parser_add_parse_error(parser, token);
close_current_select(parser);
parser->_parser_state->_reprocess_current_token = true;
return false;
} else if (tag_in(token, kEndTag,
(gumbo_tagset){TAG(CAPTION), TAG(TABLE), TAG(TBODY),
TAG(TFOOT), TAG(THEAD), TAG(TR), TAG(TD), TAG(TH)})) {
parser_add_parse_error(parser, token);
if (!has_an_element_in_table_scope(parser, token->v.end_tag)) {
ignore_token(parser);
return false;
} else {
close_current_select(parser);
// close_current_select already does the
// reset_insertion_mode_appropriately
// reset_insertion_mode_appropriately(parser);
parser->_parser_state->_reprocess_current_token = true;
return false;
}
} else {
return handle_in_select(parser, token);
}
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#parsing-main-intemplate
static bool handle_in_template(GumboParser* parser, GumboToken* token) {
GumboParserState* state = parser->_parser_state;
if (token->type == GUMBO_TOKEN_WHITESPACE ||
token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_COMMENT || token->type == GUMBO_TOKEN_NULL ||
token->type == GUMBO_TOKEN_DOCTYPE) {
return handle_in_body(parser, token);
} else if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(BASE), TAG(BASEFONT), TAG(BGSOUND),
TAG(LINK), TAG(META), TAG(NOFRAMES), TAG(SCRIPT),
TAG(STYLE), TAG(TEMPLATE), TAG(TITLE)}) ||
tag_is(token, kEndTag, GUMBO_TAG_TEMPLATE)) {
return handle_in_head(parser, token);
} else if (tag_in(
token, kStartTag, (gumbo_tagset){TAG(CAPTION), TAG(COLGROUP),
TAG(TBODY), TAG(TFOOT), TAG(THEAD)})) {
pop_template_insertion_mode(parser);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE);
state->_reprocess_current_token = true;
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_COL)) {
pop_template_insertion_mode(parser);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_COLUMN_GROUP);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_COLUMN_GROUP);
state->_reprocess_current_token = true;
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_TR)) {
pop_template_insertion_mode(parser);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TABLE_BODY);
state->_reprocess_current_token = true;
return true;
} else if (tag_in(token, kStartTag, (gumbo_tagset){TAG(TD), TAG(TH)})) {
pop_template_insertion_mode(parser);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_ROW);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_ROW);
state->_reprocess_current_token = true;
return true;
} else if (token->type == GUMBO_TOKEN_START_TAG) {
pop_template_insertion_mode(parser);
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
state->_reprocess_current_token = true;
return true;
} else if (token->type == GUMBO_TOKEN_END_TAG) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (token->type == GUMBO_TOKEN_EOF) {
if (!has_open_element(parser, GUMBO_TAG_TEMPLATE)) {
// Stop parsing.
return true;
}
parser_add_parse_error(parser, token);
while (!node_html_tag_is(pop_current_node(parser), GUMBO_TAG_TEMPLATE))
;
clear_active_formatting_elements(parser);
pop_template_insertion_mode(parser);
reset_insertion_mode_appropriately(parser);
state->_reprocess_current_token = true;
return false;
} else {
assert(0);
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-afterbody
static bool handle_after_body(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_WHITESPACE ||
tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (token->type == GUMBO_TOKEN_COMMENT) {
GumboNode* html_node = parser->_output->root;
assert(html_node != NULL);
append_comment_node(parser, html_node, token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_is(token, kEndTag, GUMBO_TAG_HTML)) {
/* fragment case: ignore the closing HTML token */
if (is_fragment_parser(parser)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_AFTER_BODY);
GumboNode* html = parser->_parser_state->_open_elements.data[0];
assert(node_html_tag_is(html, GUMBO_TAG_HTML));
record_end_of_element(
parser->_parser_state->_current_token, &html->v.element);
return true;
} else if (token->type == GUMBO_TOKEN_EOF) {
return true;
} else {
parser_add_parse_error(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
parser->_parser_state->_reprocess_current_token = true;
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inframeset
static bool handle_in_frameset(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kStartTag, GUMBO_TAG_FRAMESET)) {
insert_element_from_token(parser, token);
return true;
} else if (tag_is(token, kEndTag, GUMBO_TAG_FRAMESET)) {
if (node_html_tag_is(get_current_node(parser), GUMBO_TAG_HTML)) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
pop_current_node(parser);
if (!is_fragment_parser(parser) &&
!node_html_tag_is(get_current_node(parser), GUMBO_TAG_FRAMESET)) {
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_FRAMESET);
}
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_FRAME)) {
insert_element_from_token(parser, token);
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOFRAMES)) {
return handle_in_head(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
if (!node_html_tag_is(get_current_node(parser), GUMBO_TAG_HTML)) {
parser_add_parse_error(parser, token);
return false;
}
return true;
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-afterframeset
static bool handle_after_frameset(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_WHITESPACE) {
insert_text_token(parser, token);
return true;
} else if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_current_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE) {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
} else if (tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (tag_is(token, kEndTag, GUMBO_TAG_HTML)) {
GumboNode* html = parser->_parser_state->_open_elements.data[0];
assert(node_html_tag_is(html, GUMBO_TAG_HTML));
record_end_of_element(
parser->_parser_state->_current_token, &html->v.element);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_AFTER_AFTER_FRAMESET);
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOFRAMES)) {
return handle_in_head(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
return true;
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-after-after-body-insertion-mode
static bool handle_after_after_body(GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_document_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE ||
token->type == GUMBO_TOKEN_WHITESPACE ||
tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
return true;
} else {
parser_add_parse_error(parser, token);
set_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_BODY);
parser->_parser_state->_reprocess_current_token = true;
return false;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#the-after-after-frameset-insertion-mode
static bool handle_after_after_frameset(
GumboParser* parser, GumboToken* token) {
if (token->type == GUMBO_TOKEN_COMMENT) {
append_comment_node(parser, get_document_node(parser), token);
return true;
} else if (token->type == GUMBO_TOKEN_DOCTYPE ||
token->type == GUMBO_TOKEN_WHITESPACE ||
tag_is(token, kStartTag, GUMBO_TAG_HTML)) {
return handle_in_body(parser, token);
} else if (token->type == GUMBO_TOKEN_EOF) {
return true;
} else if (tag_is(token, kStartTag, GUMBO_TAG_NOFRAMES)) {
return handle_in_head(parser, token);
} else {
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
}
}
// Function pointers for each insertion mode. Keep in sync with
// insertion_mode.h.
typedef bool (*TokenHandler)(GumboParser* parser, GumboToken* token);
static const TokenHandler kTokenHandlers[] = {handle_initial,
handle_before_html, handle_before_head, handle_in_head,
handle_in_head_noscript, handle_after_head, handle_in_body, handle_text,
handle_in_table, handle_in_table_text, handle_in_caption,
handle_in_column_group, handle_in_table_body, handle_in_row, handle_in_cell,
handle_in_select, handle_in_select_in_table, handle_in_template,
handle_after_body, handle_in_frameset, handle_after_frameset,
handle_after_after_body, handle_after_after_frameset};
static bool handle_html_content(GumboParser* parser, GumboToken* token) {
return kTokenHandlers[(unsigned int) parser->_parser_state->_insertion_mode](
parser, token);
}
// http://www.whatwg.org/specs/web-apps/current-work/complete/tokenization.html#parsing-main-inforeign
static bool handle_in_foreign_content(GumboParser* parser, GumboToken* token) {
gumbo_debug("Handling foreign content");
switch (token->type) {
case GUMBO_TOKEN_NULL:
parser_add_parse_error(parser, token);
token->v.character = kUtf8ReplacementChar;
insert_text_token(parser, token);
return false;
case GUMBO_TOKEN_WHITESPACE:
insert_text_token(parser, token);
return true;
case GUMBO_TOKEN_CDATA:
case GUMBO_TOKEN_CHARACTER:
insert_text_token(parser, token);
set_frameset_not_ok(parser);
return true;
case GUMBO_TOKEN_COMMENT:
append_comment_node(parser, get_current_node(parser), token);
return true;
case GUMBO_TOKEN_DOCTYPE:
parser_add_parse_error(parser, token);
ignore_token(parser);
return false;
default:
// Fall through to the if-statements below.
break;
}
// Order matters for these clauses.
if (tag_in(token, kStartTag,
(gumbo_tagset){TAG(B), TAG(BIG), TAG(BLOCKQUOTE), TAG(BODY), TAG(BR),
TAG(CENTER), TAG(CODE), TAG(DD), TAG(DIV), TAG(DL), TAG(DT),
TAG(EM), TAG(EMBED), TAG(H1), TAG(H2), TAG(H3), TAG(H4), TAG(H5),
TAG(H6), TAG(HEAD), TAG(HR), TAG(I), TAG(IMG), TAG(LI),
TAG(LISTING), TAG(MENU), TAG(META), TAG(NOBR), TAG(OL), TAG(P),
TAG(PRE), TAG(RUBY), TAG(S), TAG(SMALL), TAG(SPAN), TAG(STRONG),
TAG(STRIKE), TAG(SUB), TAG(SUP), TAG(TABLE), TAG(TT), TAG(U),
TAG(UL), TAG(VAR)}) ||
(tag_is(token, kStartTag, GUMBO_TAG_FONT) &&
(token_has_attribute(token, "color") ||
token_has_attribute(token, "face") ||
token_has_attribute(token, "size")))) {
/* Parse error */
parser_add_parse_error(parser, token);
/*
* Fragment case: If the parser was originally created for the HTML
* fragment parsing algorithm, then act as described in the "any other
* start tag" entry below.
*/
if (!is_fragment_parser(parser)) {
do {
pop_current_node(parser);
} while (!(is_mathml_integration_point(get_current_node(parser)) ||
is_html_integration_point(get_current_node(parser)) ||
get_current_node(parser)->v.element.tag_namespace ==
GUMBO_NAMESPACE_HTML));
parser->_parser_state->_reprocess_current_token = true;
return false;
}
assert(token->type == GUMBO_TOKEN_START_TAG);
}
if (token->type == GUMBO_TOKEN_START_TAG) {
const GumboNamespaceEnum current_namespace =
get_adjusted_current_node(parser)->v.element.tag_namespace;
if (current_namespace == GUMBO_NAMESPACE_MATHML) {
adjust_mathml_attributes(parser, token);
}
if (current_namespace == GUMBO_NAMESPACE_SVG) {
// Tag adjustment is left to the gumbo_normalize_svg_tagname helper
// function.
adjust_svg_attributes(parser, token);
}
adjust_foreign_attributes(parser, token);
insert_foreign_element(parser, token, current_namespace);
if (token->v.start_tag.is_self_closing) {
pop_current_node(parser);
acknowledge_self_closing_tag(parser);
}
return true;
// </script> tags are handled like any other end tag, putting the script's
// text into a text node child and closing the current node.
} else {
assert(token->type == GUMBO_TOKEN_END_TAG);
GumboNode* node = get_current_node(parser);
assert(node != NULL);
GumboStringPiece token_tagname = token->original_text;
GumboStringPiece node_tagname = node->v.element.original_tag;
gumbo_tag_from_original_text(&token_tagname);
gumbo_tag_from_original_text(&node_tagname);
bool is_success = true;
if (!gumbo_string_equals_ignore_case(&node_tagname, &token_tagname)) {
parser_add_parse_error(parser, token);
is_success = false;
}
int i = parser->_parser_state->_open_elements.length;
for (--i; i > 0;) {
// Here we move up the stack until we find an HTML element (in which
// case we do nothing) or we find the element that we're about to
// close (in which case we pop everything we've seen until that
// point.)
gumbo_debug("Foreign %.*s node at %d.\n", node_tagname.length,
node_tagname.data, i);
if (gumbo_string_equals_ignore_case(&node_tagname, &token_tagname)) {
gumbo_debug("Matches.\n");
while (pop_current_node(parser) != node) {
// Pop all the nodes below the current one. Node is guaranteed to
// be an element on the stack of open elements (set below), so
// this loop is guaranteed to terminate.
}
return is_success;
}
--i;
node = parser->_parser_state->_open_elements.data[i];
if (node->v.element.tag_namespace == GUMBO_NAMESPACE_HTML) {
// Must break before gumbo_tag_from_original_text to avoid passing
// parser-inserted nodes through.
break;
}
node_tagname = node->v.element.original_tag;
gumbo_tag_from_original_text(&node_tagname);
}
assert(node->v.element.tag_namespace == GUMBO_NAMESPACE_HTML);
// We can't call handle_token directly because the current node is still in
// the SVG namespace, so it would re-enter this and result in infinite
// recursion.
return handle_html_content(parser, token) && is_success;
}
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#tree-construction
static bool handle_token(GumboParser* parser, GumboToken* token) {
if (parser->_parser_state->_ignore_next_linefeed &&
token->type == GUMBO_TOKEN_WHITESPACE && token->v.character == '\n') {
parser->_parser_state->_ignore_next_linefeed = false;
ignore_token(parser);
return true;
}
// This needs to be reset both here and in the conditional above to catch both
// the case where the next token is not whitespace (so we don't ignore
// whitespace in the middle of <pre> tags) and where there are multiple
// whitespace tokens (so we don't ignore the second one).
parser->_parser_state->_ignore_next_linefeed = false;
if (tag_is(token, kEndTag, GUMBO_TAG_BODY)) {
parser->_parser_state->_closed_body_tag = true;
}
if (tag_is(token, kEndTag, GUMBO_TAG_HTML)) {
parser->_parser_state->_closed_html_tag = true;
}
const GumboNode* current_node = get_adjusted_current_node(parser);
assert(!current_node || current_node->type == GUMBO_NODE_ELEMENT ||
current_node->type == GUMBO_NODE_TEMPLATE);
if (current_node) {
gumbo_debug("Current node: <%s>.\n",
gumbo_normalized_tagname(current_node->v.element.tag));
}
if (!current_node ||
current_node->v.element.tag_namespace == GUMBO_NAMESPACE_HTML ||
(is_mathml_integration_point(current_node) &&
(token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_WHITESPACE ||
token->type == GUMBO_TOKEN_NULL ||
(token->type == GUMBO_TOKEN_START_TAG &&
!tag_in(token, kStartTag,
(gumbo_tagset){TAG(MGLYPH), TAG(MALIGNMARK)})))) ||
(current_node->v.element.tag_namespace == GUMBO_NAMESPACE_MATHML &&
node_qualified_tag_is(
current_node, GUMBO_NAMESPACE_MATHML, GUMBO_TAG_ANNOTATION_XML) &&
tag_is(token, kStartTag, GUMBO_TAG_SVG)) ||
(is_html_integration_point(current_node) &&
(token->type == GUMBO_TOKEN_START_TAG ||
token->type == GUMBO_TOKEN_CHARACTER ||
token->type == GUMBO_TOKEN_NULL ||
token->type == GUMBO_TOKEN_WHITESPACE)) ||
token->type == GUMBO_TOKEN_EOF) {
return handle_html_content(parser, token);
} else {
return handle_in_foreign_content(parser, token);
}
}
static void fragment_parser_init(GumboParser* parser, GumboTag fragment_ctx,
GumboNamespaceEnum fragment_namespace) {
GumboNode* root;
assert(fragment_ctx != GUMBO_TAG_LAST);
// 3
parser->_parser_state->_fragment_ctx = create_element(parser, fragment_ctx);
parser->_parser_state->_fragment_ctx->v.element.tag_namespace =
fragment_namespace;
// 4
if (fragment_namespace == GUMBO_NAMESPACE_HTML) {
// Non-HTML namespaces always start in the DATA state.
switch (fragment_ctx) {
case GUMBO_TAG_TITLE:
case GUMBO_TAG_TEXTAREA:
gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA);
break;
case GUMBO_TAG_STYLE:
case GUMBO_TAG_XMP:
case GUMBO_TAG_IFRAME:
case GUMBO_TAG_NOEMBED:
case GUMBO_TAG_NOFRAMES:
gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT);
break;
case GUMBO_TAG_SCRIPT:
gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
break;
case GUMBO_TAG_NOSCRIPT:
/* scripting is disabled in Gumbo, so leave the tokenizer
* in the default data state */
break;
case GUMBO_TAG_PLAINTEXT:
gumbo_tokenizer_set_state(parser, GUMBO_LEX_PLAINTEXT);
break;
default:
/* default data state */
break;
}
}
// 5. 6. 7.
root = insert_element_of_tag_type(
parser, GUMBO_TAG_HTML, GUMBO_INSERTION_IMPLIED);
parser->_output->root = root;
// 8.
if (fragment_ctx == GUMBO_TAG_TEMPLATE) {
push_template_insertion_mode(parser, GUMBO_INSERTION_MODE_IN_TEMPLATE);
}
// 10.
reset_insertion_mode_appropriately(parser);
}
GumboOutput* gumbo_parse(const char* buffer) {
return gumbo_parse_with_options(
&kGumboDefaultOptions, buffer, strlen(buffer));
}
GumboOutput* gumbo_parse_with_options(
const GumboOptions* options, const char* buffer, size_t length) {
GumboParser parser;
parser._options = options;
output_init(&parser);
gumbo_tokenizer_state_init(&parser, buffer, length);
parser_state_init(&parser);
if (options->fragment_context != GUMBO_TAG_LAST) {
fragment_parser_init(
&parser, options->fragment_context, options->fragment_namespace);
}
GumboParserState* state = parser._parser_state;
gumbo_debug("Parsing %.*s.\n", length, buffer);
// Sanity check so that infinite loops die with an assertion failure instead
// of hanging the process before we ever get an error.
int loop_count = 0;
GumboToken token;
bool has_error = false;
do {
if (state->_reprocess_current_token) {
state->_reprocess_current_token = false;
} else {
GumboNode* current_node = get_current_node(&parser);
gumbo_tokenizer_set_is_current_node_foreign(&parser,
current_node &&
current_node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML);
has_error = !gumbo_lex(&parser, &token) || has_error;
}
const char* token_type = "text";
switch (token.type) {
case GUMBO_TOKEN_DOCTYPE:
token_type = "doctype";
break;
case GUMBO_TOKEN_START_TAG:
token_type = gumbo_normalized_tagname(token.v.start_tag.tag);
break;
case GUMBO_TOKEN_END_TAG:
token_type = gumbo_normalized_tagname(token.v.end_tag);
break;
case GUMBO_TOKEN_COMMENT:
token_type = "comment";
break;
default:
break;
}
gumbo_debug("Handling %s token @%d:%d in state %d.\n", (char*) token_type,
token.position.line, token.position.column, state->_insertion_mode);
state->_current_token = &token;
state->_self_closing_flag_acknowledged =
!(token.type == GUMBO_TOKEN_START_TAG &&
token.v.start_tag.is_self_closing);
has_error = !handle_token(&parser, &token) || has_error;
// Check for memory leaks when ownership is transferred from start tag
// tokens to nodes.
assert(state->_reprocess_current_token ||
token.type != GUMBO_TOKEN_START_TAG ||
token.v.start_tag.attributes.data == NULL);
if (!state->_self_closing_flag_acknowledged) {
GumboError* error = parser_add_parse_error(&parser, &token);
if (error) {
error->type = GUMBO_ERR_UNACKNOWLEDGED_SELF_CLOSING_TAG;
}
}
++loop_count;
assert(loop_count < 1000000000);
} while ((token.type != GUMBO_TOKEN_EOF || state->_reprocess_current_token) &&
!(options->stop_on_first_error && has_error));
finish_parsing(&parser);
// For API uniformity reasons, if the doctype still has nulls, convert them to
// empty strings.
GumboDocument* doc_type = &parser._output->document->v.document;
if (doc_type->name == NULL) {
doc_type->name = gumbo_copy_stringz(&parser, "");
}
if (doc_type->public_identifier == NULL) {
doc_type->public_identifier = gumbo_copy_stringz(&parser, "");
}
if (doc_type->system_identifier == NULL) {
doc_type->system_identifier = gumbo_copy_stringz(&parser, "");
}
parser_state_destroy(&parser);
gumbo_tokenizer_state_destroy(&parser);
return parser._output;
}
void gumbo_destroy_node(GumboOptions* options, GumboNode* node) {
// Need a dummy GumboParser because the allocator comes along with the
// options object.
GumboParser parser;
parser._options = options;
destroy_node(&parser, node);
}
void gumbo_destroy_output(const GumboOptions* options, GumboOutput* output) {
// Need a dummy GumboParser because the allocator comes along with the
// options object.
GumboParser parser;
parser._options = options;
destroy_node(&parser, output->document);
for (unsigned int i = 0; i < output->errors.length; ++i) {
gumbo_error_destroy(&parser, output->errors.data[i]);
}
gumbo_vector_destroy(&parser, &output->errors);
gumbo_parser_deallocate(&parser, output);
}
| {
"content_hash": "06bc6293f14affc6c6867bfceefc87f6",
"timestamp": "",
"source": "github",
"line_count": 4188,
"max_line_length": 141,
"avg_line_length": 42.076886341929324,
"alnum_prop": 0.663621196472551,
"repo_name": "litehtml/litehtml",
"id": "653fd85acc9c9c6f737e01f336dd094886efd532",
"size": "176218",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/gumbo/parser.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1153082"
},
{
"name": "C++",
"bytes": "636948"
},
{
"name": "CMake",
"bytes": "9342"
},
{
"name": "Ragel",
"bytes": "128179"
}
],
"symlink_target": ""
} |
'use strict';
var hello = require('nodejs-lib');
module.exports = function(name) {
return hello(name).trim();
};
| {
"content_hash": "435dc6f8a7424d5a1127dc17a7455df6",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 34,
"avg_line_length": 16.714285714285715,
"alnum_prop": 0.6581196581196581,
"repo_name": "xpfriend/pocci-template-examples",
"id": "189ad66a639c234e24d0ee47c40f8de58db9775a",
"size": "117",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/example-nexus/nodejs-app/app/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1033"
},
{
"name": "JavaScript",
"bytes": "5499"
},
{
"name": "Ruby",
"bytes": "2420"
},
{
"name": "Shell",
"bytes": "9560"
}
],
"symlink_target": ""
} |
package com.cloudcoders.gestaca.logic.enrollment;
import com.cloudcoders.gestaca.logic.IEnrollmentDAO;
import com.cloudcoders.gestaca.logic.IStudentDAO;
import com.cloudcoders.gestaca.logic.ITaughtCourseDAO;
import com.cloudcoders.gestaca.logic.exceptions.InvalidPersonException;
import com.cloudcoders.gestaca.logic.exceptions.InvalidTaughtCourse;
import com.cloudcoders.gestaca.model.Enrollment;
public class AddEnrollment {
IEnrollmentDAO iEnrollmentDAO;
ITaughtCourseDAO iTaughtCourseDAO;
IStudentDAO iStudentDAO;
public AddEnrollment(IEnrollmentDAO iEnrollmentDAO, ITaughtCourseDAO iTaughtCourseDAO, IStudentDAO iStudentDAO) {
this.iEnrollmentDAO = iEnrollmentDAO;
this.iTaughtCourseDAO = iTaughtCourseDAO;
this.iStudentDAO = iStudentDAO;
}
public void add(Enrollment enrollment) throws InvalidPersonException, InvalidTaughtCourse {
if (iStudentDAO.get(enrollment.getStudent().getId()) == null) {
throw new InvalidPersonException("Invalid person!");
}
if (iTaughtCourseDAO.get(enrollment.getTaughtCourse().getId()) == null) {
throw new InvalidTaughtCourse("Invalid TaughtCourse Madafaka");
}
iEnrollmentDAO.add(enrollment);
}
}
| {
"content_hash": "70cf55d404158070ba7a3b389d002964",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 115,
"avg_line_length": 35.35294117647059,
"alnum_prop": 0.7920133111480865,
"repo_name": "CloudCoders/GestAca",
"id": "8861ce569bfb3ba4d5b569515620d0bcc5582f06",
"size": "1202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/cloudcoders/gestaca/logic/enrollment/AddEnrollment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "53040"
}
],
"symlink_target": ""
} |
namespace VinylC.Services.Data.Contracts
{
using System.Linq;
using VinylC.Data.Models;
public interface IArticleCategoryService
{
IQueryable<AtricleCategory> All();
AtricleCategory CreateNewCategory(AtricleCategory categoryToAdd);
AtricleCategory UpdateCategory(AtricleCategory updated);
}
}
| {
"content_hash": "17e0b25f4397713e9c68bf69c80872f9",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 73,
"avg_line_length": 24.357142857142858,
"alnum_prop": 0.7302052785923754,
"repo_name": "clangelov/ASP.NET-MVC-Course-Project",
"id": "d7a4ce099fae1f4ca7c7ab1e726f25b7295bbcb8",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VinylC/Services/VinylC.Services.Data/Contracts/IArticleCategoryService.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "105"
},
{
"name": "C#",
"bytes": "306404"
},
{
"name": "CSS",
"bytes": "10549"
},
{
"name": "HTML",
"bytes": "5127"
},
{
"name": "JavaScript",
"bytes": "151536"
}
],
"symlink_target": ""
} |
/*
* Powered By [柳丰]
* Web Site: http://www.trend.com.cn
*/
package com.trend.hbny.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.org.rapid_framework.beanutils.BeanUtils;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;
import com.trend.hbny.model.ELineBasicinfo;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.trend.hbny.model.*;
import com.trend.hbny.dao.*;
import com.trend.hbny.service.*;
/**
* @author neolf email:neolf(a)foxmail.com
* @version 1.0
* @since 1.0
*/
public class RDayLineAction extends BaseStruts2Action implements Preparable,ModelDriven{
//默认多列排序,example: username desc,createTime asc
protected static final String DEFAULT_SORT_COLUMNS = null;
//forward paths
protected static final String QUERY_JSP = "/pages/RDayLine/query.jsp";
protected static final String LIST_JSP= "/pages/RDayLine/list.jsp";
protected static final String CREATE_JSP = "/pages/RDayLine/create.jsp";
protected static final String EDIT_JSP = "/pages/RDayLine/edit.jsp";
protected static final String SHOW_JSP = "/pages/RDayLine/show.jsp";
//redirect paths,startWith: !
protected static final String LIST_ACTION = "!/pages/RDayLine/list.do";
private RDayLineManager rDayLineManager;
private RDayLine rDayLine;
java.lang.Long id = null;
private String[] items;
public void prepare() throws Exception {
if (isNullOrEmptyString(id)) {
rDayLine = new RDayLine();
} else {
rDayLine = (RDayLine)rDayLineManager.getById(id);
}
}
/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
public void setRDayLineManager(RDayLineManager manager) {
this.rDayLineManager = manager;
}
public Object getModel() {
return rDayLine;
}
public void setId(java.lang.Long val) {
this.id = val;
}
public void setItems(String[] items) {
this.items = items;
}
/** 进入查询页面 */
public String query() {
return QUERY_JSP;
}
/** 执行搜索 */
public String list() {
PageRequest<Map> pageRequest = newPageRequest(DEFAULT_SORT_COLUMNS);
//pageRequest.getFilters().put("key",value); //add custom filter
Page page = rDayLineManager.findByPageRequest(pageRequest);
savePage(page,pageRequest);
return LIST_JSP;
}
/** 查看对象*/
public String show() {
return SHOW_JSP;
}
/** 进入新增页面*/
public String create() {
return CREATE_JSP;
}
/** 保存新增对象 */
public String save() {
rDayLineManager.save(rDayLine);
return LIST_ACTION;
}
/**进入更新页面*/
public String edit() {
return EDIT_JSP;
}
/**保存更新对象*/
public String update() {
rDayLineManager.update(this.rDayLine);
return LIST_ACTION;
}
/**删除对象*/
public String delete() {
for(int i = 0; i < items.length; i++) {
Hashtable params = HttpUtils.parseQueryString(items[i]);
java.lang.Long id = new java.lang.Long((String)params.get("id"));
rDayLineManager.removeById(id);
}
return LIST_ACTION;
}
/**添加Excel对象*/
public List<RDayLine> getLists(){
return rDayLineManager.findAll();
}
/**添加Excel对象*/
public String getReportName() {
return "Report.xls";
}
}
| {
"content_hash": "636f632c4d3fe7ce4b9378cb7114525a",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 88,
"avg_line_length": 22.824324324324323,
"alnum_prop": 0.7101835405565423,
"repo_name": "neolfdev/dlscxx",
"id": "fbd6f411906bba57fd1b2272135d19cff43fa8ea",
"size": "3538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java_src/com/trend/hbny/action/RDayLineAction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "400"
},
{
"name": "C#",
"bytes": "2785"
},
{
"name": "Java",
"bytes": "2084580"
},
{
"name": "JavaScript",
"bytes": "4007143"
},
{
"name": "PHP",
"bytes": "24990"
},
{
"name": "Python",
"bytes": "7875"
},
{
"name": "Ruby",
"bytes": "2587"
},
{
"name": "Shell",
"bytes": "6460"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>V8 API Reference Guide for node.js v8.5.0: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v8.5.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1AllocationProfile.html">AllocationProfile</a></li><li class="navelem"><a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html">Allocation</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::AllocationProfile::Allocation Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html">v8::AllocationProfile::Allocation</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html#a012fe5238f5ebec039d7832f2d3ae8ed">count</a></td><td class="entry"><a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html">v8::AllocationProfile::Allocation</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html#a346410fa5dfb796dff396069897c0aba">size</a></td><td class="entry"><a class="el" href="structv8_1_1AllocationProfile_1_1Allocation.html">v8::AllocationProfile::Allocation</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| {
"content_hash": "9cf0c93aebb522fe7ab42db695ae5f59",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 313,
"avg_line_length": 48,
"alnum_prop": 0.6622299382716049,
"repo_name": "v8-dox/v8-dox.github.io",
"id": "aab2e7b4a8225cb85ec64875b3f510ff6635d768",
"size": "5184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ba5a697/html/structv8_1_1AllocationProfile_1_1Allocation-members.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.rlcommunity.btanner.agents;
import org.rlcommunity.btanner.agentLib.learningModules.sarsa0.Sarsa0LearningModuleFactory;
import org.rlcommunity.btanner.agentLib.actionSelectors.epsilonGreedy.EpsilonGreedyActionSelectorFactory;
import org.rlcommunity.btanner.agents.AbstractSarsa;
import java.util.Vector;
import org.rlcommunity.btanner.agentLib.actionSelectors.ActionSelectorFactoryInterface;
import org.rlcommunity.btanner.agentLib.functionApproximators.CMAC.CMACFunctionApproximatorFactory;
import org.rlcommunity.btanner.agentLib.functionApproximators.FunctionApproximatorFactoryInterface;
import org.rlcommunity.btanner.agentLib.learningBoosters.AbstractLearningBoosterFactory;
import org.rlcommunity.btanner.agentLib.learningModules.AbstractLearningModuleFactory;
import rlVizLib.general.ParameterHolder;
/**
*
* @author Brian Tanner
*/
public class EpsilonGreedyCMACSarsa extends AbstractSarsa {
public static ParameterHolder getDefaultParameters() {
FunctionApproximatorFactoryInterface FAF=new CMACFunctionApproximatorFactory();
ActionSelectorFactoryInterface ASF=new EpsilonGreedyActionSelectorFactory();
Sarsa0LearningModuleFactory S0LMF=new Sarsa0LearningModuleFactory(FAF, ASF);
ParameterHolder p = AbstractSarsa.getDefaultParameters(S0LMF);
return p;
}
@Override
protected AbstractLearningModuleFactory makeLearningModuleFactory() {
return new Sarsa0LearningModuleFactory(makeFunctionApproximatorFactory(), makeActionSelectorFactory());
}
protected FunctionApproximatorFactoryInterface makeFunctionApproximatorFactory() {
return new CMACFunctionApproximatorFactory();
}
protected ActionSelectorFactoryInterface makeActionSelectorFactory() {
return new EpsilonGreedyActionSelectorFactory();
}
public EpsilonGreedyCMACSarsa(ParameterHolder p){
super(p);
}
public EpsilonGreedyCMACSarsa(){
this(getDefaultParameters());
}
@Override
protected Vector<AbstractLearningBoosterFactory> makeBoosterFactories() {
return new Vector<AbstractLearningBoosterFactory>();
}
}
| {
"content_hash": "2f97194a59ecd54bbee45dcb14a9f9c2",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 111,
"avg_line_length": 40.61971830985915,
"alnum_prop": 0.7895284327323162,
"repo_name": "chrahunt/bt-agentlib",
"id": "76d74e9ef6a10d26e588a9d94a8083c468212ec4",
"size": "2884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/rlcommunity/btanner/agents/EpsilonGreedyCMACSarsa.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "1261350"
},
{
"name": "CSS",
"bytes": "912"
},
{
"name": "Gnuplot",
"bytes": "11226"
},
{
"name": "HTML",
"bytes": "52280"
},
{
"name": "Java",
"bytes": "509673"
},
{
"name": "Makefile",
"bytes": "63130"
},
{
"name": "Matlab",
"bytes": "6642"
},
{
"name": "PHP",
"bytes": "512"
},
{
"name": "Python",
"bytes": "65406"
},
{
"name": "Shell",
"bytes": "9803"
}
],
"symlink_target": ""
} |
@implementation SCImageCollectionViewItem
#pragma mark - Accessors
@synthesize imageURL = _imageURL;
- (void)setImageURL:(NSURL *)url {
[url retain];
[_imageURL release];
_imageURL = url;
if (_imageURL) {
[self.imageView setImageWithURL:url placeholderImage:nil];
} else {
self.imageView.image = nil;
}
}
#pragma mark - NSObject
- (void)dealloc {
[_imageURL release];
[super dealloc];
}
#pragma mark - Initializer
- (id)initWithReuseIdentifier:(NSString *)aReuseIdentifier {
if ((self = [super initWithStyle:SSCollectionViewItemStyleImage reuseIdentifier:aReuseIdentifier])) {
self.imageView.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
}
return self;
}
- (void)prepareForReuse {
[super prepareForReuse];
self.imageURL = nil;
}
@end
| {
"content_hash": "f2b6c7bd0d18315b4ffa2cc8839c38ea",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 102,
"avg_line_length": 18.186046511627907,
"alnum_prop": 0.7237851662404092,
"repo_name": "111minutes/CocoaPods",
"id": "a89ad7c4e8aea0f58a98aca1e76b9c30b5132ffb",
"size": "1003",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/SSCatalog/Classes/SCImageCollectionViewItem.m",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace OpenCFP\Http\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
class ForgotFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email', EmailType::class, ['constraints' => [new Assert\Email()]])
->add('send', SubmitType::class, ['label' => 'Reset my password']);
}
}
| {
"content_hash": "cf24337ed8efb569b5f1cf18a8825fa7",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 89,
"avg_line_length": 28.772727272727273,
"alnum_prop": 0.7361769352290679,
"repo_name": "mdwheele/opencfp",
"id": "e8531882587c0209ec86da0c80f781f1a7800e08",
"size": "851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/Http/Form/ForgotFormType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2877"
},
{
"name": "HTML",
"bytes": "76356"
},
{
"name": "JavaScript",
"bytes": "31798"
},
{
"name": "Makefile",
"bytes": "852"
},
{
"name": "PHP",
"bytes": "773799"
},
{
"name": "Shell",
"bytes": "3747"
}
],
"symlink_target": ""
} |
/*
Security support for OpenTRV.
*/
#ifndef SECURITY_H
#define SECURITY_H
#include "V0p2_Main.h"
// How much info does a leaf node transmit about stats such as temperature and occupancy?
// Excess unencrypted stats may, for example, allow a clever burglar to work out when no one is home.
// Note that even in the 'always' setting,
// some TXes may be selectively skipped or censored for energy saving and security reasons
// eg an additional 'never transmit occupancy' flag may be set locally.
// The values correspond to levels and intermediate values not explicitly enumerated may be allowed.
// Lower values mean less security is required.
enum stats_TX_level
{
stTXalwaysAll = 0, // Always be prepared to transmit all stats.
stTXmostUnsec, // Allow TX of all but most security-sensitive stats in plaintext, eg occupancy status.
stTXsecOnly, // Only transmit if the stats TX can be kept secure/encrypted.
stTXnever = 0xff // Never transmit status info above the minimum necessary.
};
// Get the current stats transmission level (for data outbound from this node).
// May not exactly match enumerated levels; use inequalities.
stats_TX_level getStatsTXLevel();
// Generate 'secure' new random byte.
// This should be essentially all entropy and unguessable.
// Likely to be slow and may force some I/O.
uint8_t getSecureRandomByte();
// Add entropy to the pool, if any, along with an estimate of how many bits of real entropy are present.
// * data byte containing 'random' bits.
// * estBits estimated number of truely securely random bits in range [0,8].
void addEntropyToPool(uint8_t data, uint8_t estBits);
#endif
| {
"content_hash": "27fb0a557fa32f12606b9439e6d16029",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 106,
"avg_line_length": 37.77272727272727,
"alnum_prop": 0.7484957882069796,
"repo_name": "opentrv/OpenTRV-Arduino-V0p2",
"id": "8ced535c89151a6e2431a8d8ca038747065d2c37",
"size": "2319",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Arduino/contrib/GG20141018/V0p2_Main/Security.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2227106"
},
{
"name": "C++",
"bytes": "22600502"
},
{
"name": "Game Maker Language",
"bytes": "41646"
},
{
"name": "Prolog",
"bytes": "41527"
},
{
"name": "Shell",
"bytes": "5419"
},
{
"name": "Stata",
"bytes": "3822875"
}
],
"symlink_target": ""
} |
package gov.nih.nci.cabig.caaers.dao.index;
import gov.nih.nci.cabig.caaers.CaaersDbTestCase;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain.index.IndexEntry;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author: Biju Joseph
*/
public class OrganizationIndexDaoIntegrationTest extends CaaersDbTestCase {
OrganizationIndexDao dao;
@Override
protected void setUp() throws Exception {
super.setUp();
dao = (OrganizationIndexDao) getDeployedApplicationContext().getBean("organizationIndexDao");
}
public void testUpdateIndex(){
{
IndexEntry i0 = new IndexEntry(-1);
i0.addRole(UserGroupType.business_administrator);
i0.addRole(UserGroupType.ae_reporter);
IndexEntry i1 = new IndexEntry(-2);
i1.addRole(UserGroupType.ae_study_data_reviewer);
List<IndexEntry> iList = new ArrayList<IndexEntry>();
iList.add(i0);
iList.add(i1);
dao.updateIndex("test", iList);
}
interruptSession();
{
List<IndexEntry> entries = dao.queryAllIndexEntries("test");
assertEquals(2, entries.size());
IndexEntry i0 = entries.get(0);
IndexEntry i1 = entries.get(1);
System.out.println(entries) ;
if(i1.getEntityId() == -2){
assertTrue((i1.getPrivilege() & UserGroupType.ae_study_data_reviewer.getPrivilege()) > 0);
}
if(i0.getEntityId() == -1){
System.out.println("AeReporter : " + UserGroupType.ae_reporter.getPrivilege() + " business admin : " + UserGroupType.business_administrator.getPrivilege() + " OR : " + (UserGroupType.ae_reporter.getPrivilege() | UserGroupType.business_administrator.getPrivilege()));
assertTrue((i0.getPrivilege() & UserGroupType.ae_reporter.getPrivilege()) > 0);
assertTrue((i0.getPrivilege() & UserGroupType.business_administrator.getPrivilege()) > 0);
}
}
}
}
| {
"content_hash": "baee4201c3af9040ffd07add9290f5d4",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 282,
"avg_line_length": 32.19178082191781,
"alnum_prop": 0.6412765957446809,
"repo_name": "NCIP/caaers",
"id": "b7eec7a090f3120980ab9ecb83094ca0a9b4283a",
"size": "2707",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "caAERS/software/core/src/test/java/gov/nih/nci/cabig/caaers/dao/index/OrganizationIndexDaoIntegrationTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AspectJ",
"bytes": "2052"
},
{
"name": "CSS",
"bytes": "150269"
},
{
"name": "Groovy",
"bytes": "19195107"
},
{
"name": "Java",
"bytes": "13042355"
},
{
"name": "JavaScript",
"bytes": "438475"
},
{
"name": "Ruby",
"bytes": "29724"
},
{
"name": "Shell",
"bytes": "1436"
},
{
"name": "XSLT",
"bytes": "1330533"
}
],
"symlink_target": ""
} |
[data-section=''] > section > h4 [data-section-title] {
color: cyan;
} | {
"content_hash": "6b198e4edc89f841c71ca15e11457f76",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 55,
"avg_line_length": 24,
"alnum_prop": 0.625,
"repo_name": "giakki/uncss",
"id": "b73281397e6466887346dc4031b50d27e199735b",
"size": "72",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/selectors/expected/complex.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22195"
},
{
"name": "HTML",
"bytes": "25747"
},
{
"name": "JavaScript",
"bytes": "54660"
}
],
"symlink_target": ""
} |
#include "config.h"
#include <algorithm>
#include <array>
#include <cstdlib>
#include <iterator>
#include "alc/effects/base.h"
#include "almalloc.h"
#include "alnumbers.h"
#include "alnumeric.h"
#include "alspan.h"
#include "core/ambidefs.h"
#include "core/bufferline.h"
#include "core/context.h"
#include "core/devformat.h"
#include "core/device.h"
#include "core/effectslot.h"
#include "core/filters/biquad.h"
#include "core/mixer.h"
#include "intrusive_ptr.h"
namespace {
using uint = unsigned int;
#define MAX_UPDATE_SAMPLES 128
#define WAVEFORM_FRACBITS 24
#define WAVEFORM_FRACONE (1<<WAVEFORM_FRACBITS)
#define WAVEFORM_FRACMASK (WAVEFORM_FRACONE-1)
inline float Sin(uint index)
{
constexpr float scale{al::numbers::pi_v<float>*2.0f / WAVEFORM_FRACONE};
return std::sin(static_cast<float>(index) * scale);
}
inline float Saw(uint index)
{ return static_cast<float>(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f; }
inline float Square(uint index)
{ return static_cast<float>(static_cast<int>((index>>(WAVEFORM_FRACBITS-2))&2) - 1); }
inline float One(uint) { return 1.0f; }
template<float (&func)(uint)>
void Modulate(float *RESTRICT dst, uint index, const uint step, size_t todo)
{
for(size_t i{0u};i < todo;i++)
{
index += step;
index &= WAVEFORM_FRACMASK;
dst[i] = func(index);
}
}
struct ModulatorState final : public EffectState {
void (*mGetSamples)(float*RESTRICT, uint, const uint, size_t){};
uint mIndex{0};
uint mStep{1};
struct {
BiquadFilter Filter;
float CurrentGains[MAX_OUTPUT_CHANNELS]{};
float TargetGains[MAX_OUTPUT_CHANNELS]{};
} mChans[MaxAmbiChannels];
void deviceUpdate(const DeviceBase *device, const Buffer &buffer) override;
void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
const EffectTarget target) override;
void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
const al::span<FloatBufferLine> samplesOut) override;
DEF_NEWDEL(ModulatorState)
};
void ModulatorState::deviceUpdate(const DeviceBase*, const Buffer&)
{
for(auto &e : mChans)
{
e.Filter.clear();
std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f);
}
}
void ModulatorState::update(const ContextBase *context, const EffectSlot *slot,
const EffectProps *props, const EffectTarget target)
{
const DeviceBase *device{context->mDevice};
const float step{props->Modulator.Frequency / static_cast<float>(device->Frequency)};
mStep = fastf2u(clampf(step*WAVEFORM_FRACONE, 0.0f, float{WAVEFORM_FRACONE-1}));
if(mStep == 0)
mGetSamples = Modulate<One>;
else if(props->Modulator.Waveform == ModulatorWaveform::Sinusoid)
mGetSamples = Modulate<Sin>;
else if(props->Modulator.Waveform == ModulatorWaveform::Sawtooth)
mGetSamples = Modulate<Saw>;
else /*if(props->Modulator.Waveform == ModulatorWaveform::Square)*/
mGetSamples = Modulate<Square>;
float f0norm{props->Modulator.HighPassCutoff / static_cast<float>(device->Frequency)};
f0norm = clampf(f0norm, 1.0f/512.0f, 0.49f);
/* Bandwidth value is constant in octaves. */
mChans[0].Filter.setParamsFromBandwidth(BiquadType::HighPass, f0norm, 1.0f, 0.75f);
for(size_t i{1u};i < slot->Wet.Buffer.size();++i)
mChans[i].Filter.copyParamsFrom(mChans[0].Filter);
mOutTarget = target.Main->Buffer;
auto set_gains = [slot,target](auto &chan, al::span<const float,MaxAmbiChannels> coeffs)
{ ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); };
SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains);
}
void ModulatorState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
{
for(size_t base{0u};base < samplesToDo;)
{
alignas(16) float modsamples[MAX_UPDATE_SAMPLES];
const size_t td{minz(MAX_UPDATE_SAMPLES, samplesToDo-base)};
mGetSamples(modsamples, mIndex, mStep, td);
mIndex += static_cast<uint>(mStep * td);
mIndex &= WAVEFORM_FRACMASK;
auto chandata = std::begin(mChans);
for(const auto &input : samplesIn)
{
alignas(16) float temps[MAX_UPDATE_SAMPLES];
chandata->Filter.process({&input[base], td}, temps);
for(size_t i{0u};i < td;i++)
temps[i] *= modsamples[i];
MixSamples({temps, td}, samplesOut, chandata->CurrentGains, chandata->TargetGains,
samplesToDo-base, base);
++chandata;
}
base += td;
}
}
struct ModulatorStateFactory final : public EffectStateFactory {
al::intrusive_ptr<EffectState> create() override
{ return al::intrusive_ptr<EffectState>{new ModulatorState{}}; }
};
} // namespace
EffectStateFactory *ModulatorStateFactory_getFactory()
{
static ModulatorStateFactory ModulatorFactory{};
return &ModulatorFactory;
}
| {
"content_hash": "07ba56ac498a1301281f73717d17372f",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 147,
"avg_line_length": 30.727272727272727,
"alnum_prop": 0.6775147928994083,
"repo_name": "Try/Tempest",
"id": "84561f5c337afe0bca35ef1fb843e240a6015b39",
"size": "5960",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Engine/thirdparty/openal-soft/alc/effects/modulator.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "53599"
},
{
"name": "C++",
"bytes": "4790826"
},
{
"name": "CMake",
"bytes": "70000"
},
{
"name": "GLSL",
"bytes": "12928"
},
{
"name": "M4",
"bytes": "25387"
},
{
"name": "Makefile",
"bytes": "25787"
},
{
"name": "Objective-C++",
"bytes": "29332"
},
{
"name": "Python",
"bytes": "451787"
},
{
"name": "Shell",
"bytes": "26543"
}
],
"symlink_target": ""
} |
local path = (...):match("(.-)[^%.]+$")
local ListView = require (path.."class").extends(require (path.."View"),"ListView")
path = nil
------------------------------------------
-- Public functions
------------------------------------------
ListView.Direction = {
Horizontal = 0, Vertical = 1
}
function ListView.new(x,y,width,height,scrollDirection)
local self = ListView.newObject(x,y,width,height)
self.scrollDirection = ListView.Direction[scrollDirection]
self.isDragging = false
self.delegate = nil
return self
end
function ListView:mousepressed(x,y,b)
if not self:sub_mousepressed(x,y,b) then
self.isDragging = true
end
end
function ListView:mousemoved(x,y,dx,dy)
if not self:super_mousemoved(x,y,dx,dy) and self.isDragging then
-- Scroll action
end
end
function ListView:mousereleased(x,y,b)
self:sub_mousereleased()
self.isDragging = false
end
return ListView | {
"content_hash": "a1cf543cda3a11186a8d924f2dee0b8e",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 83,
"avg_line_length": 23.42105263157895,
"alnum_prop": 0.6640449438202247,
"repo_name": "LexLoki/LoveUIView",
"id": "a379ee8cd19b2cfe4e8bb975952fbc0ccf4c9a5c",
"size": "2014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LoveUIView/ListView.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "31172"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
<File path="Classes/AutoScalingDescribeAutoScalingGroupsRequest.html">
<Token>
<TokenIdentifier>//apple_ref/occ/cl/AutoScalingDescribeAutoScalingGroupsRequest</TokenIdentifier>
<Abstract type="html">Describe Auto Scaling Groups Request</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<NodeRef refid="69"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/init</TokenIdentifier>
<Abstract type="html">Default constructor for a new object. Callers should use the
property methods to initialize this object after creating it.</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>- (id)init</Declaration>
<Anchor>//api/name/init</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setAutoScalingGroupNames:</TokenIdentifier>
<Abstract type="html">A list of Auto Scaling group names.</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSMutableArray *autoScalingGroupNames</Declaration>
<Anchor>//api/name/autoScalingGroupNames</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/autoScalingGroupNames</TokenIdentifier>
<Abstract type="html">A list of Auto Scaling group names.</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSMutableArray *autoScalingGroupNames</Declaration>
<Anchor>//api/name/autoScalingGroupNames</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setNextToken:</TokenIdentifier>
<Abstract type="html">A string that marks the start of the next batch of returned results.
<p>
<b>Constraints:</b><br/>
<b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/></Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSString *nextToken</Declaration>
<Anchor>//api/name/nextToken</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/nextToken</TokenIdentifier>
<Abstract type="html">A string that marks the start of the next batch of returned results.
<p>
<b>Constraints:</b><br/>
<b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/></Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSString *nextToken</Declaration>
<Anchor>//api/name/nextToken</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/setMaxRecords:</TokenIdentifier>
<Abstract type="html">The maximum number of records to return.
<p>
<b>Constraints:</b><br/>
<b>Range: </b>1 - 50<br/></Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSNumber *maxRecords</Declaration>
<Anchor>//api/name/maxRecords</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instp/AutoScalingDescribeAutoScalingGroupsRequest/maxRecords</TokenIdentifier>
<Abstract type="html">The maximum number of records to return.
<p>
<b>Constraints:</b><br/>
<b>Range: </b>1 - 50<br/></Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>@property (nonatomic, retain) NSNumber *maxRecords</Declaration>
<Anchor>//api/name/maxRecords</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/addAutoScalingGroupName:</TokenIdentifier>
<Abstract type="html">Adds a single object to autoScalingGroupNames.
This function will alloc and init autoScalingGroupNames if not already done.</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>- (void)addAutoScalingGroupName:(NSString *)autoScalingGroupNameObject</Declaration>
<Anchor>//api/name/addAutoScalingGroupName:</Anchor>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/AutoScalingDescribeAutoScalingGroupsRequest/description</TokenIdentifier>
<Abstract type="html">Returns a string representation of this object; useful for testing and
debugging.</Abstract>
<DeclaredIn>AutoScalingDescribeAutoScalingGroupsRequest.h</DeclaredIn>
<Declaration>- (NSString *)description</Declaration>
<ReturnValue><Abstract type="html">A string representation of this object.</Abstract></ReturnValue>
<Anchor>//api/name/description</Anchor>
</Token>
</File>
</Tokens> | {
"content_hash": "9dcaceadbfbeb792271a905a35127202",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 129,
"avg_line_length": 40.47286821705426,
"alnum_prop": 0.746217199770159,
"repo_name": "abovelabs/aws-ios-sdk",
"id": "769217456ea0e3921543221a191fde232a53a01f",
"size": "5221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Documentation/com.amazon.aws.ios.docset/Contents/Resources/Tokens69.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Azure end
module Azure::DevTestLabs end
module Azure::DevTestLabs::Profiles end
module Azure::DevTestLabs::Profiles::Latest end
| {
"content_hash": "3327a998356e98fa83d0617ac89d8ae9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 47,
"avg_line_length": 33.75,
"alnum_prop": 0.8222222222222222,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "17225e1118d5f9a2453696ff864fe2eca9a8c785",
"size": "309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_devtestlabs/lib/profiles/latest/devtestlabs_module_definition.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using AutoMapper;
using NHibernate.Envers.Configuration.Attributes;
using Storymark.Service.Data.ViewModels;
namespace Storymark.Service.Data.Entities
{
[Audited]
public class Project
{
public virtual Guid Id { get; protected set; }
public virtual string Title { get; set; }
public virtual string ProjectType { get; set; }
public virtual Manuscript Manuscript { get; set; }
public virtual GlobalStoryGrid GlobalStoryGrid { get; set; }
public virtual Folder RootFolder { get; set; }
public virtual Person Owner { get; set; }
public virtual IList<Project> SubProjects { get; set; }
}
} | {
"content_hash": "024e4efcf4c31afbd5b43f4283072203",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 68,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.7383458646616541,
"repo_name": "jwynia/StoryMark",
"id": "50160a0c8faf0e87979513d9435673bf3c440fe2",
"size": "667",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Storymark.Service/Data/Entities/Project.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "210"
},
{
"name": "C#",
"bytes": "278731"
},
{
"name": "CSS",
"bytes": "10433"
},
{
"name": "HTML",
"bytes": "3085"
},
{
"name": "JavaScript",
"bytes": "17754"
}
],
"symlink_target": ""
} |
var cssConcat = require('css-concat');
var express = require('express');
var browserify = require('browserify');
var md5 = require('md5');
var send = require('send');
var url = require('url');
var path = require('path');
var compression = require('compression');
var isImage = require('is-image');
var clientJS = './client/client.js';
var clientCSS = './client/client.css';
var index = './client/client.html';
var client = browserify({
debug: process.env.NODE_ENV !== 'production'
});
client.add(clientJS);
var css = new Buffer(cssConcat.concat(clientCSS));
console.log('bundled css');
var app = express();
app.use(compression());
var public = path.resolve(__dirname, 'client');
client.bundle(function(err, buf) {
if(err) {
throw err;
}
console.log('bundled javascript');
// yay magic cache busting
var JSETag = md5(buf);
var CSSETag = md5(css);
app.use(function(req, res, next) {
var request = url.parse(req.url).pathname;
if(request !== '/bundle.css' && request !== '/bundle.js') {
if(isImage(request)) {
console.log('returning data for: %s from %s', request, public);
send(req, request, {root: public}).pipe(res);
} else {
console.log('serving client for request:', request);
send(req, index).pipe(res);
}
return;
}
next();
});
app.get('/bundle.css', function (req, res) {
res.status(200);
res.set({
'Content-Type': 'text/css',
'Content-Length': css.length,
'ETag': CSSETag
});
res.end(css);
});
app.get('/bundle.js', function (req, res) {
res.status(200);
res.set({
'Content-Type': 'text/javascript',
'Content-Length': buf.length,
'ETag': JSETag
});
res.end(buf);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
});
| {
"content_hash": "b757901332876e1d53c4531e468ef380",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 67,
"avg_line_length": 23.061728395061728,
"alnum_prop": 0.6359743040685225,
"repo_name": "RpprRoger/brain",
"id": "4c3d9ea0bf0276a7142a505d7b6f03497e589572",
"size": "1868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1464"
},
{
"name": "HTML",
"bytes": "338"
},
{
"name": "JavaScript",
"bytes": "15928"
}
],
"symlink_target": ""
} |
Homework tasks @ SAP GeekyCamp
| {
"content_hash": "25c79c6a4c228cf479867031730586da",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 30,
"avg_line_length": 31,
"alnum_prop": 0.8064516129032258,
"repo_name": "YaneYosifov/SAP-GeekyCamp",
"id": "14509f772f94c394e943fad38195457f60e22a7c",
"size": "47",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "10455"
}
],
"symlink_target": ""
} |
package sun.tools.jconsole;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import static javax.swing.SwingConstants.*;
import static sun.tools.jconsole.JConsole.*;
import static sun.tools.jconsole.Resources.*;
import static sun.tools.jconsole.Utilities.*;
@SuppressWarnings("serial")
public class BorderedComponent extends JPanel implements ActionListener {
JButton moreOrLessButton;
String valueLabelStr;
JLabel label;
JComponent comp;
boolean collapsed = false;
private JPopupMenu popupMenu;
private Icon collapseIcon;
private Icon expandIcon;
private static Image getImage(String name) {
Toolkit tk = Toolkit.getDefaultToolkit();
name = "resources/" + name + ".png";
return tk.getImage(BorderedComponent.class.getResource(name));
}
public BorderedComponent(String text) {
this(text, null, false);
}
public BorderedComponent(String text, JComponent comp) {
this(text, comp, false);
}
public BorderedComponent(String text, JComponent comp, boolean collapsible) {
super(null);
this.comp = comp;
// Only add border if text is not null
if (text != null) {
TitledBorder border;
if (collapsible) {
final JLabel textLabel = new JLabel(text);
JPanel borderLabel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0)) {
public int getBaseline(int w, int h) {
Dimension dim = textLabel.getPreferredSize();
return textLabel.getBaseline(dim.width, dim.height) + textLabel.getY();
}
};
borderLabel.add(textLabel);
border = new LabeledBorder(borderLabel);
textLabel.setForeground(border.getTitleColor());
if (IS_WIN) {
collapseIcon = new ImageIcon(getImage("collapse-winlf"));
expandIcon = new ImageIcon(getImage("expand-winlf"));
} else {
collapseIcon = new ArrowIcon(SOUTH, textLabel);
expandIcon = new ArrowIcon(EAST, textLabel);
}
moreOrLessButton = new JButton(collapseIcon);
moreOrLessButton.setContentAreaFilled(false);
moreOrLessButton.setBorderPainted(false);
moreOrLessButton.setMargin(new Insets(0, 0, 0, 0));
moreOrLessButton.addActionListener(this);
String toolTip =
getText("BorderedComponent.moreOrLessButton.toolTip");
moreOrLessButton.setToolTipText(toolTip);
borderLabel.add(moreOrLessButton);
borderLabel.setSize(borderLabel.getPreferredSize());
add(borderLabel);
} else {
border = new TitledBorder(text);
}
setBorder(new CompoundBorder(new FocusBorder(this), border));
} else {
setBorder(new FocusBorder(this));
}
if (comp != null) {
add(comp);
}
}
public void setComponent(JComponent comp) {
if (this.comp != null) {
remove(this.comp);
}
this.comp = comp;
if (!collapsed) {
LayoutManager lm = getLayout();
if (lm instanceof BorderLayout) {
add(comp, BorderLayout.CENTER);
} else {
add(comp);
}
}
revalidate();
}
public void setValueLabel(String str) {
this.valueLabelStr = str;
if (label != null) {
label.setText(Resources.getText("Current value",valueLabelStr));
}
}
public void actionPerformed(ActionEvent ev) {
if (collapsed) {
if (label != null) {
remove(label);
}
add(comp);
moreOrLessButton.setIcon(collapseIcon);
} else {
remove(comp);
if (valueLabelStr != null) {
if (label == null) {
label = new JLabel(Resources.getText("Current value",
valueLabelStr));
}
add(label);
}
moreOrLessButton.setIcon(expandIcon);
}
collapsed = !collapsed;
JComponent container = (JComponent)getParent();
if (container != null &&
container.getLayout() instanceof VariableGridLayout) {
((VariableGridLayout)container.getLayout()).setFillRow(this, !collapsed);
container.revalidate();
}
}
public Dimension getMinimumSize() {
if (getLayout() != null) {
// A layout manager has been set, so delegate to it
return super.getMinimumSize();
}
if (moreOrLessButton != null) {
Dimension d = moreOrLessButton.getMinimumSize();
Insets i = getInsets();
d.width += i.left + i.right;
d.height += i.top + i.bottom;
return d;
} else {
return super.getMinimumSize();
}
}
public void doLayout() {
if (getLayout() != null) {
// A layout manager has been set, so delegate to it
super.doLayout();
return;
}
Dimension d = getSize();
Insets i = getInsets();
if (collapsed) {
if (label != null) {
Dimension p = label.getPreferredSize();
label.setBounds(i.left,
i.top + (d.height - i.top - i.bottom - p.height) / 2,
p.width,
p.height);
}
} else {
if (comp != null) {
comp.setBounds(i.left,
i.top,
d.width - i.left - i.right,
d.height - i.top - i.bottom);
}
}
}
private static class ArrowIcon implements Icon {
private int direction;
private JLabel textLabel;
public ArrowIcon(int direction, JLabel textLabel) {
this.direction = direction;
this.textLabel = textLabel;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
int w = getIconWidth();
int h = w;
Polygon p = new Polygon();
switch (direction) {
case EAST:
p.addPoint(x + 2, y);
p.addPoint(x + w - 2, y + h / 2);
p.addPoint(x + 2, y + h - 1);
break;
case SOUTH:
p.addPoint(x, y + 2);
p.addPoint(x + w / 2, y + h - 2);
p.addPoint(x + w - 1, y + 2);
break;
}
g.fillPolygon(p);
}
public int getIconWidth() {
return getIconHeight();
}
public int getIconHeight() {
Graphics g = textLabel.getGraphics();
if (g != null) {
int h = g.getFontMetrics(textLabel.getFont()).getAscent() * 6/10;
if (h % 2 == 0) {
h += 1; // Make it odd
}
return h;
} else {
return 7;
}
}
}
/**
* A subclass of <code>TitledBorder</code> which implements an arbitrary border
* with the addition of a JComponent (JLabel, JPanel, etc) in the
* default position.
* <p>
* If the border property value is not
* specified in the constuctor or by invoking the appropriate
* set method, the property value will be defined by the current
* look and feel, using the following property name in the
* Defaults Table:
* <ul>
* <li>"TitledBorder.border"
* </ul>
*/
protected static class LabeledBorder extends TitledBorder {
protected JComponent label;
private Point compLoc = new Point();
/**
* Creates a LabeledBorder instance.
*
* @param label the label the border should display
*/
public LabeledBorder(JComponent label) {
this(null, label);
}
/**
* Creates a LabeledBorder instance with the specified border
* and an empty label.
*
* @param border the border
*/
public LabeledBorder(Border border) {
this(border, null);
}
/**
* Creates a LabeledBorder instance with the specified border and
* label.
*
* @param border the border
* @param label the label the border should display
*/
public LabeledBorder(Border border, JComponent label) {
super(border);
this.label = label;
if (label instanceof JLabel &&
label.getForeground() instanceof ColorUIResource) {
label.setForeground(getTitleColor());
}
}
/**
* Paints the border for the specified component with the
* specified position and size.
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*/
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Border border = getBorder();
if (label == null) {
if (border != null) {
border.paintBorder(c, g, x, y, width, height);
}
return;
}
Rectangle grooveRect = new Rectangle(x + EDGE_SPACING, y + EDGE_SPACING,
width - (EDGE_SPACING * 2),
height - (EDGE_SPACING * 2));
Dimension labelDim = label.getPreferredSize();
int baseline = label.getBaseline(labelDim.width, labelDim.height);
int ascent = Math.max(0, baseline);
int descent = labelDim.height - ascent;
int diff;
Insets insets;
if (border != null) {
insets = border.getBorderInsets(c);
} else {
insets = new Insets(0, 0, 0, 0);
}
diff = Math.max(0, ascent/2 + TEXT_SPACING - EDGE_SPACING);
grooveRect.y += diff;
grooveRect.height -= diff;
compLoc.y = grooveRect.y + insets.top/2 - (ascent + descent) / 2 - 1;
int justification;
if (c.getComponentOrientation().isLeftToRight()) {
justification = LEFT;
} else {
justification = RIGHT;
}
switch (justification) {
case LEFT:
compLoc.x = grooveRect.x + TEXT_INSET_H + insets.left;
break;
case RIGHT:
compLoc.x = (grooveRect.x + grooveRect.width
- (labelDim.width + TEXT_INSET_H + insets.right));
break;
}
// If title is positioned in middle of border AND its fontsize
// is greater than the border's thickness, we'll need to paint
// the border in sections to leave space for the component's background
// to show through the title.
//
if (border != null) {
if (grooveRect.y > compLoc.y - ascent) {
Rectangle clipRect = new Rectangle();
// save original clip
Rectangle saveClip = g.getClipBounds();
// paint strip left of text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, x, y, compLoc.x-1-x, height)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
// paint strip right of text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect, compLoc.x+ labelDim.width +1, y,
x+width-(compLoc.x+ labelDim.width +1), height)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
// paint strip below text
clipRect.setBounds(saveClip);
if (computeIntersection(clipRect,
compLoc.x - 1, compLoc.y + ascent + descent,
labelDim.width + 2,
y + height - compLoc.y - ascent - descent)) {
g.setClip(clipRect);
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
// restore clip
g.setClip(saveClip);
} else {
border.paintBorder(c, g, grooveRect.x, grooveRect.y,
grooveRect.width, grooveRect.height);
}
label.setLocation(compLoc);
label.setSize(labelDim);
}
}
/**
* Reinitialize the insets parameter with this Border's current Insets.
* @param c the component for which this border insets value applies
* @param insets the object to be reinitialized
*/
public Insets getBorderInsets(Component c, Insets insets) {
int height = 16;
Border border = getBorder();
if (border != null) {
if (border instanceof AbstractBorder) {
((AbstractBorder)border).getBorderInsets(c, insets);
} else {
// Can't reuse border insets because the Border interface
// can't be enhanced.
Insets i = border.getBorderInsets(c);
insets.top = i.top;
insets.right = i.right;
insets.bottom = i.bottom;
insets.left = i.left;
}
} else {
insets.left = insets.top = insets.right = insets.bottom = 0;
}
insets.left += EDGE_SPACING + TEXT_SPACING;
insets.right += EDGE_SPACING + TEXT_SPACING;
insets.top += EDGE_SPACING + TEXT_SPACING;
insets.bottom += EDGE_SPACING + TEXT_SPACING;
if (c == null || label == null) {
return insets;
}
insets.top += label.getHeight();
return insets;
}
/**
* Returns the label of the labeled border.
*/
public JComponent getLabel() {
return label;
}
/**
* Sets the title of the titled border.
* param title the title for the border
*/
public void setLabel(JComponent label) {
this.label = label;
}
/**
* Returns the minimum dimensions this border requires
* in order to fully display the border and title.
* @param c the component where this border will be drawn
*/
public Dimension getMinimumSize(Component c) {
Insets insets = getBorderInsets(c);
Dimension minSize = new Dimension(insets.right + insets.left,
insets.top + insets.bottom);
minSize.width += label.getWidth();
return minSize;
}
private static boolean computeIntersection(Rectangle dest,
int rx, int ry, int rw, int rh) {
int x1 = Math.max(rx, dest.x);
int x2 = Math.min(rx + rw, dest.x + dest.width);
int y1 = Math.max(ry, dest.y);
int y2 = Math.min(ry + rh, dest.y + dest.height);
dest.x = x1;
dest.y = y1;
dest.width = x2 - x1;
dest.height = y2 - y1;
if (dest.width <= 0 || dest.height <= 0) {
return false;
}
return true;
}
}
protected static class FocusBorder extends AbstractBorder implements FocusListener {
private Component comp;
private Color focusColor;
private boolean focusLostTemporarily = false;
public FocusBorder(Component comp) {
this.comp = comp;
comp.addFocusListener(this);
// This is the best guess for a L&F specific color
focusColor = UIManager.getColor("TabbedPane.focus");
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (comp.hasFocus() || focusLostTemporarily) {
Color color = g.getColor();
g.setColor(focusColor);
BasicGraphicsUtils.drawDashedRect(g, x, y, width, height);
g.setColor(color);
}
}
public Insets getBorderInsets(Component c) {
return getBorderInsets(c, new Insets(0, 0, 0, 0));
}
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.top = insets.right = insets.bottom = 2;
return insets;
}
public void focusGained(FocusEvent e) {
comp.repaint();
}
public void focusLost(FocusEvent e) {
// We will still paint focus even if lost temporarily
focusLostTemporarily = e.isTemporary();
if (!focusLostTemporarily) {
comp.repaint();
}
}
}
}
| {
"content_hash": "a6ca6f2b36ac1b0b2d6adebfe8f02662",
"timestamp": "",
"source": "github",
"line_count": 549,
"max_line_length": 95,
"avg_line_length": 33.90528233151184,
"alnum_prop": 0.4990329859245729,
"repo_name": "andreagenso/java2scala",
"id": "0b5429bc26947c5e9caa10eecc3052907311f63e",
"size": "19826",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/tools/jconsole/BorderedComponent.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": ""
} |
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/clr_back_full" >
<FrameLayout
android:id="@+id/flContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
| {
"content_hash": "161380a2a0c4d28194be73f1e048df4a",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 62,
"avg_line_length": 26.266666666666666,
"alnum_prop": 0.7385786802030457,
"repo_name": "gtgray/instagramClient",
"id": "1eb9ea1322943ee5f7d21c8b4aea416db15742ec",
"size": "394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "62708"
}
],
"symlink_target": ""
} |
-include $(TOPDIR)/.config
-include $(TOPDIR)/Make.defs
include $(APPDIR)/Make.defs
# built-in application info
APPNAME = proc_test
FUNCNAME = proc_test_main
THREADEXEC = TASH_EXECMD_ASYNC
# procfs test Example
ASRCS =
CSRCS =
MAINSRC = proc_test_main.c
AOBJS = $(ASRCS:.S=$(OBJEXT))
COBJS = $(CSRCS:.c=$(OBJEXT))
MAINOBJ = $(MAINSRC:.c=$(OBJEXT))
SRCS = $(ASRCS) $(CSRCS) $(MAINSRC)
OBJS = $(AOBJS) $(COBJS)
ifneq ($(CONFIG_BUILD_KERNEL),y)
OBJS += $(MAINOBJ)
endif
ifeq ($(CONFIG_WINDOWS_NATIVE),y)
BIN = ..\..\libapps$(LIBEXT)
else
ifeq ($(WINTOOL),y)
BIN = ..\\..\\libapps$(LIBEXT)
else
BIN = ../../libapps$(LIBEXT)
endif
endif
ifeq ($(WINTOOL),y)
INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}"
else
INSTALL_DIR = $(BIN_DIR)
endif
CONFIG_EXAMPLES_PROC_TEST_PROGNAME ?= proc_test$(EXEEXT)
PROGNAME = $(CONFIG_EXAMPLES_PROC_TEST_PROGNAME)
ROOTDEPPATH = --dep-path .
# Common build
VPATH =
all: .built
.PHONY: clean depend distclean
$(AOBJS): %$(OBJEXT): %.S
$(call ASSEMBLE, $<, $@)
$(COBJS) $(MAINOBJ): %$(OBJEXT): %.c
$(call COMPILE, $<, $@)
.built: $(OBJS)
$(call ARCHIVE, $(BIN), $(OBJS))
@touch .built
ifeq ($(CONFIG_BUILD_KERNEL),y)
$(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ)
@echo "LD: $(PROGNAME)"
$(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) -o $(INSTALL_DIR)$(DELIM)$(PROGNAME) $(ARCHCRT0OBJ) $(MAINOBJ) $(LDLIBS)
$(Q) $(NM) -u $(INSTALL_DIR)$(DELIM)$(PROGNAME)
install: $(BIN_DIR)$(DELIM)$(PROGNAME)
else
install:
endif
ifeq ($(CONFIG_BUILTIN_APPS)$(CONFIG_EXAMPLES_PROC_TEST),yy)
$(BUILTIN_REGISTRY)$(DELIM)$(APPNAME)_main.bdat: $(DEPCONFIG) Makefile
$(Q) $(call REGISTER,$(APPNAME),$(APPNAME)_main,$(THREADEXEC),$(PRIORITY),$(STACKSIZE))
context: $(BUILTIN_REGISTRY)$(DELIM)$(APPNAME)_main.bdat
else
context:
endif
.depend: Makefile $(SRCS)
@$(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep
@touch $@
depend: .depend
clean:
$(call DELFILE, .built)
$(call CLEAN)
distclean: clean
$(call DELFILE, Make.dep)
$(call DELFILE, .depend)
-include Make.dep
.PHONY: preconfig
preconfig:
| {
"content_hash": "f9cb6a3de45930d56308f4c8b4486063",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 111,
"avg_line_length": 19.49056603773585,
"alnum_prop": 0.6442400774443369,
"repo_name": "kimusan/TizenRT",
"id": "1948cdae73207c6e6ca6738c704a5e9e63962058",
"size": "4605",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apps/examples/proc_test/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "225006"
},
{
"name": "Batchfile",
"bytes": "39014"
},
{
"name": "C",
"bytes": "24550679"
},
{
"name": "C++",
"bytes": "646285"
},
{
"name": "HTML",
"bytes": "2149"
},
{
"name": "Makefile",
"bytes": "518481"
},
{
"name": "Objective-C",
"bytes": "90599"
},
{
"name": "Perl",
"bytes": "2687"
},
{
"name": "Python",
"bytes": "31505"
},
{
"name": "Shell",
"bytes": "139199"
},
{
"name": "Tcl",
"bytes": "325812"
}
],
"symlink_target": ""
} |
package com.csy.maksmaigin.mvc.view.viewholder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import butterknife.ButterKnife;
public abstract class CommonViewHolder extends RecyclerView.ViewHolder {
public CommonViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public abstract void bindData(Object object);
}
| {
"content_hash": "a86c5ddfd6b9d874e7c9a5da74729ee0",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 72,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.7625,
"repo_name": "chensy-and/maksmaigin",
"id": "7da556db0c55ab1507faac57310815f4de4751de",
"size": "400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maksmaigin/app/src/main/java/com/csy/maksmaigin/mvc/view/viewholder/CommonViewHolder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4344"
},
{
"name": "CSS",
"bytes": "3683"
},
{
"name": "HTML",
"bytes": "11221"
},
{
"name": "Java",
"bytes": "1239658"
},
{
"name": "JavaScript",
"bytes": "29044"
},
{
"name": "Objective-C",
"bytes": "34607"
},
{
"name": "Ruby",
"bytes": "228"
}
],
"symlink_target": ""
} |
package org.codeandmagic.android;
/**
* Implementation of {@link TextStyle} defining the possible values for the 'textStyle' attribute
* using the Roboto font.
* Created by evelina on 16/01/2014.
*/
public enum RobotoTextStyle implements TextStyle {
NORMAL("normal", "roboto/Roboto-Regular.ttf"),
LIGHT("light", "roboto/Roboto-Light.ttf"),
BOLD("bold", "roboto/Roboto-Bold.ttf"),
CONDENSED("condensed", "roboto/RobotoCondensed-Regular.ttf"),
CONDENSED_LIGHT("condensedLight", "roboto/RobotoCondensed-Light.ttf"),
CONDENSED_BOLD("condensedBold", "roboto/RobotoCondensed-Bold.ttf");
private String mName;
private String mFontName;
RobotoTextStyle(String name, String fontName) {
mName = name;
mFontName = fontName;
}
@Override
public String getFontName() {
return mFontName;
}
@Override
public String getName() {
return mName;
}
}
| {
"content_hash": "e2ce6e5eade446536b869b12746fe164",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 97,
"avg_line_length": 27.5,
"alnum_prop": 0.679144385026738,
"repo_name": "CodeAndMagic/TypefaceLibrary",
"id": "489545430b0f0432317d895d192df31ac62bd365",
"size": "935",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Library/src/main/java/org/codeandmagic/android/RobotoTextStyle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "841"
},
{
"name": "Java",
"bytes": "12987"
},
{
"name": "Shell",
"bytes": "7484"
}
],
"symlink_target": ""
} |
..
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
====================================
Heat Stack Lifecycle Scheduler Hints
====================================
This is a mechanism whereby when heat processes a stack with Server or Volume
resources, the stack id, root stack id, stack resource uuid, stack resource
name and the path in the stack can be passed by heat to nova and cinder as
scheduler hints.
Enabling the scheduler hints
----------------------------
By default, passing the lifecycle scheduler hints is disabled. To enable it,
set stack_scheduler_hints to True in heat.conf.
The hints
---------
When heat processes a stack, and the feature is enabled, the stack id, root
stack id, stack resource uuid, stack resource name, and the path in the stack
(as a list of comma delimited strings of stackresourcename and stackname) will
be passed by heat to nova and cinder as scheduler hints.
Purpose
-------
A heat provider may have a need for custom code to examine stack requests
prior to performing the operations to create or update a stack. After the
custom code completes, the provider may want to provide hints to the nova
or cinder schedulers with stack related identifiers, for processing by
any custom scheduler plug-ins configured for nova or cinder.
| {
"content_hash": "8f5edd3ab3a20cb2385ad6070e76be68",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 79,
"avg_line_length": 44.048780487804876,
"alnum_prop": 0.7220376522702104,
"repo_name": "cwolferh/heat-scratch",
"id": "44b14ebf4d63471eef29146695c734d79aca76c4",
"size": "1806",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc/source/developing_guides/schedulerhints.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "8338769"
},
{
"name": "Shell",
"bytes": "56516"
}
],
"symlink_target": ""
} |
% CVT-B algorithm
clear all
close all
clc
input_image = int32(imread('flowergray.jpg'));
input_image = imresize(input_image, [50 50]);
[width height] = size(input_image);
old_generators = [50 124 100];
new_generators = zeros(size(old_generators));
voronoi_clusters = Calculate_Voronoi_Clusters(input_image, old_generators);
CVT_Old_Energy = zeros(size(old_generators));
for k = 1 : size(old_generators, 2)
CVT_Old_Energy(k) = Calculate_CVT_Energy(voronoi_clusters, input_image, old_generators(k), k);
end
for l = 1 : size(old_generators, 2)
for k = 1 : size(old_generators, 2)
if(l ~= k)
voronoi_l = voronoi_clusters(:,:,l);
voronoi_k = voronoi_clusters(:,:,k);
for y = 1 : width
for x = 1 : height
if(voronoi_l(x, y) == 1)
assumed_mean = input_image(x, y);
CVT_New_Energy = Calculate_CVT_Energy(voronoi_k, input_image, assumed_mean, 1)
end
end
end
end
end
end
| {
"content_hash": "483d2d96b5219a1db0918b4d7caf5797",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 102,
"avg_line_length": 31.205882352941178,
"alnum_prop": 0.5702167766258247,
"repo_name": "sriravic/ewcvt",
"id": "3ff6e7062fd4fdbb4f1dcc38c1e4b7f9ece7ec09",
"size": "1061",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CVTB.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Matlab",
"bytes": "874"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="generator" content="JsDoc Toolkit" />
<title>JsDoc Reference - AutoFill#s.border</title>
<link href="../css/default.css" type="text/css" rel="stylesheet" media="all" />
</head>
<body>
<div id="header">
</div>
<div class="index">
<div class="menu">
<!-- begin publish.classesIndex -->
<div align="center"><a href="../index.html">Class Index</a> | <a href="../files.html">File Index</a></div>
<h2 class="heading1">Classes</h2>
<ul class="classList">
<li><a href="../symbols/_global_.html">_global_</a></li>
<li><a href="../symbols/AutoFill.html">AutoFill</a></li>
<li><a href="../symbols/AutoFill%23dom.html">AutoFill#dom</a></li>
<li><a href="../symbols/AutoFill%23s.html">AutoFill#s</a></li>
<li><a href="../symbols/AutoFill%23s.border.html">AutoFill#s.border</a></li>
<li><a href="../symbols/AutoFill%23s.columns.html">AutoFill#s.columns</a></li>
<li><a href="../symbols/AutoFill%23s.drag.html">AutoFill#s.drag</a></li>
<li><a href="../symbols/AutoFill%23s.filler.html">AutoFill#s.filler</a></li>
<li><a href="../symbols/AutoFill%23s.screen.html">AutoFill#s.screen</a></li>
<li><a href="../symbols/AutoFill%23s.scroller.html">AutoFill#s.scroller</a></li>
</ul>
<!-- end publish.classesIndex -->
</div>
<div class="fineprint" style="clear:both">
Generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blank">JsDoc Toolkit</a> 2.4.0 on Sat Oct 30 2010 08:18:59 GMT+0100 (BST)<br />
HTML template: <a href="http://www.thebrightlines.com/2010/05/06/new-template-for-jsdoctoolkit-codeview/" target="_blank">Codeview</a>
</div>
</div>
<div class="content">
<div class="innerContent">
<h1 class="classTitle">
Namespace <span>AutoFill#s.border</span>
</h1>
<p class="description summary">
Cached information about the border display
<br /><em>Defined in: </em> <a href="../symbols/src/js_AutoFill.js.html">AutoFill.js</a>.
</p>
<div class="props">
<table class="summaryTable" cellspacing="0" summary="A summary of the constructor documented in the class AutoFill#s.border.">
<caption>Namespace Summary</caption>
<thead>
<tr>
<th scope="col">Constructor Attributes</th>
<th scope="col">Constructor Name and Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="attributes"> </td>
<td class="nameDescription" >
<div class="fixedFont">
<b><a href="../symbols/AutoFill%23s.border.html#constructor">AutoFill#s.border</a></b>
</div>
<div class="description"></div>
</td>
</tr>
</tbody>
</table>
</div>
<!--
#### METHODS SUMMARY
-->
<!--
#### EVENTS SUMMARY
-->
<!--
#### CONSTRUCTOR DETAILS
-->
<div class="details props">
<div class="innerProps">
<a name="constructor"></a>
<div class="sectionTitle">
Namespace Detail
</div>
<div class="fixedFont">
<b>AutoFill#s.border</b>
</div>
<div class="description">
</div>
</div>
</div>
<!--
#### FIELD DETAILS
-->
<!--
#### METHOD DETAILS
-->
<!--
#### EVENT DETAILS
-->
</div>
</div>
</body>
</html>
| {
"content_hash": "fdcf4b0b9dfc61723ee0410ada2ba978",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 155,
"avg_line_length": 23.742138364779873,
"alnum_prop": 0.5573509933774834,
"repo_name": "omeganetresearch/SoNetCMS",
"id": "8da040b39848e541ddef692780a7e289548669d6",
"size": "3775",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "assets/core/resources/filemanager/scripts/DataTables-1.7.4/extras/AutoFill/media/docs/symbols/AutoFill#s.border.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "5668"
},
{
"name": "CSS",
"bytes": "275870"
},
{
"name": "HTML",
"bytes": "1618869"
},
{
"name": "JavaScript",
"bytes": "667781"
},
{
"name": "PHP",
"bytes": "1407595"
}
],
"symlink_target": ""
} |
{% macro scenario_tabs(selected,num,path, id) %}
<div class="section-tabs js-tabs clearfix mb20">
<ul>
{% set navs = [
{url:"timeline-review",label:"Timeline"},
{url:"contact",label:"Contact"},
{url:"details-fme",label:"Medical"},
{url:"evidence-portal",label:"Evidence"},
{url:"appointment",label:"Appointment"}
] %}
{% for item in navs %}
<li {% if item.url == selected %} class="active"{% endif %}><a href="/fha/scrutiny-scenarios/baseline-new-detail-bar/{{ item.url }}/">{{ item.label }}</a></li>
{% endfor %}
</ul>
</div>
{% endmacro %}
| {
"content_hash": "950940dcba59dadd8776fc10a4734517",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 167,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.5576923076923077,
"repo_name": "dwpdigitaltech/healthanddisability",
"id": "82e169eb245bae563f416adb3b406e640ff81def",
"size": "624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/fha/scrutiny-scenarios/baseline-new-detail-bar/_macros_nav_baseline.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "58296"
},
{
"name": "HTML",
"bytes": "934977"
},
{
"name": "JavaScript",
"bytes": "66322"
},
{
"name": "Shell",
"bytes": "1495"
}
],
"symlink_target": ""
} |
<?php
namespace Ajgarlag\Psr15\Router\RequestHandler;
use Ajgarlag\Psr15\Router\Matcher\RequestMatcher;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class Route implements RouteInterface
{
private RequestMatcher $requestMatcher;
private RequestHandlerInterface $requestHandler;
public function __construct(RequestMatcher $requestMatcher, RequestHandlerInterface $requestHandler)
{
$this->requestMatcher = $requestMatcher;
$this->requestHandler = $requestHandler;
}
public function match(ServerRequestInterface $request): bool
{
return $this->requestMatcher->match($request);
}
public function getRequestHandler(): RequestHandlerInterface
{
return $this->requestHandler;
}
}
| {
"content_hash": "234ac8a3e36dd6d81dd0110a0c6c6602",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 104,
"avg_line_length": 26.096774193548388,
"alnum_prop": 0.7441285537700866,
"repo_name": "ajgarlag/psr15-router",
"id": "ad731d0c8cfac6029e5c193b29a71ad68c179317",
"size": "1040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RequestHandler/Route.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "45043"
}
],
"symlink_target": ""
} |
<?php
namespace fennec\db\record;
use Yii;
use yii\behaviors\SluggableBehavior;
abstract class SluggableRecord extends ActiveRecord
{
abstract public function getSlugAttribute();
public function behaviors()
{
$behaviors = [
[
'class' => SluggableBehavior::className(),
'attribute' => $this->getSlugAttribute(),
]
];
return array_merge(parent::behaviors(),$behaviors);
}
} | {
"content_hash": "33444340cb6f6f8574b291bdc0d46d06",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 55,
"avg_line_length": 17.16,
"alnum_prop": 0.655011655011655,
"repo_name": "cherifGsoul/fennec-cms",
"id": "375f67845885c169adeab691c7b470e5ea6434a4",
"size": "429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/db/record/SluggableRecord.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "200"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "3150"
},
{
"name": "HTML",
"bytes": "1782"
},
{
"name": "JavaScript",
"bytes": "2870"
},
{
"name": "PHP",
"bytes": "252098"
}
],
"symlink_target": ""
} |
import logging
import StringIO
import time
import unittest
from xml.etree import ElementTree
from nova import vendor
from tornado import ioloop
from twisted.internet import defer
from nova import flags
from nova import rpc
from nova import test
from nova.auth import users
from nova.compute import node
from nova.endpoint import api
from nova.endpoint import cloud
FLAGS = flags.FLAGS
class CloudTestCase(test.BaseTestCase):
def setUp(self):
super(CloudTestCase, self).setUp()
self.flags(fake_libvirt=True,
fake_storage=True,
fake_users=True)
self.conn = rpc.Connection.instance()
logging.getLogger().setLevel(logging.DEBUG)
# set up our cloud
self.cloud = cloud.CloudController()
self.cloud_consumer = rpc.AdapterConsumer(connection=self.conn,
topic=FLAGS.cloud_topic,
proxy=self.cloud)
self.injected.append(self.cloud_consumer.attach_to_tornado(self.ioloop))
# set up a node
self.node = node.Node()
self.node_consumer = rpc.AdapterConsumer(connection=self.conn,
topic=FLAGS.compute_topic,
proxy=self.node)
self.injected.append(self.node_consumer.attach_to_tornado(self.ioloop))
try:
users.UserManager.instance().create_user('admin', 'admin', 'admin')
except: pass
admin = users.UserManager.instance().get_user('admin')
project = users.UserManager.instance().create_project('proj', 'admin', 'proj')
self.context = api.APIRequestContext(handler=None,project=project,user=admin)
def tearDown(self):
users.UserManager.instance().delete_project('proj')
users.UserManager.instance().delete_user('admin')
def test_console_output(self):
if FLAGS.fake_libvirt:
logging.debug("Can't test instances without a real virtual env.")
return
instance_id = 'foo'
inst = yield self.node.run_instance(instance_id)
output = yield self.cloud.get_console_output(self.context, [instance_id])
logging.debug(output)
self.assert_(output)
rv = yield self.node.terminate_instance(instance_id)
def test_run_instances(self):
if FLAGS.fake_libvirt:
logging.debug("Can't test instances without a real virtual env.")
return
image_id = FLAGS.default_image
instance_type = FLAGS.default_instance_type
max_count = 1
kwargs = {'image_id': image_id,
'instance_type': instance_type,
'max_count': max_count}
rv = yield self.cloud.run_instances(self.context, **kwargs)
# TODO: check for proper response
instance = rv['reservationSet'][0][rv['reservationSet'][0].keys()[0]][0]
logging.debug("Need to watch instance %s until it's running..." % instance['instance_id'])
while True:
rv = yield defer.succeed(time.sleep(1))
info = self.cloud._get_instance(instance['instance_id'])
logging.debug(info['state'])
if info['state'] == node.Instance.RUNNING:
break
self.assert_(rv)
if not FLAGS.fake_libvirt:
time.sleep(45) # Should use boto for polling here
for reservations in rv['reservationSet']:
# for res_id in reservations.keys():
# logging.debug(reservations[res_id])
# for instance in reservations[res_id]:
for instance in reservations[reservations.keys()[0]]:
logging.debug("Terminating instance %s" % instance['instance_id'])
rv = yield self.node.terminate_instance(instance['instance_id'])
def test_instance_update_state(self):
def instance(num):
return {
'reservation_id': 'r-1',
'instance_id': 'i-%s' % num,
'image_id': 'ami-%s' % num,
'private_dns_name': '10.0.0.%s' % num,
'dns_name': '10.0.0%s' % num,
'ami_launch_index': str(num),
'instance_type': 'fake',
'availability_zone': 'fake',
'key_name': None,
'kernel_id': 'fake',
'ramdisk_id': 'fake',
'groups': ['default'],
'product_codes': None,
'state': 0x01,
'user_data': ''
}
rv = self.cloud._format_instances(self.context)
self.assert_(len(rv['reservationSet']) == 0)
# simulate launch of 5 instances
# self.cloud.instances['pending'] = {}
#for i in xrange(5):
# inst = instance(i)
# self.cloud.instances['pending'][inst['instance_id']] = inst
#rv = self.cloud._format_instances(self.admin)
#self.assert_(len(rv['reservationSet']) == 1)
#self.assert_(len(rv['reservationSet'][0]['instances_set']) == 5)
# report 4 nodes each having 1 of the instances
#for i in xrange(4):
# self.cloud.update_state('instances', {('node-%s' % i): {('i-%s' % i): instance(i)}})
# one instance should be pending still
#self.assert_(len(self.cloud.instances['pending'].keys()) == 1)
# check that the reservations collapse
#rv = self.cloud._format_instances(self.admin)
#self.assert_(len(rv['reservationSet']) == 1)
#self.assert_(len(rv['reservationSet'][0]['instances_set']) == 5)
# check that we can get metadata for each instance
#for i in xrange(4):
# data = self.cloud.get_metadata(instance(i)['private_dns_name'])
# self.assert_(data['meta-data']['ami-id'] == 'ami-%s' % i)
| {
"content_hash": "0ebb97e8a0ff18c47024ecee32d39e75",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 98,
"avg_line_length": 40.142857142857146,
"alnum_prop": 0.5695644805965091,
"repo_name": "joshuamckenty/yolo-octo-wookie",
"id": "9df83ec625ab14d33c41df8dff1c1d52493d7eab",
"size": "6678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nova/tests/cloud_unittest.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "459821"
},
{
"name": "Shell",
"bytes": "12630"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="animated-vector-drawable-24.2.1">
<CLASSES>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/24.2.1/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/24.2.1/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/android-sdks/extras/android/m2repository/com/android/support/animated-vector-drawable/24.2.1/animated-vector-drawable-24.2.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "7884eb0f4c56000a534ba2bb9c420df4",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 177,
"avg_line_length": 53.666666666666664,
"alnum_prop": 0.7049689440993789,
"repo_name": "omkarmoghe/MH-Android-Workshop",
"id": "29f7a722de821be8b18f0e6e1039ad49f161890c",
"size": "644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/animated_vector_drawable_24_2_1.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "10802"
}
],
"symlink_target": ""
} |
package com.buddycloud;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.Window;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.buddycloud.fragments.ChannelStreamFragment;
import com.buddycloud.fragments.ContentFragment;
import com.buddycloud.fragments.GenericChannelsFragment;
import com.buddycloud.fragments.SearchChannelsFragment;
import com.buddycloud.fragments.SlidingFragmentActivity;
import com.buddycloud.fragments.SubscribedChannelsFragment;
import com.buddycloud.log.Logger;
import com.buddycloud.model.SyncModel;
import com.buddycloud.notifications.GCMEvent;
import com.buddycloud.notifications.GCMIntentService;
import com.buddycloud.notifications.GCMUtils;
import com.buddycloud.preferences.Preferences;
import com.buddycloud.utils.ActionbarUtil;
import com.buddycloud.utils.Backstack;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenedListener;
public class MainActivity extends SlidingFragmentActivity {
private static final String TAG = MainActivity.class.getName();
private String myJid;
private Backstack backStack;
private ChannelStreamFragment channelStreamFrag;
private SubscribedChannelsFragment subscribedFrag;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
ActionbarUtil.showActionBar(this, getString(R.string.app_name), true);
setSlidingActionBarEnabled(false);
setBehindContentView(R.layout.menu_frame);
setContentView(R.layout.content_frame);
this.backStack = new Backstack(this);
if (savedInstanceState != null) {
channelStreamFrag = (ChannelStreamFragment) getSupportFragmentManager().getFragment(
savedInstanceState, "mContent");
}
// Check if the welcome screen visible for login.
// Otherwise, show the main screen.
if (shouldLogin()) {
Intent welcomeActivity = new Intent();
welcomeActivity.setClass(getApplicationContext(), WelcomeActivity.class);
startActivityForResult(welcomeActivity, WelcomeActivity.REQUEST_CODE);
} else {
startActivity();
}
}
// You need to do the Play Services APK check here too.
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (channelStreamFrag != null) {
getSupportFragmentManager().putFragment(outState, "mContent", channelStreamFrag);
}
}
private boolean shouldLogin() {
return Preferences.getPreference(this, Preferences.MY_CHANNEL_JID) == null ||
Preferences.getPreference(this, Preferences.PASSWORD) == null ||
Preferences.getPreference(this, Preferences.API_ADDRESS) == null;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return false;
}
return true;
}
@Override
public void onBackPressed() {
if (getSlidingMenu().isMenuShowing()) {
finish();
} else {
if (!backStack.pop()) {
getSlidingMenu().showMenu();
}
}
}
private ContentFragment getCurrentFragment() {
if (getSlidingMenu().isMenuShowing()) {
return subscribedFrag;
}
return channelStreamFrag;
}
public ChannelStreamFragment getChannelStreamFrag() {
return channelStreamFrag;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WelcomeActivity.REQUEST_CODE) {
if (resultCode == WelcomeActivity.RESULT_CODE_OK) {
startActivity();
} else {
finish();
}
} else if (requestCode == SearchActivity.REQUEST_CODE) {
if (data != null) {
String channelJid = data.getStringExtra(GenericChannelsFragment.CHANNEL);
String filter = data.getStringExtra(SearchChannelsFragment.FILTER);
showChannelFragment(channelJid);
backStack.pushSearch(filter);
} else {
backStack.pop();
}
} else if (requestCode == GenericChannelActivity.REQUEST_CODE) {
if (data != null) {
final String channelJid = data.getStringExtra(GenericChannelsFragment.CHANNEL);
showChannelFragment(channelJid);
backStack.pushGeneric(data.getBundleExtra(GenericChannelsFragment.INPUT_ARGS));
} else {
backStack.pop();
}
} else if (requestCode == PostNewTopicActivity.REQUEST_CODE) {
if (resultCode == PostNewTopicActivity.NEW_POST_CREATED_RESULT) {
channelStreamFrag.synchPostStream();
}
else if (data != null) {
final String channelJid = data.getStringExtra(GenericChannelsFragment.CHANNEL);
showChannelFragment(channelJid);
backStack.pushGeneric(data.getBundleExtra(GenericChannelsFragment.INPUT_ARGS));
}
else {
backStack.pop();
}
}
}
@Override
public void onAttachedToWindow() {
Uri data = getIntent().getData();
String scheme = getIntent().getScheme();
String channelJid = null;
if (data != null && scheme != null && scheme.equals(Preferences.BUDDYCLOUD_SCHEME)) {
channelJid = data.getSchemeSpecificPart();
}
if (channelJid == null) {
channelJid = getIntent().getStringExtra(GenericChannelsFragment.CHANNEL);
}
if (channelJid == null) {
showChannelFragment(myJid, false, false);
showMenu();
} else {
showChannelFragment(channelJid);
}
String event = getIntent().getStringExtra(GCMIntentService.GCM_NOTIFICATION_EVENT);
if (event != null) {
GCMEvent gcmEvent = GCMEvent.valueOf(event);
process(gcmEvent);
}
super.onAttachedToWindow();
}
private void startActivity() {
this.myJid = (String) Preferences.getPreference(this, Preferences.MY_CHANNEL_JID);
registerInGCM();
addMenuFragment();
customizeMenu();
}
private void process(GCMEvent event) {
switch (event) {
case POST_AFTER_MY_POST:
case POST_ON_SUBSCRIBED_CHANNEL:
case POST_ON_MY_CHANNEL:
case MENTION:
GCMUtils.clearGCMAuthors(this);
default:
break;
}
}
private void registerInGCM() {
try {
GCMUtils.issueGCMRegistration(this);
} catch (Exception e) {
Logger.error(TAG, "Failed to register in GCM.", e);
}
}
public Backstack getBackStack() {
return backStack;
}
public ChannelStreamFragment showChannelFragment(String channelJid) {
return showChannelFragment(channelJid, false, true);
}
public ChannelStreamFragment showChannelFragment(String channelJid,
boolean pushPreviousToBackstack, boolean clearCounters) {
if (!pushPreviousToBackstack && channelStreamFrag != null) {
String previousChannel = channelStreamFrag.getArguments().getString(
GenericChannelsFragment.CHANNEL);
if (previousChannel != null) {
getBackStack().pushChannel(previousChannel);
}
}
this.channelStreamFrag = new ChannelStreamFragment();
Bundle args = new Bundle();
args.putString(GenericChannelsFragment.CHANNEL, channelJid);
channelStreamFrag.setArguments(args);
if (clearCounters) {
SyncModel.getInstance().visitChannel(this, channelJid);
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, channelStreamFrag)
.commitAllowingStateLoss();
if (getSlidingMenu().isMenuShowing()) {
getSlidingMenu().showContent();
} else {
fragmentChanged();
}
return channelStreamFrag;
}
private void customizeMenu() {
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.15f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
sm.setOnOpenedListener(new OnOpenedListener() {
@Override
public void onOpened() {
fragmentChanged();
}
});
sm.setOnClosedListener(new OnClosedListener() {
@Override
public void onClosed() {
fragmentChanged();
}
});
}
private void addMenuFragment() {
this.subscribedFrag = new SubscribedChannelsFragment();
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
t.replace(R.id.menu_frame, subscribedFrag);
t.commitAllowingStateLoss();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
ContentFragment currentFragment = getCurrentFragment();
if (currentFragment != null) {
currentFragment.createOptions(menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (item.getItemId() == android.R.id.home) {
showMenu();
return true;
}
return getCurrentFragment().menuItemSelected(featureId, item);
}
private void fragmentChanged() {
getCurrentFragment().attached(this);
supportInvalidateOptionsMenu();
}
}
| {
"content_hash": "17bcebf92d0d160dc7af526db8e7d4e6",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 87,
"avg_line_length": 29.81290322580645,
"alnum_prop": 0.7156459640770396,
"repo_name": "buddycloud/buddycloud-android",
"id": "3cc9341c0d3f0b22db50eb172a411c756deb8faf",
"size": "9242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/buddycloud/MainActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "486191"
},
{
"name": "Shell",
"bytes": "810"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.