text stringlengths 2 1.04M | meta dict |
|---|---|
"""Tests for Kaleidescape config flow."""
import dataclasses
from unittest.mock import AsyncMock
from homeassistant.components.kaleidescape.const import DOMAIN
from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import MOCK_HOST, MOCK_SSDP_DISCOVERY_INFO
from tests.common import MockConfigEntry
async def test_user_config_flow_success(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test user config flow success."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: MOCK_HOST}
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert "data" in result
assert result["data"][CONF_HOST] == MOCK_HOST
async def test_user_config_flow_bad_connect_errors(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test errors when connection error occurs."""
mock_device.connect.side_effect = ConnectionError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
async def test_user_config_flow_unsupported_device_errors(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test errors when connecting to unsupported device."""
mock_device.is_server_only = True
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "unsupported"}
async def test_user_config_flow_device_exists_abort(
hass: HomeAssistant, mock_device: AsyncMock, mock_integration: MockConfigEntry
) -> None:
"""Test flow aborts when device already configured."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: MOCK_HOST}
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_ssdp_config_flow_success(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test ssdp config flow success."""
discovery_info = dataclasses.replace(MOCK_SSDP_DISCOVERY_INFO)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=discovery_info
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
await hass.async_block_till_done()
assert result["type"] == FlowResultType.CREATE_ENTRY
assert "data" in result
assert result["data"][CONF_HOST] == MOCK_HOST
async def test_ssdp_config_flow_bad_connect_aborts(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test abort when connection error occurs."""
mock_device.connect.side_effect = ConnectionError
discovery_info = dataclasses.replace(MOCK_SSDP_DISCOVERY_INFO)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=discovery_info
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_ssdp_config_flow_unsupported_device_aborts(
hass: HomeAssistant, mock_device: AsyncMock
) -> None:
"""Test abort when connecting to unsupported device."""
mock_device.is_server_only = True
discovery_info = dataclasses.replace(MOCK_SSDP_DISCOVERY_INFO)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=discovery_info
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "unsupported"
| {
"content_hash": "9de7319e2de7d256f5f4d2a3616045f1",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 82,
"avg_line_length": 34.30952380952381,
"alnum_prop": 0.6985889428637521,
"repo_name": "w1ll1am23/home-assistant",
"id": "8171ed0955bb47a829fdd227153fe2db48fc75cd",
"size": "4323",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "tests/components/kaleidescape/test_config_flow.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2963"
},
{
"name": "PLSQL",
"bytes": "840"
},
{
"name": "Python",
"bytes": "52277012"
},
{
"name": "Shell",
"bytes": "6252"
}
],
"symlink_target": ""
} |
using System;
using System.Runtime.CompilerServices;
namespace System.Globalization {
[ScriptIgnoreNamespace]
[ScriptImport]
public sealed class NumberFormatInfo {
private NumberFormatInfo() {
}
[ScriptField]
[ScriptName("nan")]
public string NaNSymbol {
get {
return null;
}
}
[ScriptField]
[ScriptName("neg")]
public string NegativeSign {
get {
return null;
}
}
[ScriptField]
[ScriptName("pos")]
public string PositiveSign {
get {
return null;
}
}
[ScriptField]
[ScriptName("negInf")]
public string NegativeInfinityText {
get {
return null;
}
}
[ScriptField]
[ScriptName("posInf")]
public string PositiveInfinityText {
get {
return null;
}
}
[ScriptField]
[ScriptName("per")]
public string PercentSymbol {
get {
return null;
}
}
[ScriptField]
[ScriptName("perGW")]
public int[] PercentGroupSizes {
get {
return null;
}
}
[ScriptField]
[ScriptName("perDD")]
public int PercentDecimalDigits {
get {
return 0;
}
}
[ScriptField]
[ScriptName("perDS")]
public string PercentDecimalSeparator {
get {
return null;
}
}
[ScriptField]
[ScriptName("perGS")]
public string PercentGroupSeparator {
get {
return null;
}
}
[ScriptField]
[ScriptName("perNP")]
public string PercentNegativePattern {
get {
return null;
}
}
[ScriptField]
[ScriptName("perPP")]
public string PercentPositivePattern {
get {
return null;
}
}
[ScriptField]
[ScriptName("cur")]
public string CurrencySymbol {
get {
return null;
}
}
[ScriptField]
[ScriptName("curGW")]
public int[] CurrencyGroupSizes {
get {
return null;
}
}
[ScriptField]
[ScriptName("curDD")]
public int CurrencyDecimalDigits {
get {
return 0;
}
}
[ScriptField]
[ScriptName("curDS")]
public string CurrencyDecimalSeparator {
get {
return null;
}
}
[ScriptField]
[ScriptName("curGS")]
public string CurrencyGroupSeparator {
get {
return null;
}
}
[ScriptField]
[ScriptName("curNP")]
public string CurrencyNegativePattern {
get {
return null;
}
}
[ScriptField]
[ScriptName("curPP")]
public string CurrencyPositivePattern {
get {
return null;
}
}
[ScriptField]
[ScriptName("gw")]
public int[] NumberGroupSizes {
get {
return null;
}
}
[ScriptField]
[ScriptName("dd")]
public int NumberDecimalDigits {
get {
return 0;
}
}
[ScriptField]
[ScriptName("ds")]
public string NumberDecimalSeparator {
get {
return null;
}
}
[ScriptField]
[ScriptName("gs")]
public string NumberGroupSeparator {
get {
return null;
}
}
}
}
| {
"content_hash": "c134d27853ed413be557dfa284a88bc4",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 48,
"avg_line_length": 20.573604060913706,
"alnum_prop": 0.4246237355045645,
"repo_name": "x335/scriptsharp",
"id": "60ab5ae0a51f4bd508d380b84ddd700ae5529f00",
"size": "4200",
"binary": false,
"copies": "2",
"ref": "refs/heads/cc",
"path": "src/Core/CoreLib/Globalization/NumberFormatInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "577"
},
{
"name": "C#",
"bytes": "3516019"
},
{
"name": "CSS",
"bytes": "4920"
},
{
"name": "HTML",
"bytes": "51098"
},
{
"name": "JavaScript",
"bytes": "115046"
},
{
"name": "PowerShell",
"bytes": "6336"
}
],
"symlink_target": ""
} |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Provides information about the context menu state. The ethods of this class
/// can only be accessed on browser process the UI thread.
/// </summary>
public sealed unsafe partial class CefContextMenuParams
{
/// <summary>
/// Returns the X coordinate of the mouse where the context menu was invoked.
/// Coords are relative to the associated RenderView's origin.
/// </summary>
public int X
{
get { return cef_context_menu_params_t.get_xcoord(_self); }
}
/// <summary>
/// Returns the Y coordinate of the mouse where the context menu was invoked.
/// Coords are relative to the associated RenderView's origin.
/// </summary>
public int Y
{
get { return cef_context_menu_params_t.get_ycoord(_self); }
}
/// <summary>
/// Returns flags representing the type of node that the context menu was
/// invoked on.
/// </summary>
public CefContextMenuTypeFlags ContextMenuType
{
get { return cef_context_menu_params_t.get_type_flags(_self); }
}
/// <summary>
/// Returns the URL of the link, if any, that encloses the node that the
/// context menu was invoked on.
/// </summary>
public string LinkUrl
{
get
{
var n_result = cef_context_menu_params_t.get_link_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the link URL, if any, to be used ONLY for "copy link address". We
/// don't validate this field in the frontend process.
/// </summary>
public string UnfilteredLinkUrl
{
get
{
var n_result = cef_context_menu_params_t.get_unfiltered_link_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the source URL, if any, for the element that the context menu was
/// invoked on. Example of elements with source URLs are img, audio, and video.
/// </summary>
public string SourceUrl
{
get
{
var n_result = cef_context_menu_params_t.get_source_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns true if the context menu was invoked on an image which has
/// non-empty contents.
/// </summary>
public bool HasImageContents
{
get { return cef_context_menu_params_t.has_image_contents(_self) != 0; }
}
/// <summary>
/// Returns the URL of the top level page that the context menu was invoked on.
/// </summary>
public string PageUrl
{
get
{
var n_result = cef_context_menu_params_t.get_page_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the URL of the subframe that the context menu was invoked on.
/// </summary>
public string FrameUrl
{
get
{
var n_result = cef_context_menu_params_t.get_frame_url(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the character encoding of the subframe that the context menu was
/// invoked on.
/// </summary>
public string FrameCharset
{
get
{
var n_result = cef_context_menu_params_t.get_frame_charset(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the type of context node that the context menu was invoked on.
/// </summary>
public CefContextMenuMediaType MediaType
{
get { return cef_context_menu_params_t.get_media_type(_self); }
}
/// <summary>
/// Returns flags representing the actions supported by the media element, if
/// any, that the context menu was invoked on.
/// </summary>
public CefContextMenuMediaStateFlags MediaState
{
get { return cef_context_menu_params_t.get_media_state_flags(_self); }
}
/// <summary>
/// Returns the text of the selection, if any, that the context menu was
/// invoked on.
/// </summary>
public string SelectionText
{
get
{
var n_result = cef_context_menu_params_t.get_selection_text(_self);
return cef_string_userfree.ToString(n_result);
}
}
/// <summary>
/// Returns the text of the misspelled word, if any, that the context menu was
/// invoked on.
/// </summary>
public string GetMisspelledWord()
{
var n_result = cef_context_menu_params_t.get_misspelled_word(_self);
return cef_string_userfree.ToString(n_result);
}
/// <summary>
/// Returns the hash of the misspelled word, if any, that the context menu was
/// invoked on.
/// </summary>
public int GetMisspellingHash()
{
return cef_context_menu_params_t.get_misspelling_hash(_self);
}
/// <summary>
/// Returns true if suggestions exist, false otherwise. Fills in |suggestions|
/// from the spell check service for the misspelled word if there is one.
/// </summary>
public string[] GetDictionarySuggestions()
{
var n_suggestions = libcef.string_list_alloc();
cef_context_menu_params_t.get_dictionary_suggestions(_self, n_suggestions);
var suggestions = cef_string_list.ToArray(n_suggestions);
libcef.string_list_free(n_suggestions);
return suggestions;
}
/// <summary>
/// Returns true if the context menu was invoked on an editable node.
/// </summary>
public bool IsEditable
{
get { return cef_context_menu_params_t.is_editable(_self) != 0; }
}
/// <summary>
/// Returns true if the context menu was invoked on an editable node where
/// spell-check is enabled.
/// </summary>
public bool IsSpellCheckEnabled
{
get { return cef_context_menu_params_t.is_spell_check_enabled(_self) != 0; }
}
/// <summary>
/// Returns flags representing the actions supported by the editable node, if
/// any, that the context menu was invoked on.
/// </summary>
public CefContextMenuEditStateFlags EditState
{
get { return cef_context_menu_params_t.get_edit_state_flags(_self); }
}
}
}
| {
"content_hash": "1b96a6b5a75a2b6326de51e977a057a3",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 88,
"avg_line_length": 33.925581395348836,
"alnum_prop": 0.5488072388264327,
"repo_name": "rajsite/lvcef",
"id": "9ffd6f9dfd94ed5938b10f90a50ca87173c48238",
"size": "7294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xilium.cefglue/CefGlue/Classes.Proxies/CefContextMenuParams.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1918"
},
{
"name": "C",
"bytes": "98211"
},
{
"name": "C#",
"bytes": "1893550"
},
{
"name": "C++",
"bytes": "539857"
},
{
"name": "HTML",
"bytes": "2095"
},
{
"name": "LabVIEW",
"bytes": "3118"
},
{
"name": "Objective-C",
"bytes": "11097"
},
{
"name": "Python",
"bytes": "113684"
},
{
"name": "Shell",
"bytes": "34"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>concurrency-system: 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.12.2 / concurrency-system - 1.1.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">ยซ Up</a>
<h1>
concurrency-system
<small>
1.1.0
<span class="label label-info">Not compatible ๐ผ</span>
</small>
</h1>
<p>๐
<em><script>document.write(moment("2022-10-18 00:27:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-18 00:27:54 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.12.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "dev@clarus.me"
homepage: "https://github.com/coq-concurrency/system"
dev-repo: "git+https://github.com/coq-concurrency/system.git"
bug-reports: "https://github.com/coq-concurrency/system/issues"
authors: ["Guillaume Claret"]
license: "MIT"
build: [
["ruby" "pp.rb"]
["./configure.sh"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"ocaml"
"conf-ruby" {build}
"coq" {>= "8.4pl4" & < "8.6"}
"coq-error-handlers"
"coq-function-ninjas"
"coq-list-string" {>= "2.0.0"}
]
tags: [
"date:2015-11-26"
"keyword:effects"
"keyword:extraction"
]
synopsis: "Experimental library to write concurrent applications in Coq"
url {
src: "https://github.com/coq-concurrency/system/archive/1.1.0.tar.gz"
checksum: "md5=ac9441be42d767e1c9d22b487b4ce791"
}
</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-concurrency-system.1.1.0 coq.8.12.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.12.2).
The following dependencies couldn't be met:
- coq-concurrency-system -> coq < 8.6 -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
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-concurrency-system.1.1.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": "34258d9a212f99576dae48127734d15b",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 159,
"avg_line_length": 39.08771929824562,
"alnum_prop": 0.5341113105924596,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "82266c7884582947544d0960c677ea4ea920533e",
"size": "6709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.12.2/concurrency-system/1.1.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;
use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2;
/**
* @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
* @xmlType IdentifierType
* @xmlName AgencyIDType
* @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\AgencyIDType
*/
class AgencyIDType
extends _2\IdentifierType
{
} // end class AgencyIDType
| {
"content_hash": "95e8d80f83b47d00e50b78c10b2cd788",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 85,
"avg_line_length": 27.823529411764707,
"alnum_prop": 0.8033826638477801,
"repo_name": "heroicstudios/quickbooks-php-sdk",
"id": "22122681183115538065ed5e672a35a2b41954c0",
"size": "473",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "sdk/Dependencies/XSD2PHP/test/data/expected/ContactPerson1/oasis/names/specification/ubl/schema/xsd/CommonBasicComponents_2/AgencyIDType.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19489"
},
{
"name": "JavaScript",
"bytes": "47994"
},
{
"name": "PHP",
"bytes": "5852540"
},
{
"name": "Perl",
"bytes": "2024"
},
{
"name": "Shell",
"bytes": "99"
},
{
"name": "XSLT",
"bytes": "11481"
}
],
"symlink_target": ""
} |
package com.intellij.openapi.projectRoots;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.IconUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class SdkType implements SdkTypeId {
public static final ExtensionPointName<SdkType> EP_NAME = ExtensionPointName.create("com.intellij.sdkType");
private final String myName;
public SdkType(@NotNull String name) {
myName = name;
}
/**
* Returns a recommended starting path for a file chooser (where SDKs of this type are usually may be found),
* or {@code null} if not applicable/no SDKs found.
* <p/>
* E.g. for Python SDK on Unix the method may return either {@code "/usr/bin"} or {@code "/usr/bin/python"}
* (if there is only one Python interpreter installed on a host).
*/
@Nullable
public abstract String suggestHomePath();
/**
* Returns a list of all valid SDKs found on this host.
* <p/>
* E.g. for Python SDK on Unix the method may return {@code ["/usr/bin/python2", "/usr/bin/python3"]}.
*/
@NotNull
public Collection<String> suggestHomePaths() {
String home = suggestHomePath();
return home != null ? Collections.singletonList(home) : Collections.<String>emptyList();
}
/**
* If a path selected in the file chooser is not a valid SDK home path, returns an adjusted version of the path that is again
* checked for validity.
*
* @param homePath the path selected in the file chooser.
* @return the path to be used as the SDK home.
*/
@NotNull
public String adjustSelectedSdkHome(@NotNull String homePath) {
return homePath;
}
public abstract boolean isValidSdkHome(String path);
@Override
@Nullable
public String getVersionString(@NotNull Sdk sdk) {
return getVersionString(sdk.getHomePath());
}
@Nullable
public String getVersionString(String sdkHome){
return null;
}
public abstract String suggestSdkName(String currentSdkName, String sdkHome);
public void setupSdkPaths(@NotNull Sdk sdk) {}
public boolean setupSdkPaths(@NotNull Sdk sdk, @NotNull SdkModel sdkModel) {
setupSdkPaths(sdk);
return true;
}
/**
* @return Configurable object for the sdk's additional data or null if not applicable
*/
@Nullable
public abstract AdditionalDataConfigurable createAdditionalDataConfigurable(@NotNull SdkModel sdkModel, @NotNull SdkModificator sdkModificator);
@Nullable
public SdkAdditionalData loadAdditionalData(Element additional) {
return null;
}
@Override
@Nullable
public SdkAdditionalData loadAdditionalData(@NotNull Sdk currentSdk, Element additional) {
return loadAdditionalData(additional);
}
@NotNull
@Override
public String getName() {
return myName;
}
@NotNull
public abstract String getPresentableName();
public Icon getIcon() {
return null;
}
@NotNull
public String getHelpTopic() {
return "preferences.jdks";
}
@NotNull
public Icon getIconForAddAction() {
return IconUtil.getAddIcon();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SdkType)) return false;
final SdkType sdkType = (SdkType)o;
if (!myName.equals(sdkType.myName)) return false;
return true;
}
@Override
public int hashCode() {
return myName.hashCode();
}
@Override
public String toString() {
return getName();
}
@NotNull
public FileChooserDescriptor getHomeChooserDescriptor() {
final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false) {
@Override
public void validateSelectedFiles(VirtualFile[] files) throws Exception {
if (files.length != 0){
final String selectedPath = files[0].getPath();
boolean valid = isValidSdkHome(selectedPath);
if (!valid){
valid = isValidSdkHome(adjustSelectedSdkHome(selectedPath));
if (!valid) {
String message = files[0].isDirectory()
? ProjectBundle.message("sdk.configure.home.invalid.error", getPresentableName())
: ProjectBundle.message("sdk.configure.home.file.invalid.error", getPresentableName());
throw new Exception(message);
}
}
}
}
};
descriptor.setTitle(ProjectBundle.message("sdk.configure.home.title", getPresentableName()));
return descriptor;
}
@NotNull
public String getHomeFieldLabel() {
return ProjectBundle.message("sdk.configure.type.home.path", getPresentableName());
}
@Nullable
public String getDefaultDocumentationUrl(@NotNull final Sdk sdk) {
return null;
}
@Nullable
public String getDownloadSdkUrl() {
return null;
}
@NotNull
public static SdkType[] getAllTypes() {
List<SdkType> allTypes = new ArrayList<>();
Collections.addAll(allTypes, ApplicationManager.getApplication().getComponents(SdkType.class));
Collections.addAll(allTypes, Extensions.getExtensions(EP_NAME));
return allTypes.toArray(new SdkType[allTypes.size()]);
}
@NotNull
public static <T extends SdkType> T findInstance(@NotNull Class<T> sdkTypeClass) {
for (SdkType sdkType : Extensions.getExtensions(EP_NAME)) {
if (sdkTypeClass.equals(sdkType.getClass())) {
//noinspection unchecked
return (T)sdkType;
}
}
assert false;
return null;
}
public boolean isRootTypeApplicable(@NotNull OrderRootType type) {
return true;
}
/**
* If this method returns true, instead of showing the standard file path chooser when a new SDK of the type is created,
* the {@link #showCustomCreateUI} method is called.
*
* @return true if the custom create UI is supported, false otherwise.
* @since 12.0
*/
public boolean supportsCustomCreateUI() {
return false;
}
/**
* Shows the custom SDK create UI. The returned SDK needs to have the correct name and home path; the framework will call
* setupSdkPaths() on the returned SDK.
*
* @param sdkModel the list of SDKs currently displayed in the configuration dialog.
* @param parentComponent the parent component for showing the dialog.
* @param sdkCreatedCallback the callback to which the created SDK is passed.
* @since 12.0
*/
public void showCustomCreateUI(@NotNull SdkModel sdkModel, @NotNull JComponent parentComponent, @NotNull Consumer<Sdk> sdkCreatedCallback) {
}
/**
* Checks if the home directory of the specified SDK is valid. By default, checks that the directory points to a valid local
* path. Can be overridden for remote SDKs.
*
* @param sdk the SDK to validate the path for.
* @return true if the home path is valid, false otherwise.
* @since 12.1
*/
public boolean sdkHasValidPath(@NotNull Sdk sdk) {
VirtualFile homeDir = sdk.getHomeDirectory();
return homeDir != null && homeDir.isValid();
}
public String sdkPath(@NotNull VirtualFile homePath) {
return homePath.getPath();
}
}
| {
"content_hash": "177814101ec070577a1dd1f235d4dfec",
"timestamp": "",
"source": "github",
"line_count": 252,
"max_line_length": 146,
"avg_line_length": 30.214285714285715,
"alnum_prop": 0.7048857368006304,
"repo_name": "idea4bsd/idea4bsd",
"id": "6ab50e8ec4ea0b2cf2055b5ba9ae4ec4af360c79",
"size": "8214",
"binary": false,
"copies": "4",
"ref": "refs/heads/idea4bsd-master",
"path": "platform/lang-api/src/com/intellij/openapi/projectRoots/SdkType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "59458"
},
{
"name": "C",
"bytes": "224097"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "197012"
},
{
"name": "CSS",
"bytes": "197224"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2971715"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1829102"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "158117117"
},
{
"name": "JavaScript",
"bytes": "563135"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "2208983"
},
{
"name": "Lex",
"bytes": "179058"
},
{
"name": "Makefile",
"bytes": "3018"
},
{
"name": "NSIS",
"bytes": "49952"
},
{
"name": "Objective-C",
"bytes": "28750"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6607"
},
{
"name": "Python",
"bytes": "23911290"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "63460"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
<?php
class PlaintextHasherTest extends PHPUnit_Framework_TestCase {
public function testBasicHashing()
{
$hasher = new Oss2\Auth\Hashing\PlaintextHasher;
$value = $hasher->make('password');
$this->assertNotSame('otherpassword', $value);
$this->assertTrue($hasher->check('password', $value));
$this->assertFalse($hasher->needsRehash($value));
}
}
| {
"content_hash": "9f034ec8f437060aaa21f4a16d675ee9",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 62,
"avg_line_length": 28.714285714285715,
"alnum_prop": 0.6467661691542289,
"repo_name": "oss2/auth",
"id": "0795177bedf205b6a3c0914ca0cc14880eb56942",
"size": "723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Hashing/PlaintextHasherTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "132766"
}
],
"symlink_target": ""
} |
import Embed from '../blots/embed';
import Quill from '../core/quill';
import Module from '../core/module';
class FormulaBlot extends Embed {
static create(value) {
let node = super.create(value);
if (typeof value === 'string') {
window.katex.render(value, node);
node.setAttribute('data-value', value);
}
node.setAttribute('contenteditable', false);
return node;
}
static value(domNode) {
return domNode.getAttribute('data-value');
}
index() {
return 1;
}
}
FormulaBlot.blotName = 'formula';
FormulaBlot.className = 'ql-formula';
FormulaBlot.tagName = 'SPAN';
class Formula extends Module {
static register() {
Quill.register(FormulaBlot, true);
}
constructor() {
super();
if (window.katex == null) {
throw new Error('Formula module requires KaTeX.');
}
}
}
export { FormulaBlot, Formula as default };
| {
"content_hash": "2fb26eca346a6229fd1735d0fe130755",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 56,
"avg_line_length": 20.318181818181817,
"alnum_prop": 0.645413870246085,
"repo_name": "ATM-Christal/VR-final",
"id": "18a157677dde84172c7aad5bc360b46dfb490b3c",
"size": "894",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "node_modules/quill/modules/formula.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7678"
},
{
"name": "HTML",
"bytes": "4758"
},
{
"name": "JavaScript",
"bytes": "28486"
},
{
"name": "Vue",
"bytes": "1175755"
}
],
"symlink_target": ""
} |
.class public Landroid/widget/TextView$MagnifierView;
.super Landroid/view/View;
.source "TextView.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/widget/TextView;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0xc
name = "MagnifierView"
.end annotation
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Landroid/widget/TextView$MagnifierView$1;,
Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
}
.end annotation
# instance fields
.field private REGION_SIZE_X:I
.field private REGION_SIZE_Y:I
.field private ROUND_RADIUS:I
.field private final UPDATE_MAGNIFIER:I
.field private final VERTICAL_OFFSET:I
.field private final ZOOM_FACTOR:F
.field builder:Landroid/view/SurfaceEffects$Effect$Builder;
.field private defaultOffsetInOneHandedMode:[I
.field private defaultScaleInOneHandedMode:F
.field mBackground:Landroid/graphics/drawable/Drawable;
.field private mContext:Landroid/content/Context;
.field private mIsFirstTouchDown:Z
.field private mMagnifierViewHeight:I
.field private mMagnifierViewWidth:I
.field private mMaxPositionX:F
.field private mMaxPositionY:F
.field private mMaxX:F
.field private mMaxY:F
.field private mMinPositionX:F
.field private mMinPositionY:F
.field private mMinX:F
.field private mMinY:F
.field private mOriginView:Landroid/widget/TextView;
.field private mPopupWindow:Landroid/widget/PopupWindow;
.field private mPositionInWindow:[I
.field private mPositionOnScreen:[I
.field private mPositionX:F
.field private mPositionY:F
.field private mRawX:I
.field private mRawY:I
.field private mStopDraw:Ljava/lang/Runnable;
.field private mTransitionOffset:[F
.field private mTranslatedPoint:Landroid/graphics/PointF;
.field private mTruncated:[F
.field private mUpdateHandler:Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
.field private mVerticalOffset:I
.field private mView:Landroid/view/View;
.field private mWindowOffsetOnScreenX:I
.field private mWindowOffsetOnScreenY:I
# direct methods
.method static synthetic -get0(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->REGION_SIZE_X:I
return v0
.end method
.method static synthetic -get1(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->REGION_SIZE_Y:I
return v0
.end method
.method static synthetic -get10(Landroid/widget/TextView$MagnifierView;)[F
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
return-object v0
.end method
.method static synthetic -get11(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->mVerticalOffset:I
return v0
.end method
.method static synthetic -get12(Landroid/widget/TextView$MagnifierView;)Landroid/view/View;
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mView:Landroid/view/View;
return-object v0
.end method
.method static synthetic -get2(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->ROUND_RADIUS:I
return v0
.end method
.method static synthetic -get3(Landroid/widget/TextView$MagnifierView;)[I
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
return-object v0
.end method
.method static synthetic -get4(Landroid/widget/TextView$MagnifierView;)F
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
return v0
.end method
.method static synthetic -get5(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
return v0
.end method
.method static synthetic -get6(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
return v0
.end method
.method static synthetic -get7(Landroid/widget/TextView$MagnifierView;)I
.locals 1
iget v0, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
return v0
.end method
.method static synthetic -get8(Landroid/widget/TextView$MagnifierView;)[F
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
return-object v0
.end method
.method static synthetic -get9(Landroid/widget/TextView$MagnifierView;)Landroid/graphics/PointF;
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTranslatedPoint:Landroid/graphics/PointF;
return-object v0
.end method
.method constructor <init>(Landroid/content/Context;Landroid/widget/TextView;)V
.locals 4
const/4 v2, 0x0
const/4 v1, 0x0
const/4 v3, 0x2
invoke-direct {p0, p1}, Landroid/view/View;-><init>(Landroid/content/Context;)V
const/16 v0, 0x65
iput v0, p0, Landroid/widget/TextView$MagnifierView;->UPDATE_MAGNIFIER:I
const v0, 0x3f2b851f # 0.67f
iput v0, p0, Landroid/widget/TextView$MagnifierView;->ZOOM_FACTOR:F
new-instance v0, Landroid/graphics/PointF;
invoke-direct {v0, v1, v1}, Landroid/graphics/PointF;-><init>(FF)V
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTranslatedPoint:Landroid/graphics/PointF;
new-array v0, v3, [I
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
new-array v0, v3, [I
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPositionInWindow:[I
const/high16 v0, 0x3f800000 # 1.0f
iput v0, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
iput-object v2, p0, Landroid/widget/TextView$MagnifierView;->mUpdateHandler:Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
const/4 v0, 0x1
iput-boolean v0, p0, Landroid/widget/TextView$MagnifierView;->mIsFirstTouchDown:Z
new-instance v0, Landroid/widget/TextView$MagnifierView$1;
invoke-direct {v0, p0}, Landroid/widget/TextView$MagnifierView$1;-><init>(Landroid/widget/TextView$MagnifierView;)V
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mStopDraw:Ljava/lang/Runnable;
iput-object p2, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iput-object p1, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
iput-object p0, p0, Landroid/widget/TextView$MagnifierView;->mView:Landroid/view/View;
new-instance v0, Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
invoke-direct {v0, p0, v2}, Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;-><init>(Landroid/widget/TextView$MagnifierView;Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;)V
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mUpdateHandler:Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v0
const v1, 0x10503de
invoke-virtual {v0, v1}, Landroid/content/res/Resources;->getDimension(I)F
move-result v0
float-to-int v0, v0
iput v0, p0, Landroid/widget/TextView$MagnifierView;->VERTICAL_OFFSET:I
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v0
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v1}, Landroid/content/Context;->getTheme()Landroid/content/res/Resources$Theme;
move-result-object v1
const v2, 0x1080b4c
invoke-virtual {v0, v2, v1}, Landroid/content/res/Resources;->getDrawable(ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
move-result-object v0
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mBackground:Landroid/graphics/drawable/Drawable;
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v0
const v1, 0x10503df
invoke-virtual {v0, v1}, Landroid/content/res/Resources;->getDimension(I)F
move-result v0
float-to-int v0, v0
iput v0, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewWidth:I
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v0
const v1, 0x10503dd
invoke-virtual {v0, v1}, Landroid/content/res/Resources;->getDimension(I)F
move-result v0
float-to-int v0, v0
iput v0, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->createPopupWindow()Landroid/widget/PopupWindow;
move-result-object v0
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPopupWindow:Landroid/widget/PopupWindow;
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mView:Landroid/view/View;
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mBackground:Landroid/graphics/drawable/Drawable;
invoke-virtual {v0, v1}, Landroid/view/View;->setBackground(Landroid/graphics/drawable/Drawable;)V
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->initEffect()V
new-array v0, v3, [F
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
new-array v0, v3, [F
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
new-array v0, v3, [I
iput-object v0, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->tuneOffset()V
return-void
.end method
.method private createPopupWindow()Landroid/widget/PopupWindow;
.locals 3
const/4 v2, 0x0
new-instance v0, Landroid/widget/PopupWindow;
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-direct {v0, v1}, Landroid/widget/PopupWindow;-><init>(Landroid/content/Context;)V
invoke-virtual {v0, v2}, Landroid/widget/PopupWindow;->setClippingEnabled(Z)V
const/16 v1, 0x3ed
invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setWindowLayoutType(I)V
invoke-virtual {v0, v2}, Landroid/widget/PopupWindow;->setAnimationStyle(I)V
new-instance v1, Landroid/graphics/drawable/ColorDrawable;
invoke-direct {v1, v2}, Landroid/graphics/drawable/ColorDrawable;-><init>(I)V
invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setBackgroundDrawable(Landroid/graphics/drawable/Drawable;)V
iget v1, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewWidth:I
invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setWidth(I)V
iget v1, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setHeight(I)V
invoke-virtual {v0, v2}, Landroid/widget/PopupWindow;->setTouchable(Z)V
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mView:Landroid/view/View;
invoke-virtual {v0, v1}, Landroid/widget/PopupWindow;->setContentView(Landroid/view/View;)V
return-object v0
.end method
.method private dismiss()V
.locals 1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPopupWindow:Landroid/widget/PopupWindow;
invoke-virtual {v0}, Landroid/widget/PopupWindow;->dismiss()V
return-void
.end method
.method private initEffect()V
.locals 4
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v2
invoke-virtual {v2}, Landroid/content/res/Resources;->getDisplayMetrics()Landroid/util/DisplayMetrics;
move-result-object v0
iget v1, v0, Landroid/util/DisplayMetrics;->density:F
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v2
const v3, 0x10e0125
invoke-virtual {v2, v3}, Landroid/content/res/Resources;->getInteger(I)I
move-result v2
int-to-float v2, v2
mul-float/2addr v2, v1
invoke-static {v2}, Ljava/lang/Math;->round(F)I
move-result v2
int-to-float v2, v2
iget v3, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
mul-float/2addr v2, v3
float-to-int v2, v2
iput v2, p0, Landroid/widget/TextView$MagnifierView;->REGION_SIZE_X:I
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v2
const v3, 0x10e0126
invoke-virtual {v2, v3}, Landroid/content/res/Resources;->getInteger(I)I
move-result v2
int-to-float v2, v2
mul-float/2addr v2, v1
invoke-static {v2}, Ljava/lang/Math;->round(F)I
move-result v2
int-to-float v2, v2
iget v3, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
mul-float/2addr v2, v3
float-to-int v2, v2
iput v2, p0, Landroid/widget/TextView$MagnifierView;->REGION_SIZE_Y:I
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;
move-result-object v2
const v3, 0x10e0127
invoke-virtual {v2, v3}, Landroid/content/res/Resources;->getInteger(I)I
move-result v2
int-to-float v2, v2
mul-float/2addr v2, v1
invoke-static {v2}, Ljava/lang/Math;->round(F)I
move-result v2
int-to-float v2, v2
iget v3, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
mul-float/2addr v2, v3
float-to-int v2, v2
iput v2, p0, Landroid/widget/TextView$MagnifierView;->ROUND_RADIUS:I
iget v2, p0, Landroid/widget/TextView$MagnifierView;->VERTICAL_OFFSET:I
iput v2, p0, Landroid/widget/TextView$MagnifierView;->mVerticalOffset:I
invoke-static {}, Landroid/view/SurfaceEffects;->newBuilder()Landroid/view/SurfaceEffects$Effect$Builder;
move-result-object v2
iput-object v2, p0, Landroid/widget/TextView$MagnifierView;->builder:Landroid/view/SurfaceEffects$Effect$Builder;
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->builder:Landroid/view/SurfaceEffects$Effect$Builder;
sget-object v3, Landroid/view/SurfaceEffects$AnimationMode;->STATIC:Landroid/view/SurfaceEffects$AnimationMode;
invoke-virtual {v2, v3}, Landroid/view/SurfaceEffects$Effect$Builder;->setAnimationMode(Landroid/view/SurfaceEffects$AnimationMode;)Landroid/view/SurfaceEffects$Effect$Builder;
move-result-object v2
sget-object v3, Landroid/view/SurfaceEffects$EffectTarget;->BEHIND:Landroid/view/SurfaceEffects$EffectTarget;
invoke-virtual {v2, v3}, Landroid/view/SurfaceEffects$Effect$Builder;->setEffectTarget(Landroid/view/SurfaceEffects$EffectTarget;)Landroid/view/SurfaceEffects$Effect$Builder;
move-result-object v2
sget-object v3, Landroid/view/SurfaceEffects$PixEffectType;->MAGNIFIER:Landroid/view/SurfaceEffects$PixEffectType;
invoke-virtual {v2, v3}, Landroid/view/SurfaceEffects$Effect$Builder;->setPixelEffectType(Landroid/view/SurfaceEffects$PixEffectType;)Landroid/view/SurfaceEffects$Effect$Builder;
return-void
.end method
.method private isOneHandedMode()Z
.locals 4
const/4 v0, 0x1
const/4 v1, 0x0
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v2}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v2
const-string/jumbo v3, "any_screen_running"
invoke-static {v2, v3, v1}, Landroid/provider/Settings$System;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I
move-result v2
if-ne v2, v0, :cond_0
:goto_0
return v0
:cond_0
move v0, v1
goto :goto_0
.end method
.method private tuneOffset()V
.locals 4
const/4 v3, 0x0
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mTranslatedPoint:Landroid/graphics/PointF;
iget-object v2, p0, Landroid/widget/TextView$MagnifierView;->mTranslatedPoint:Landroid/graphics/PointF;
iput v3, v2, Landroid/graphics/PointF;->y:F
iput v3, v1, Landroid/graphics/PointF;->x:F
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v1}, Landroid/widget/TextView;->getViewRootImpl()Landroid/view/ViewRootImpl;
move-result-object v0
if-eqz v0, :cond_0
invoke-virtual {v0}, Landroid/view/ViewRootImpl;->getTranslatedPoint()Landroid/graphics/PointF;
move-result-object v1
iput-object v1, p0, Landroid/widget/TextView$MagnifierView;->mTranslatedPoint:Landroid/graphics/PointF;
:cond_0
return-void
.end method
.method private updatePosition()V
.locals 5
const/4 v3, -0x1
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPopupWindow:Landroid/widget/PopupWindow;
invoke-virtual {v0}, Landroid/widget/PopupWindow;->isShowing()Z
move-result v0
if-eqz v0, :cond_0
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPopupWindow:Landroid/widget/PopupWindow;
iget v1, p0, Landroid/widget/TextView$MagnifierView;->mPositionX:F
float-to-int v1, v1
iget v2, p0, Landroid/widget/TextView$MagnifierView;->mPositionY:F
float-to-int v2, v2
invoke-virtual {v0, v1, v2, v3, v3}, Landroid/widget/PopupWindow;->update(IIII)V
:goto_0
return-void
:cond_0
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mPopupWindow:Landroid/widget/PopupWindow;
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v1}, Landroid/widget/TextView;->getRootView()Landroid/view/View;
move-result-object v1
iget v2, p0, Landroid/widget/TextView$MagnifierView;->mPositionX:F
float-to-int v2, v2
iget v3, p0, Landroid/widget/TextView$MagnifierView;->mPositionY:F
float-to-int v3, v3
const/4 v4, 0x0
invoke-virtual {v0, v1, v4, v2, v3}, Landroid/widget/PopupWindow;->showAtLocation(Landroid/view/View;III)V
goto :goto_0
.end method
# virtual methods
.method public magnifyScreen(FF)V
.locals 13
const/high16 v12, -0x40800000 # -1.0f
const/4 v11, 0x0
const/4 v10, 0x1
const/4 v9, 0x0
invoke-static {}, Landroid/widget/TextView;->-get15()Z
move-result v6
if-nez v6, :cond_0
return-void
:cond_0
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v6}, Landroid/widget/TextView;->getRootView()Landroid/view/View;
move-result-object v1
invoke-virtual {v1}, Landroid/view/View;->getApplicationWindowToken()Landroid/os/IBinder;
move-result-object v6
invoke-virtual {v1}, Landroid/view/View;->getWindowToken()Landroid/os/IBinder;
move-result-object v7
if-eq v6, v7, :cond_1
return-void
:cond_1
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mStopDraw:Ljava/lang/Runnable;
invoke-virtual {v6, v7}, Landroid/widget/TextView;->removeCallbacks(Ljava/lang/Runnable;)Z
float-to-int v6, p1
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
float-to-int v6, p2
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
iget-boolean v6, p0, Landroid/widget/TextView$MagnifierView;->mIsFirstTouchDown:Z
if-eqz v6, :cond_3
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->isOneHandedMode()Z
move-result v6
if-eqz v6, :cond_8
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mContext:Landroid/content/Context;
invoke-virtual {v6}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v6
const-string/jumbo v7, "reduce_screen_running_info"
invoke-static {v6, v7}, Landroid/provider/Settings$System;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;
move-result-object v2
:try_start_0
const-string/jumbo v6, ";"
invoke-virtual {v2, v6}, Ljava/lang/String;->split(Ljava/lang/String;)[Ljava/lang/String;
move-result-object v5
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
const/4 v7, 0x0
aget-object v7, v5, v7
invoke-static {v7}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I
move-result v7
const/4 v8, 0x0
aput v7, v6, v8
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
const/4 v7, 0x1
aget-object v7, v5, v7
invoke-static {v7}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I
move-result v7
const/4 v8, 0x1
aput v7, v6, v8
const/4 v6, 0x2
aget-object v6, v5, v6
invoke-static {v6}, Ljava/lang/Float;->parseFloat(Ljava/lang/String;)F
move-result v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
:try_end_0
.catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0
:goto_0
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->initEffect()V
iput-boolean v9, p0, Landroid/widget/TextView$MagnifierView;->mIsFirstTouchDown:Z
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
invoke-virtual {v6, v7}, Landroid/widget/TextView;->getLocationOnScreen([I)V
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionInWindow:[I
invoke-virtual {v6, v7}, Landroid/widget/TextView;->getLocationInWindow([I)V
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v9
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionInWindow:[I
aget v7, v7, v9
sub-int/2addr v6, v7
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenX:I
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v10
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionInWindow:[I
aget v7, v7, v10
sub-int/2addr v6, v7
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenY:I
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v9
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenX:I
sub-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingStart()I
move-result v7
add-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMinPositionX:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v10
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenY:I
sub-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingTop()I
move-result v7
add-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mVerticalOffset:I
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
sub-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMinPositionY:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v9
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenX:I
sub-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getMeasuredWidth()I
move-result v7
add-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingEnd()I
move-result v7
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewWidth:I
sub-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionX:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v10
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenY:I
sub-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getMeasuredHeight()I
move-result v7
add-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingBottom()I
move-result v7
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mVerticalOffset:I
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
sub-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionY:F
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionY:F
cmpg-float v6, v6, v11
if-gez v6, :cond_2
iput v11, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionY:F
:cond_2
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v9
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingStart()I
move-result v7
add-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMinX:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v10
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingTop()I
move-result v7
add-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMinY:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v9
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getMeasuredWidth()I
move-result v7
add-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingEnd()I
move-result v7
sub-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMaxX:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionOnScreen:[I
aget v6, v6, v10
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getMeasuredHeight()I
move-result v7
add-int/2addr v6, v7
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
invoke-virtual {v7}, Landroid/widget/TextView;->getCompoundPaddingBottom()I
move-result v7
sub-int/2addr v6, v7
int-to-float v6, v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mMaxY:F
:cond_3
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->tuneOffset()V
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenX:I
sub-int/2addr v6, v7
int-to-float v6, v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewWidth:I
int-to-float v7, v7
const/high16 v8, 0x40000000 # 2.0f
div-float/2addr v7, v8
sub-float v3, v6, v7
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mWindowOffsetOnScreenY:I
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mVerticalOffset:I
sub-int/2addr v6, v7
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMagnifierViewHeight:I
sub-int/2addr v6, v7
int-to-float v4, v6
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mMinPositionX:F
invoke-static {v3, v6}, Ljava/lang/Math;->max(FF)F
move-result v6
invoke-static {v6, v11}, Ljava/lang/Math;->max(FF)F
move-result v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionX:F
invoke-static {v6, v7}, Ljava/lang/Math;->min(FF)F
move-result v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionX:F
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mMinPositionY:F
invoke-static {v4, v6}, Ljava/lang/Math;->max(FF)F
move-result v6
invoke-static {v6, v11}, Ljava/lang/Math;->max(FF)F
move-result v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxPositionY:F
invoke-static {v6, v7}, Ljava/lang/Math;->min(FF)F
move-result v6
iput v6, p0, Landroid/widget/TextView$MagnifierView;->mPositionY:F
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionX:F
sub-float v7, v3, v7
aput v7, v6, v9
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mPositionY:F
sub-float/2addr v7, v4
aput v7, v6, v10
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
aget v7, v7, v9
mul-float/2addr v7, v12
aput v7, v6, v9
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
aget v7, v7, v10
mul-float/2addr v7, v12
aput v7, v6, v10
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
aget v6, v6, v9
cmpl-float v6, v6, v11
if-eqz v6, :cond_5
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
aput v11, v6, v9
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
int-to-float v6, v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMinX:F
cmpg-float v6, v6, v7
if-gez v6, :cond_4
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMinX:F
iget v8, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
int-to-float v8, v8
sub-float/2addr v7, v8
aput v7, v6, v9
:cond_4
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
int-to-float v6, v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxX:F
cmpl-float v6, v6, v7
if-lez v6, :cond_5
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxX:F
iget v8, p0, Landroid/widget/TextView$MagnifierView;->mRawX:I
int-to-float v8, v8
sub-float/2addr v7, v8
aput v7, v6, v9
:cond_5
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTruncated:[F
aget v6, v6, v10
cmpl-float v6, v6, v11
if-eqz v6, :cond_7
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
aput v11, v6, v10
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
int-to-float v6, v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMinY:F
cmpg-float v6, v6, v7
if-gez v6, :cond_6
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMinY:F
iget v8, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
int-to-float v8, v8
sub-float/2addr v7, v8
mul-float/2addr v7, v12
aput v7, v6, v10
:cond_6
iget v6, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
int-to-float v6, v6
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxY:F
cmpl-float v6, v6, v7
if-lez v6, :cond_7
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mTransitionOffset:[F
iget v7, p0, Landroid/widget/TextView$MagnifierView;->mMaxY:F
iget v8, p0, Landroid/widget/TextView$MagnifierView;->mRawY:I
int-to-float v8, v8
sub-float/2addr v7, v8
mul-float/2addr v7, v12
aput v7, v6, v10
:cond_7
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mStopDraw:Ljava/lang/Runnable;
invoke-virtual {v6, v7}, Landroid/widget/TextView;->removeCallbacks(Ljava/lang/Runnable;)Z
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->updatePosition()V
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mUpdateHandler:Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
const/16 v7, 0x65
invoke-virtual {v6, v7}, Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;->sendEmptyMessage(I)Z
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v7, p0, Landroid/widget/TextView$MagnifierView;->mStopDraw:Ljava/lang/Runnable;
const-wide/16 v8, 0xbb8
invoke-virtual {v6, v7, v8, v9}, Landroid/widget/TextView;->postDelayed(Ljava/lang/Runnable;J)Z
return-void
:catch_0
move-exception v0
const-string/jumbo v6, "TextView"
const-string/jumbo v7, "MagnifierView, Exception occured during getting the settings value at the one-handed mode."
invoke-static {v6, v7}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I
return-void
:cond_8
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
aput v9, v6, v9
iget-object v6, p0, Landroid/widget/TextView$MagnifierView;->defaultOffsetInOneHandedMode:[I
aput v9, v6, v10
const/high16 v6, 0x3f800000 # 1.0f
iput v6, p0, Landroid/widget/TextView$MagnifierView;->defaultScaleInOneHandedMode:F
goto/16 :goto_0
.end method
.method public stopMagnifier()V
.locals 2
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mUpdateHandler:Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;
const/16 v1, 0x65
invoke-virtual {v0, v1}, Landroid/widget/TextView$MagnifierView$UpdateMagnifierHandler;->removeMessages(I)V
invoke-direct {p0}, Landroid/widget/TextView$MagnifierView;->dismiss()V
const/4 v0, 0x1
iput-boolean v0, p0, Landroid/widget/TextView$MagnifierView;->mIsFirstTouchDown:Z
iget-object v0, p0, Landroid/widget/TextView$MagnifierView;->mOriginView:Landroid/widget/TextView;
iget-object v1, p0, Landroid/widget/TextView$MagnifierView;->mStopDraw:Ljava/lang/Runnable;
invoke-virtual {v0, v1}, Landroid/widget/TextView;->removeCallbacks(Ljava/lang/Runnable;)Z
return-void
.end method
| {
"content_hash": "22e0876589042e8897598bba9fb5ca8c",
"timestamp": "",
"source": "github",
"line_count": 1342,
"max_line_length": 206,
"avg_line_length": 27.614008941877795,
"alnum_prop": 0.7322035727778078,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "936b9c347ad6b109b9e4270ee8342005a8c4b247",
"size": "37058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework.jar.out/smali_classes2/android/widget/TextView$MagnifierView.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
import copy
from . wrapper import Wrapper
from .. util import color_list
class Feedback(Wrapper):
def __init__(self, *args, animation,
master=1, inputs=None, outputs=None, **kwds):
super().__init__(*args, animation=animation, **kwds)
self.master = master
inputs = inputs or [0]
outputs = outputs or []
in_sources = [copy.deepcopy(self.color_list) for i in inputs[1:]]
in_sources.insert(self.animation.color_list)
out_sources = [copy.deepcopy(self.color_list) for i in outputs]
self.inputs = color_list.Mixer(self.color_list, in_sources, inputs)
self.outputs = color_list.Mixer(self.color_list, out_sources, outputs)
self.clear = self.inputs.clear
self.math = self.inputs.math
def step(self, amt=1):
super().step(amt=amt)
self.clear()
self.inputs.mix(self.master)
self.outputs.mix(self.master)
def rotate(sources, begin):
if len(sources) > 1 + begin:
sources.insert(begin, sources.pop())
ins, outs = self.inputs.sources, self.outputs.sources
rotate(ins, 1)
rotate(outs, 0)
if len(ins) > 1:
self.math.copy(ins[1], ins[0])
if len(outs) > 0:
self.math.copy(outs[0], self.color_list)
| {
"content_hash": "ca2e87a46660a952a661d86d9aa1b7b1",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 78,
"avg_line_length": 29.08695652173913,
"alnum_prop": 0.5866965620328849,
"repo_name": "rec/BiblioPixel",
"id": "d78a71ef5fd1d9f16be29a9d9868726b46cda8f5",
"size": "1338",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "bibliopixel/animation/feedback.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20651"
},
{
"name": "HTML",
"bytes": "3310"
},
{
"name": "JavaScript",
"bytes": "5140"
},
{
"name": "Python",
"bytes": "673520"
},
{
"name": "Shell",
"bytes": "2973"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.media.remote;
import android.app.PendingIntent.CanceledException;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.media.remote.NotificationTransportControl.ListenerService;
import org.chromium.chrome.browser.media.remote.RemoteVideoInfo.PlayerState;
import org.chromium.chrome.test.util.ActivityUtils;
import java.util.concurrent.TimeoutException;
/**
* Tests of the notification.
*/
public class CastNotificationTest extends CastTestBase {
private static final long PAUSE_TEST_TIME_MS = 1000;
/**
* Test the pause button on the notification.
*/
@Feature({"VideoFling"})
@LargeTest
public void testNotificationPause() throws InterruptedException, TimeoutException {
castDefaultVideoFromPage(DEFAULT_VIDEO_PAGE);
// Get the notification
NotificationTransportControl notificationTransportControl = waitForCastNotification();
assertNotNull("No notificationTransportControl", notificationTransportControl);
// We can't actually click the notification's buttons, since they are owned by a different
// process and hence is not accessible through instrumentation, so send the stop event
// instead.
NotificationTransportControl.ListenerService service =
waitForCastNotificationService(notificationTransportControl);
assertNotNull("No notification service", service);
try {
service.getPendingIntent(ListenerService.ACTION_ID_PAUSE).send();
} catch (CanceledException e) {
fail();
}
assertTrue("Not paused", waitForState(PlayerState.PAUSED));
// The new position is sent in a separate message, so we have to wait a bit before
// fetching it.
Thread.sleep(STABILIZE_TIME_MS);
long position = getRemotePositionMs();
// Position should not change while paused
Thread.sleep(PAUSE_TEST_TIME_MS);
assertEquals("Pause didn't stop playback", position, getRemotePositionMs());
try {
service.getPendingIntent(ListenerService.ACTION_ID_PLAY).send();
} catch (CanceledException e) {
fail();
}
assertTrue("Not playing", waitForState(PlayerState.PLAYING));
// Should now be running again.
Thread.sleep(PAUSE_TEST_TIME_MS);
assertTrue("Run didn't restart playback", position < getRemotePositionMs());
}
/**
* Test select (pressing the body) on the notification.
*/
@Feature({"VideoFling"})
@LargeTest
public void testNotificationSelect() throws InterruptedException, TimeoutException {
castDefaultVideoFromPage(DEFAULT_VIDEO_PAGE);
// Get the notification
NotificationTransportControl notificationTransportControl = waitForCastNotification();
assertNotNull("No notificationTransportControl", notificationTransportControl);
// We can't actually click the notification's buttons, since they are owned by a different
// process and hence is not accessible through instrumentation, so send the select event
// instead.
final NotificationTransportControl.ListenerService service =
waitForCastNotificationService(notificationTransportControl);
assertNotNull("No notification service", service);
ExpandedControllerActivity fullscreenControls = ActivityUtils.waitForActivityWithTimeout(
getInstrumentation(),
ExpandedControllerActivity.class, new Runnable() {
@Override
public void run() {
try {
service.getPendingIntent(ListenerService.ACTION_ID_SELECT).send();
} catch (CanceledException e) {
fail();
}
}
}, MAX_VIEW_TIME_MS);
assertNotNull("No expanded controller activity", fullscreenControls);
View rootView = fullscreenControls.findViewById(android.R.id.content);
assertNotNull("No root view for fullscreen controls", rootView);
assertEquals("Fullscreen controls not shown", View.VISIBLE, rootView.getVisibility());
}
}
| {
"content_hash": "1a9ed809c26e0f53a840f9d5a02ad06b",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 98,
"avg_line_length": 43.61538461538461,
"alnum_prop": 0.6807760141093474,
"repo_name": "js0701/chromium-crosswalk",
"id": "c4284fe1350230c4cebf367041b5eeadccb91714",
"size": "4536",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "chrome/android/javatests/src/org/chromium/chrome/browser/media/remote/CastNotificationTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
@implementation Enrolls
@end
| {
"content_hash": "4400201a9959e0a92366cf4f90822585",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 23,
"avg_line_length": 10,
"alnum_prop": 0.8,
"repo_name": "xueqiulou/Jianguo",
"id": "fc1d8101b06a4f502abb4cb1868f8b770e78ea42",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JianGuo/JianGuo/Mine/Model/Enrolls.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37377"
},
{
"name": "C++",
"bytes": "54687"
},
{
"name": "HTML",
"bytes": "4555"
},
{
"name": "Objective-C",
"bytes": "6142119"
},
{
"name": "Objective-C++",
"bytes": "124423"
},
{
"name": "Ruby",
"bytes": "882"
},
{
"name": "Shell",
"bytes": "9276"
}
],
"symlink_target": ""
} |
tinyjson
========
Tiny (as in minimal) implementation of a JSON response parser. The parser
itself is only dependent on:
* `<string.h> - memcpy`
* `<stdlib.h> - atof`
Also included is a C++ wrapper around the low level `tinyjson_parse` function
Contact
-------
[@MatthewEndsley](https://twitter.com/#!/MatthewEndsley)
<https://github.com/mendsley/tinyjson>
License
-------
Copyright 2011 Matthew Endsley
This project is governed by the BSD 2-clause license. For details see the file
titled LICENSE in the project root folder.
| {
"content_hash": "99ff1712d14567b9cd686cf5b3469437",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 78,
"avg_line_length": 26.6,
"alnum_prop": 0.7274436090225563,
"repo_name": "mendsley/tinyjson",
"id": "ca419ccabbbc9fed82e425e4dc1586b466cfff8a",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "6572"
},
{
"name": "C++",
"bytes": "6659"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e76bbca0459a4be2e94cb55d4a4ca552",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "5c59a5b4179f1ee4bbcd0fe7c9595bf5f1f86169",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Polygonaceae/Polygonum/Polygonum fallax/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
apt-get update
apt-get install -y nodejs npm
ln -s /usr/bin/nodejs /usr/bin/node
apt-get install -y redis-server
echo "deb http://download.rethinkdb.com/apt trusty main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
wget -qO- http://download.rethinkdb.com/apt/pubkey.gpg | sudo apt-key add -
sudo apt-get update
sudo apt-get install -y rethinkdb
sudo cp /etc/rethinkdb/default.conf.sample /etc/rethinkdb/instances.d/instance1.conf
sudo /etc/init.d/rethinkdb restart
cd /vagrant
npm install | {
"content_hash": "dd39f28bd9c30cf73ad67c588b5be41c",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 106,
"avg_line_length": 33.06666666666667,
"alnum_prop": 0.7701612903225806,
"repo_name": "caco0516/node-oauth20-provider-libre",
"id": "9c864d509337b45c4cdd8b54bfdeea7fa87cfca2",
"size": "507",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "bootstrap.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "467"
},
{
"name": "JavaScript",
"bytes": "114387"
},
{
"name": "Shell",
"bytes": "507"
}
],
"symlink_target": ""
} |
<?php
namespace TralangBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity(repositoryClass="TralangBundle\Repository\CategoryRepository")
*/
class Category
{
public function __construct()
{
$this->categories = new ArrayCollection();
}
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="category", type="string", length=255, unique=true)
* @ORM\OneToMany(targetEntity="TralangBundle\Entity\Words", mappedBy="category")
*/
private $categories;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* @return Category
*/
public function setCategories($categories)
{
$this->categories = $categories;
return $this;
}
/**
* Get category
*
* @return string
*/
public function getCategories()
{
return $this->categories;
}
}
| {
"content_hash": "9f49e071c29a4e008f93f2e0dd264f21",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 85,
"avg_line_length": 17.055555555555557,
"alnum_prop": 0.5594462540716613,
"repo_name": "romamolodyko/Tralang",
"id": "4ec364fbf0574cb025d8a2e795f5d4e9694aed3b",
"size": "1228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TralangBundle/Entity/Category.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "CSS",
"bytes": "421732"
},
{
"name": "HTML",
"bytes": "18763"
},
{
"name": "JavaScript",
"bytes": "427787"
},
{
"name": "PHP",
"bytes": "73293"
}
],
"symlink_target": ""
} |
require( "class" )
local ffi = require( "ffi" )
local cef = require( "cef" )
local GL = require( "opengl" )
class( "framework.html.browser" )
local browser = framework.html.browser
local function get_view_rect( self )
local func = function( handler, browser, rect )
rect[0] = ffi.new( "cef_rect_t", 0, 0, self.width, self.height )
return 1
end
jit.off( func, true )
return func
end
local function on_paint( self )
local func = function(
handler,
browser,
type,
dirtyRectsCount,
dirtyRects,
buffer,
width,
height
)
assert( cef.cef_currently_on( ffi.C.TID_UI ) )
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
0,
GL.GL_RGBA,
width,
height,
0,
GL.GL_BGRA,
GL.GL_UNSIGNED_INT_8_8_8_8_REV,
buffer
)
end
jit.off( func, true )
return func
end
function browser:initializeRenderHandler()
local handler = ffi.new( "cef_render_handler_t" )
handler.base.size = ffi.sizeof( handler )
handler.get_view_rect = get_view_rect( self )
handler.on_paint = on_paint( self )
self.renderHandler = handler
end
| {
"content_hash": "bde0166b2b29e417ea21b5c008a7e0f3",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 66,
"avg_line_length": 20.072727272727274,
"alnum_prop": 0.6711956521739131,
"repo_name": "Planimeter/lgameframework",
"id": "aa62954083eaff1fcc25b53033128ef3c1352d99",
"size": "1282",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lua/framework/html/rendering.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "68"
},
{
"name": "C",
"bytes": "637558"
},
{
"name": "GLSL",
"bytes": "16799"
},
{
"name": "HTML",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "463358"
},
{
"name": "Shell",
"bytes": "113"
}
],
"symlink_target": ""
} |
survey 'GL',
:full_title => 'Greenland',
:default_mandatory => 'false',
:status => 'alpha',
:description => '<p><strong>This has been generated based on a default and needs to be localised for Greenland. Please help us! Contact <a href="mailto:certificate@theodi.org">certificate@theodi.org</a></strong></p><p>This self-assessment questionnaire generates an open data certificate and badge you can publish to tell people all about this open data. We also use your answers to learn how organisations publish open data.</p><p>When you answer these questions it demonstrates your efforts to comply with relevant legislation. You should also check which other laws and policies apply to your sector.</p><p><strong>You do not need to answer all the questions to get a certificate.</strong> Just answer those you can.</p>' do
translations :en => :default
section_general 'General Information',
:description => '',
:display_header => false do
q_dataTitle 'What\'s this data called?',
:discussion_topic => :dataTitle,
:help_text => 'People see the name of your open data in a list of similar ones so make this as unambiguous and descriptive as you can in this tiny box so they quickly identify what\'s unique about it.',
:required => :required
a_1 'Data Title',
:string,
:placeholder => 'Data Title',
:required => :required
q_documentationUrl 'Where is it described?',
:discussion_topic => :documentationUrl,
:display_on_certificate => true,
:text_as_statement => 'This data is described at',
:help_text => 'Give a URL for people to read about the contents of your open data and find more detail. It can be a page within a bigger catalog like data.gov.uk.'
a_1 'Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Documentation URL',
:requirement => ['pilot_1', 'basic_1']
label_pilot_1 'You should have a <strong>web page that offers documentation</strong> about the open data you publish so that people can understand its context, content and utility.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_1'
dependency :rule => 'A and B'
condition_A :q_releaseType, '!=', :a_collection
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
label_basic_1 'You must have a <strong>web page that gives documentation</strong> and access to the open data you publish so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_1'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_collection
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_publisher 'Who publishes this data?',
:discussion_topic => :publisher,
:display_on_certificate => true,
:text_as_statement => 'This data is published by',
:help_text => 'Give the name of the organisation who publishes this data. Itโs probably who you work for unless youโre doing this on behalf of someone else.',
:required => :required
a_1 'Data Publisher',
:string,
:placeholder => 'Data Publisher',
:required => :required
q_publisherUrl 'What website is the data published on?',
:discussion_topic => :publisherUrl,
:display_on_certificate => true,
:text_as_statement => 'The data is published on',
:help_text => 'Give a URL to a website, this helps us to group data from the same organisation even if people give different names.'
a_1 'Publisher URL',
:string,
:input_type => :url,
:placeholder => 'Publisher URL'
q_releaseType 'What kind of release is this?',
:discussion_topic => :releaseType,
:pick => :one,
:required => :required
a_oneoff 'a one-off release of a single dataset',
:help_text => 'This is a single file and you donโt currently plan to publish similar files in the future.'
a_collection 'a one-off release of a set of related datasets',
:help_text => 'This is a collection of related files about the same data and you donโt currently plan to publish similar collections in the future.'
a_series 'ongoing release of a series of related datasets',
:help_text => 'This is a sequence of datasets with planned periodic updates in the future.'
a_service 'a service or API for accessing open data',
:help_text => 'This is a live web service that exposes your data to programmers through an interface they can query.'
end
section_legal 'Legal Information',
:description => 'Rights, licensing and privacy' do
label_group_2 'Rights',
:help_text => 'your right to share this data with people',
:customer_renderer => '/partials/fieldset'
q_publisherRights 'Do you have the rights to publish this data as open data?',
:discussion_topic => :gl_publisherRights,
:help_text => 'If your organisation didn\'t originally create or gather this data then you might not have the right to publish it. If youโre not sure, check with the data owner because you will need their permission to publish it.',
:requirement => ['basic_2'],
:pick => :one,
:required => :required
a_yes 'yes, you have the rights to publish this data as open data',
:requirement => ['standard_1']
a_no 'no, you don\'t have the rights to publish this data as open data'
a_unsure 'you\'re not sure if you have the rights to publish this data as open data'
a_complicated 'the rights in this data are complicated or unclear'
label_standard_1 'You should have a <strong>clear legal right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_1'
dependency :rule => 'A'
condition_A :q_publisherRights, '!=', :a_yes
label_basic_2 'You must have the <strong>right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_2'
dependency :rule => 'A'
condition_A :q_publisherRights, '==', :a_no
q_rightsRiskAssessment 'Where do you detail the risks people might encounter if they use this data?',
:discussion_topic => :gl_rightsRiskAssessment,
:display_on_certificate => true,
:text_as_statement => 'Risks in using this data are described at',
:help_text => 'It can be risky for people to use data without a clear legal right to do so. For example, the data might be taken down in response to a legal challenge. Give a URL for a page that describes the risk of using this data.'
dependency :rule => 'A'
condition_A :q_publisherRights, '==', :a_complicated
a_1 'Risk Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Risk Documentation URL',
:requirement => ['pilot_2']
label_pilot_2 'You should document <strong>risks associated with using this data</strong>, so people can work out how they want to use it.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_2'
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_complicated
condition_B :q_rightsRiskAssessment, '==', {:string_value => '', :answer_reference => '1'}
q_publisherOrigin 'Was <em>all</em> this data originally created or gathered by you?',
:discussion_topic => :gl_publisherOrigin,
:display_on_certificate => true,
:text_as_statement => 'This data was',
:help_text => 'If any part of this data was sourced outside your organisation by other individuals or organisations then you need to give extra information about your right to publish it.',
:pick => :one,
:required => :required
dependency :rule => '(A or B)'
condition_A :q_publisherRights, '==', :a_yes
condition_B :q_publisherRights, '==', :a_unsure
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'originally created or generated by its curator'
q_thirdPartyOrigin 'Was some of this data extracted or calculated from other data?',
:discussion_topic => :gl_thirdPartyOrigin,
:help_text => 'An extract or smaller part of someone else\'s data still means your rights to use it might be affected. There might also be legal issues if you analysed their data to produce new results from it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
a_false 'no'
a_true 'yes',
:requirement => ['basic_3']
label_basic_3 'You indicated that this data wasn\'t originally created or gathered by you, and wasn\'t crowdsourced, so it must have been extracted or calculated from other data sources.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_3'
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_false
condition_D :q_thirdPartyOrigin, '!=', :a_true
q_thirdPartyOpen 'Are <em>all</em> sources of this data already published as open data?',
:discussion_topic => :gl_thirdPartyOpen,
:display_on_certificate => true,
:text_as_statement => 'This data is created from',
:help_text => 'You\'re allowed to republish someone else\'s data if it\'s already under an open data licence or if their rights have expired or been waived. If any part of this data is not like this then you\'ll need legal advice before you can publish it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'open data sources',
:requirement => ['basic_4']
label_basic_4 'You should get <strong>legal advice to make sure you have the right to publish this data</strong>.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_4'
dependency :rule => 'A and B and C and D and E'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_true
condition_D :q_thirdPartyOpen, '==', :a_false
condition_E :q_thirdPartyOpen, '==', :a_false
q_crowdsourced 'Was some of this data crowdsourced?',
:discussion_topic => :gl_crowdsourced,
:display_on_certificate => true,
:text_as_statement => 'Some of this data is',
:help_text => 'If the data includes information contributed by people outside your organisation, you need their permission to publish their contributions as open data.',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'crowdsourced',
:requirement => ['basic_5']
label_basic_5 'You indicated that the data wasn\'t originally created or gathered by you, and wasn\'t extracted or calculated from other data, so it must have been crowdsourced.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_5'
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_thirdPartyOrigin, '==', :a_false
condition_D :q_crowdsourced, '!=', :a_true
q_crowdsourcedContent 'Did contributors to this data use their judgement?',
:discussion_topic => :gl_crowdsourcedContent,
:help_text => 'If people used their creativity or judgement to contribute data then they have copyright over their work. For example, writing a description or deciding whether or not to include some data in a dataset would require judgement. So contributors must transfer or waive their rights, or license the data to you before you can publish it.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
a_false 'no'
a_true 'yes'
q_claUrl 'Where is the Contributor Licence Agreement (CLA)?',
:discussion_topic => :gl_claUrl,
:display_on_certificate => true,
:text_as_statement => 'The Contributor Licence Agreement is at',
:help_text => 'Give a link to an agreement that shows contributors allow you to reuse their data. A CLA will either transfer contributor\'s rights to you, waive their rights, or license the data to you so you can publish it.',
:help_text_more_url => 'http://en.wikipedia.org/wiki/Contributor_License_Agreement',
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
a_1 'Contributor Licence Agreement URL',
:string,
:input_type => :url,
:placeholder => 'Contributor Licence Agreement URL',
:required => :required
q_cldsRecorded 'Have all contributors agreed to the Contributor Licence Agreement (CLA)?',
:discussion_topic => :gl_cldsRecorded,
:help_text => 'Check all contributors agree to a CLA before you reuse or republish their contributions. You should keep a record of who gave contributions and whether or not they agree to the CLA.',
:pick => :one,
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
a_false 'no'
a_true 'yes',
:requirement => ['basic_6']
label_basic_6 'You must get <strong>contributors to agree to a Contributor Licence Agreement</strong> (CLA) that gives you the right to publish their work as open data.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_6'
dependency :rule => 'A and B and C and D and E'
condition_A :q_publisherRights, '==', :a_unsure
condition_B :q_publisherOrigin, '==', :a_false
condition_C :q_crowdsourced, '==', :a_true
condition_D :q_crowdsourcedContent, '==', :a_true
condition_E :q_cldsRecorded, '==', :a_false
q_sourceDocumentationUrl 'Where do you describe sources of this data?',
:discussion_topic => :gl_sourceDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The sources of this data are described at',
:help_text => 'Give a URL that documents where the data was sourced from (its provenance) and the rights under which you publish the data. This helps people understand where the data comes from.'
dependency :rule => 'A'
condition_A :q_publisherOrigin, '==', :a_false
a_1 'Data Sources Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Data Sources Documentation URL',
:requirement => ['pilot_3']
label_pilot_3 'You should document <strong>where the data came from and the rights under which you publish it</strong>, so people are assured they can use parts which came from third parties.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_3'
dependency :rule => 'A and B'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_sourceDocumentationMetadata 'Is documentation about the sources of this data also in machine-readable format?',
:discussion_topic => :gl_sourceDocumentationMetadata,
:display_on_certificate => true,
:text_as_statement => 'The curator has published',
:help_text => 'Information about data sources should be human-readable so people can understand it, as well as in a metadata format that computers can process. When everyone does this it helps other people find out how the same open data is being used and justify its ongoing publication.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable data about the sources of this data',
:requirement => ['standard_2']
label_standard_2 'You should <strong>include machine-readable data about the sources of this data</strong>.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_2'
dependency :rule => 'A and B and C'
condition_A :q_publisherOrigin, '==', :a_false
condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_sourceDocumentationMetadata, '==', :a_false
label_group_3 'Licensing',
:help_text => 'how you give people permission to use this data',
:customer_renderer => '/partials/fieldset'
q_copyrightURL 'Where have you published the rights statement for this dataset?',
:discussion_topic => :gl_copyrightURL,
:display_on_certificate => true,
:text_as_statement => 'The rights statement is at',
:help_text => 'Give the URL to a page that describes the right to re-use this dataset. This should include a reference to its license, attribution requirements, and a statement about relevant copyright. A rights statement helps people understand what they can and can\'t do with the data.'
a_1 'Rights Statement URL',
:string,
:input_type => :url,
:placeholder => 'Rights Statement URL',
:requirement => ['pilot_4']
label_pilot_4 'You should <strong>publish a rights statement</strong> that details copyright, licensing and how people should give attribution to the data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_4'
dependency :rule => 'A'
condition_A :q_copyrightURL, '==', {:string_value => '', :answer_reference => '1'}
q_dataLicence 'Under which licence can people reuse this data?',
:discussion_topic => :gl_dataLicence,
:display_on_certificate => true,
:text_as_statement => 'This data is available under',
:help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it. Creative content includes the organisation and selection of items within data, but does not include facts. So people need a waiver or a licence which proves that they can use the data and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the data, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
a_cc_by 'Creative Commons Attribution',
:text_as_statement => 'Creative Commons Attribution'
a_cc_by_sa 'Creative Commons Attribution Share-Alike',
:text_as_statement => 'Creative Commons Attribution Share-Alike'
a_cc_zero 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_odc_by 'Open Data Commons Attribution License',
:text_as_statement => 'Open Data Commons Attribution License'
a_odc_odbl 'Open Data Commons Open Database License (ODbL)',
:text_as_statement => 'Open Data Commons Open Database License (ODbL)'
a_odc_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)',
:text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)'
a_na 'Not applicable',
:text_as_statement => ''
a_other 'Other...',
:text_as_statement => ''
q_dataNotApplicable 'Why doesn\'t a licence apply to this data?',
:discussion_topic => :gl_dataNotApplicable,
:display_on_certificate => true,
:text_as_statement => 'This data is not licensed because',
:pick => :one,
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_na
a_norights 'there is no copyright in this data',
:text_as_statement => 'there is no copyright in it',
:help_text => 'Copyright only applies to data if you spent intellectual effort creating what\'s in it, for example, by writing text that\'s within the data, or deciding whether particular data is included. There\'s no copyright if the data only contains facts where no judgements were made about whether to include them or not.'
a_expired 'copyright has expired',
:text_as_statement => 'copyright has expired',
:help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.'
a_waived 'copyright has been waived',
:text_as_statement => '',
:help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.'
q_dataWaiver 'Which waiver do you use to waive copyright in the data?',
:discussion_topic => :gl_dataWaiver,
:display_on_certificate => true,
:text_as_statement => 'Rights in the data have been waived with',
:help_text => 'You need a statement to show people copyright has been waived, so they understand that they can do whatever they like with this data. Standard waivers already exist like PDDL and CCZero but you can write your own with legal advice.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A and B'
condition_A :q_dataLicence, '==', :a_na
condition_B :q_dataNotApplicable, '==', :a_waived
a_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)',
:text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)'
a_cc0 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_other 'Other...',
:text_as_statement => ''
q_dataOtherWaiver 'Where is the waiver for the copyright in the data?',
:discussion_topic => :gl_dataOtherWaiver,
:display_on_certificate => true,
:text_as_statement => 'Rights in the data have been waived with',
:help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive copyright in the data.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_dataLicence, '==', :a_na
condition_B :q_dataNotApplicable, '==', :a_waived
condition_C :q_dataWaiver, '==', :a_other
a_1 'Waiver URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Waiver URL'
q_otherDataLicenceName 'What is the name of the licence?',
:discussion_topic => :gl_otherDataLicenceName,
:display_on_certificate => true,
:text_as_statement => 'This data is available under',
:help_text => 'If you use a different licence, we need the name so people can see it on your Open Data Certificate.',
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_1 'Other Licence Name',
:string,
:required => :required,
:placeholder => 'Other Licence Name'
q_otherDataLicenceURL 'Where is the licence?',
:discussion_topic => :gl_otherDataLicenceURL,
:display_on_certificate => true,
:text_as_statement => 'This licence is at',
:help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.',
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_1 'Other Licence URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Other Licence URL'
q_otherDataLicenceOpen 'Is the licence an open licence?',
:discussion_topic => :gl_otherDataLicenceOpen,
:help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.',
:help_text_more_url => 'http://opendefinition.org/',
:pick => :one,
:required => :required
dependency :rule => 'A'
condition_A :q_dataLicence, '==', :a_other
a_false 'no'
a_true 'yes',
:requirement => ['basic_7']
label_basic_7 'You must <strong>publish open data under an open licence</strong> so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_7'
dependency :rule => 'A and B'
condition_A :q_dataLicence, '==', :a_other
condition_B :q_otherDataLicenceOpen, '==', :a_false
q_contentRights 'Is there any copyright in the content of this data?',
:discussion_topic => :gl_contentRights,
:display_on_certificate => true,
:text_as_statement => 'There are',
:pick => :one,
:required => :required
a_norights 'no, the data only contains facts and numbers',
:text_as_statement => 'no rights in the content of the data',
:help_text => 'There is no copyright in factual information. If the data does not contain any content that was created through intellectual effort, there are no rights in the content.'
a_samerights 'yes, and the rights are all held by the same person or organisation',
:text_as_statement => '',
:help_text => 'Choose this option if the content in the data was all created by or transferred to the same person or organisation.'
a_mixedrights 'yes, and the rights are held by different people or organisations',
:text_as_statement => '',
:help_text => 'In some data, the rights in different records are held by different people or organisations. Information about rights needs to be kept in the data too.'
q_explicitWaiver 'Is the content of the data marked as public domain?',
:discussion_topic => :gl_explicitWaiver,
:display_on_certificate => true,
:text_as_statement => 'The content has been',
:help_text => 'Content can be marked as public domain using the <a href="http://creativecommons.org/publicdomain/">Creative Commons Public Domain Mark</a>. This helps people know that it can be freely reused.',
:pick => :one
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_norights
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'marked as public domain',
:requirement => ['standard_3']
label_standard_3 'You should <strong>mark public domain content as public domain</strong> so that people know they can reuse it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_3'
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_norights
condition_B :q_explicitWaiver, '==', :a_false
q_contentLicence 'Under which licence can others reuse content?',
:discussion_topic => :gl_contentLicence,
:display_on_certificate => true,
:text_as_statement => 'The content is available under',
:help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it but creative content does not include facts. So people need a waiver or a licence which proves that they can use the content and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the content, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_samerights
a_cc_by 'Creative Commons Attribution',
:text_as_statement => 'Creative Commons Attribution'
a_cc_by_sa 'Creative Commons Attribution Share-Alike',
:text_as_statement => 'Creative Commons Attribution Share-Alike'
a_cc_zero 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_na 'Not applicable',
:text_as_statement => ''
a_other 'Other...',
:text_as_statement => ''
q_contentNotApplicable 'Why doesn\'t a licence apply to the content of the data?',
:discussion_topic => :gl_contentNotApplicable,
:display_on_certificate => true,
:text_as_statement => 'The content in this data is not licensed because',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
a_norights 'there is no copyright in the content of this data',
:text_as_statement => 'there is no copyright',
:help_text => 'Copyright only applies to content if you spent intellectual effort creating it, for example, by writing text that\'s within the data. There\'s no copyright if the content only contains facts.'
a_expired 'copyright has expired',
:text_as_statement => 'copyright has expired',
:help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.'
a_waived 'copyright has been waived',
:text_as_statement => '',
:help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.'
q_contentWaiver 'Which waiver do you use to waive copyright?',
:discussion_topic => :gl_contentWaiver,
:display_on_certificate => true,
:text_as_statement => 'Copyright has been waived with',
:help_text => 'You need a statement to show people you\'ve done this, so they understand that they can do whatever they like with this data. Standard waivers already exist like CCZero but you can write your own with legal advice.',
:pick => :one,
:required => :required,
:display_type => 'dropdown'
dependency :rule => 'A and B and C'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
condition_C :q_contentNotApplicable, '==', :a_waived
a_cc0 'Creative Commons CCZero',
:text_as_statement => 'Creative Commons CCZero'
a_other 'Other...',
:text_as_statement => 'Other...'
q_contentOtherWaiver 'Where is the waiver for the copyright?',
:discussion_topic => :gl_contentOtherWaiver,
:display_on_certificate => true,
:text_as_statement => 'Copyright has been waived with',
:help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive your copyright.',
:required => :required
dependency :rule => 'A and B and C and D'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_na
condition_C :q_contentNotApplicable, '==', :a_waived
condition_D :q_contentWaiver, '==', :a_other
a_1 'Waiver URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Waiver URL'
q_otherContentLicenceName 'What\'s the name of the licence?',
:discussion_topic => :gl_otherContentLicenceName,
:display_on_certificate => true,
:text_as_statement => 'The content is available under',
:help_text => 'If you use a different licence, we need its name so people can see it on your Open Data Certificate.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_1 'Licence Name',
:string,
:required => :required,
:placeholder => 'Licence Name'
q_otherContentLicenceURL 'Where is the licence?',
:discussion_topic => :gl_otherContentLicenceURL,
:display_on_certificate => true,
:text_as_statement => 'The content licence is at',
:help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_1 'Licence URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Licence URL'
q_otherContentLicenceOpen 'Is the licence an open licence?',
:discussion_topic => :gl_otherContentLicenceOpen,
:help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.',
:help_text_more_url => 'http://opendefinition.org/',
:pick => :one,
:required => :required
dependency :rule => 'A and B'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
a_false 'no'
a_true 'yes',
:requirement => ['basic_8']
label_basic_8 'You must <strong>publish open data under an open licence</strong> so that people can use it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_8'
dependency :rule => 'A and B and C'
condition_A :q_contentRights, '==', :a_samerights
condition_B :q_contentLicence, '==', :a_other
condition_C :q_otherContentLicenceOpen, '==', :a_false
q_contentRightsURL 'Where are the rights and licensing of the content explained?',
:discussion_topic => :gl_contentRightsURL,
:display_on_certificate => true,
:text_as_statement => 'The rights and licensing of the content are explained at',
:help_text => 'Give the URL for a page where you describe how someone can find out the rights and licensing of a piece of content from the data.',
:required => :required
dependency :rule => 'A'
condition_A :q_contentRights, '==', :a_mixedrights
a_1 'Content Rights Description URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Content Rights Description URL'
q_copyrightStatementMetadata 'Does your rights statement include machine-readable versions of',
:discussion_topic => :gl_copyrightStatementMetadata,
:display_on_certificate => true,
:text_as_statement => 'The rights statement includes data about',
:help_text => 'It\'s good practice to embed information about rights in machine-readable formats so people can automatically attribute this data back to you when they use it.',
:help_text_more_url => 'https://github.com/theodi/open-data-licensing/blob/master/guides/publisher-guide.md',
:pick => :any
dependency :rule => 'A'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
a_dataLicense 'data licence',
:text_as_statement => 'its data licence',
:requirement => ['standard_4']
a_contentLicense 'content licence',
:text_as_statement => 'its content licence',
:requirement => ['standard_5']
a_attribution 'attribution text',
:text_as_statement => 'what attribution text to use',
:requirement => ['standard_6']
a_attributionURL 'attribution URL',
:text_as_statement => 'what attribution link to give',
:requirement => ['standard_7']
a_copyrightNotice 'copyright notice or statement',
:text_as_statement => 'a copyright notice or statement',
:requirement => ['exemplar_1']
a_copyrightYear 'copyright year',
:text_as_statement => 'the copyright year',
:requirement => ['exemplar_2']
a_copyrightHolder 'copyright holder',
:text_as_statement => 'the copyright holder',
:requirement => ['exemplar_3']
label_standard_4 'You should provide <strong>machine-readable data in your rights statement about the licence</strong> for this data, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_4'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_dataLicense
label_standard_5 'You should provide <strong>machine-readable data in your rights statement about the licence for the content</strong> of this data, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_5'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_contentLicense
label_standard_6 'You should provide <strong>machine-readable data in your rights statement about the text to use when citing the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_6'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_attribution
label_standard_7 'You should provide <strong>machine-readable data in your rights statement about the URL to link to when citing this data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_7'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_attributionURL
label_exemplar_1 'You should provide <strong>machine-readable data in your rights statement about the copyright statement or notice of this data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_1'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightNotice
label_exemplar_2 'You should provide <strong>machine-readable data in your rights statement about the copyright year for the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_2'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightYear
label_exemplar_3 'You should provide <strong>machine-readable data in your rights statement about the copyright holder for the data</strong>, so automatic tools can use it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_3'
dependency :rule => 'A and B'
condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightHolder
label_group_4 'Privacy',
:help_text => 'how you protect people\'s privacy',
:customer_renderer => '/partials/fieldset'
q_dataPersonal 'Can individuals be identified from this data?',
:discussion_topic => :gl_dataPersonal,
:display_on_certificate => true,
:text_as_statement => 'This data contains',
:pick => :one,
:required => :pilot
a_not_personal 'no, the data is not about people or their activities',
:text_as_statement => 'no data about individuals',
:help_text => 'Remember that individuals can still be identified even if data isn\'t directly about them. For example, road traffic flow data combined with an individual\'s commuting patterns could reveal information about that person.'
a_summarised 'no, the data has been anonymised by aggregating individuals into groups, so they can\'t be distinguished from other people in the group',
:text_as_statement => 'aggregated data',
:help_text => 'Statistical disclosure controls can help to make sure that individuals are not identifiable within aggregate data.'
a_individual 'yes, there is a risk that individuals be identified, for example by third parties with access to extra information',
:text_as_statement => 'information that could identify individuals',
:help_text => 'Some data is legitimately about individuals like civil service pay or public expenses for example.'
q_statisticalAnonAudited 'Has your anonymisation process been independently audited?',
:discussion_topic => :gl_statisticalAnonAudited,
:display_on_certificate => true,
:text_as_statement => 'The anonymisation process has been',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataPersonal, '==', :a_summarised
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_8']
label_standard_8 'You should <strong>have your anonymisation process audited independently</strong> to ensure it reduces the risk of individuals being reidentified.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_8'
dependency :rule => 'A and B'
condition_A :q_dataPersonal, '==', :a_summarised
condition_B :q_statisticalAnonAudited, '==', :a_false
q_appliedAnon 'Have you attempted to reduce or remove the possibility of individuals being identified?',
:discussion_topic => :gl_appliedAnon,
:display_on_certificate => true,
:text_as_statement => 'This data about individuals has been',
:help_text => 'Anonymisation reduces the risk of individuals being identified from the data you publish. The best technique to use depends on the kind of data you have.',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_dataPersonal, '==', :a_individual
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'anonymised'
q_lawfulDisclosure 'Are you required or permitted by law to publish this data about individuals?',
:discussion_topic => :gl_lawfulDisclosure,
:display_on_certificate => true,
:text_as_statement => 'By law, this data about individuals',
:help_text => 'The law might require you to publish data about people, such as the names of company directors. Or you might have permission from the affected individuals to publish information about them.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'can be published',
:requirement => ['pilot_5']
label_pilot_5 'You should <strong>only publish personal data without anonymisation if you are required or permitted to do so by law</strong>.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_5'
dependency :rule => 'A and B and C'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_false
q_lawfulDisclosureURL 'Where do you document your right to publish data about individuals?',
:discussion_topic => :gl_lawfulDisclosureURL,
:display_on_certificate => true,
:text_as_statement => 'The right to publish this data about individuals is documented at'
dependency :rule => 'A and B and C'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_true
a_1 'Disclosure Rationale URL',
:string,
:input_type => :url,
:placeholder => 'Disclosure Rationale URL',
:requirement => ['standard_9']
label_standard_9 'You should <strong>document your right to publish data about individuals</strong> for people who use your data and for those affected by disclosure.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_9'
dependency :rule => 'A and B and C and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_false
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_lawfulDisclosureURL, '==', {:string_value => '', :answer_reference => '1'}
q_riskAssessmentExists 'Have you assessed the risks of disclosing personal data?',
:discussion_topic => :gl_riskAssessmentExists,
:display_on_certificate => true,
:text_as_statement => 'The curator has',
:help_text => 'A risk assessment measures risks to the privacy of individuals in your data as well as the use and disclosure of that information.',
:pick => :one
dependency :rule => 'A and (B or C)'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
a_false 'no',
:text_as_statement => 'not carried out a privacy risk assessment'
a_true 'yes',
:text_as_statement => 'carried out a privacy risk assessment',
:requirement => ['pilot_6']
label_pilot_6 'You should <strong>assess the risks of disclosing personal data</strong> if you publish data about individuals.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_6'
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_false
q_riskAssessmentUrl 'Where is your risk assessment published?',
:discussion_topic => :gl_riskAssessmentUrl,
:display_on_certificate => true,
:text_as_statement => 'The risk assessment is published at',
:help_text => 'Give a URL to where people can check how you have assessed the privacy risks to individuals. This may be redacted or summarised if it contains sensitive information.'
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
a_1 'Risk Assessment URL',
:string,
:input_type => :url,
:placeholder => 'Risk Assessment URL',
:requirement => ['standard_10']
label_standard_10 'You should <strong>publish your privacy risk assessment</strong> so people can understand how you have assessed the risks of disclosing data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_10'
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '==', {:string_value => '', :answer_reference => '1'}
q_riskAssessmentAudited 'Has your risk assessment been independently audited?',
:discussion_topic => :gl_riskAssessmentAudited,
:display_on_certificate => true,
:text_as_statement => 'The risk assessment has been',
:help_text => 'It\'s good practice to check your risk assessment was done correctly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.',
:pick => :one
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_11']
label_standard_11 'You should <strong>have your risk assessment audited independently</strong> to ensure it has been carried out correctly.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_11'
dependency :rule => 'A and (B or C) and D and E and F'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_F :q_riskAssessmentAudited, '==', :a_false
q_anonymisationAudited 'Has your anonymisation approach been independently audited?',
:discussion_topic => :gl_anonymisationAudited,
:display_on_certificate => true,
:text_as_statement => 'The anonymisation of the data has been',
:help_text => 'It is good practice to make sure your process to remove personal identifiable data works properly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.',
:pick => :one
dependency :rule => 'A and (B or C) and D'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'independently audited',
:requirement => ['standard_12']
label_standard_12 'You should <strong>have your anonymisation process audited independently</strong> by an expert to ensure it is appropriate for your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_12'
dependency :rule => 'A and (B or C) and D and E'
condition_A :q_dataPersonal, '==', :a_individual
condition_B :q_appliedAnon, '==', :a_true
condition_C :q_lawfulDisclosure, '==', :a_true
condition_D :q_riskAssessmentExists, '==', :a_true
condition_E :q_anonymisationAudited, '==', :a_false
end
section_practical 'Practical Information',
:description => 'Findability, accuracy, quality and guarantees' do
label_group_6 'Findability',
:help_text => 'how you help people find your data',
:customer_renderer => '/partials/fieldset'
q_onWebsite 'Is there a link to your data from your main website?',
:discussion_topic => :onWebsite,
:help_text => 'Data can be found more easily if it is linked to from your main website.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_13']
label_standard_13 'You should <strong>ensure that people can find the data from your main website</strong> so that people can find it more easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_13'
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_false
repeater 'Web Page' do
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_true
q_webpage 'Which page on your website links to the data?',
:discussion_topic => :webpage,
:display_on_certificate => true,
:text_as_statement => 'The website links to the data from',
:help_text => 'Give a URL on your main website that includes a link to this data.',
:required => :required
dependency :rule => 'A'
condition_A :q_onWebsite, '==', :a_true
a_1 'Web page URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Web page URL'
end
q_listed 'Is your data listed within a collection?',
:discussion_topic => :listed,
:help_text => 'Data is easier for people to find when it\'s in relevant data catalogs like academic, public sector or health for example, or when it turns up in relevant search results.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_14']
label_standard_14 'You should <strong>ensure that people can find your data when they search for it</strong> in locations that list data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_14'
dependency :rule => 'A'
condition_A :q_listed, '==', :a_false
repeater 'Listing' do
dependency :rule => 'A'
condition_A :q_listed, '==', :a_true
q_listing 'Where is it listed?',
:discussion_topic => :listing,
:display_on_certificate => true,
:text_as_statement => 'The data appears in this collection',
:help_text => 'Give a URL where this data is listed within a relevant collection. For example, data.gov.uk (if it\'s UK public sector data), hub.data.ac.uk (if it\'s UK academia data) or a URL for search engine results.',
:required => :required
dependency :rule => 'A'
condition_A :q_listed, '==', :a_true
a_1 'Listing URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Listing URL'
end
q_referenced 'Is this data referenced from your own publications?',
:discussion_topic => :referenced,
:help_text => 'When you reference your data within your own publications, such as reports, presentations or blog posts, you give it more context and help people find and understand it better.',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_15']
label_standard_15 'You should <strong>reference data from your own publications</strong> so that people are aware of its availability and context.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_15'
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_false
repeater 'Reference' do
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_true
q_reference 'Where is your data referenced?',
:discussion_topic => :reference,
:display_on_certificate => true,
:text_as_statement => 'This data is referenced from',
:help_text => 'Give a URL to a document that cites or references this data.',
:required => :required
dependency :rule => 'A'
condition_A :q_referenced, '==', :a_true
a_1 'Reference URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Reference URL'
end
label_group_7 'Accuracy',
:help_text => 'how you keep your data up-to-date',
:customer_renderer => '/partials/fieldset'
q_serviceType 'Does the data behind your API change?',
:discussion_topic => :serviceType,
:display_on_certificate => true,
:text_as_statement => 'The data behind the API',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_static 'no, the API gives access to unchanging data',
:text_as_statement => 'will not change',
:help_text => 'Some APIs just make accessing an unchanging dataset easier, particularly when there\'s lots of it.'
a_changing 'yes, the API gives access to changing data',
:text_as_statement => 'will change',
:help_text => 'Some APIs give instant access to more up-to-date and ever-changing data'
q_timeSensitive 'Will your data go out of date?',
:discussion_topic => :timeSensitive,
:display_on_certificate => true,
:text_as_statement => 'The accuracy or relevance of this data will',
:pick => :one
dependency :rule => '(A or B or (C and D))'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
a_true 'yes, this data will go out of date',
:text_as_statement => 'go out of date',
:help_text => 'For example, a dataset of bus stop locations will go out of date over time as some are moved or new ones created.'
a_timestamped 'yes, this data will go out of date over time but itโs time stamped',
:text_as_statement => 'go out of date but it is timestamped',
:help_text => 'For example, population statistics usually include a fixed timestamp to indicate when the statistics were relevant.',
:requirement => ['pilot_7']
a_false 'no, this data does not contain any time-sensitive information',
:text_as_statement => 'not go out of date',
:help_text => 'For example, the results of an experiment will not go out of date because the data accurately reports observed outcomes.',
:requirement => ['standard_16']
label_pilot_7 'You should <strong>put timestamps in your data when you release it</strong> so people know the period it relates to and when it will expire.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_7'
dependency :rule => '(A or B or (C and D)) and (E and F)'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
condition_E :q_timeSensitive, '!=', :a_timestamped
condition_F :q_timeSensitive, '!=', :a_false
label_standard_16 'You should <strong>publish updates to time-sensitive data</strong> so that it does not go stale.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_16'
dependency :rule => '(A or B or (C and D)) and (E)'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_releaseType, '==', :a_collection
condition_C :q_releaseType, '==', :a_service
condition_D :q_serviceType, '==', :a_static
condition_E :q_timeSensitive, '!=', :a_false
q_frequentChanges 'Does this data change at least daily?',
:discussion_topic => :frequentChanges,
:display_on_certificate => true,
:text_as_statement => 'This data changes',
:help_text => 'Tell people if the underlying data changes on most days. When data changes frequently it also goes out of date quickly, so people need to know if you also update it frequently and quickly too.',
:pick => :one,
:required => :pilot
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'at least daily'
q_seriesType 'What type of dataset series is this?',
:discussion_topic => :seriesType,
:display_on_certificate => true,
:text_as_statement => 'This data is a series of',
:pick => :one,
:required => :exemplar
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
a_dumps 'regular copies of a complete database',
:text_as_statement => 'copies of a database',
:help_text => 'Choose if you publish new and updated copies of your full database regularly. When you create database dumps, it\'s useful for people to have access to a feed of the changes so they can keep their copies up to date.'
a_aggregate 'regular aggregates of changing data',
:text_as_statement => 'aggregates of changing data',
:help_text => 'Choose if you create new datasets regularly. You might do this if the underlying data can\'t be released as open data or if you only publish data that\'s new since the last publication.'
q_changeFeed 'Is a feed of changes available?',
:discussion_topic => :changeFeed,
:display_on_certificate => true,
:text_as_statement => 'A feed of changes to this data',
:help_text => 'Tell people if you provide a stream of changes that affect this data, like new entries or amendments to existing entries. Feeds might be in RSS, Atom or custom formats.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_seriesType, '==', :a_dumps
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'is available',
:requirement => ['exemplar_4']
label_exemplar_4 'You should <strong>provide a feed of changes to your data</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_4'
dependency :rule => 'A and B and C and D'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_seriesType, '==', :a_dumps
condition_D :q_changeFeed, '==', :a_false
q_frequentSeriesPublication 'How often do you create a new release?',
:discussion_topic => :frequentSeriesPublication,
:display_on_certificate => true,
:text_as_statement => 'New releases of this data are made',
:help_text => 'This determines how out of date this data becomes before people can get an update.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
a_rarely 'less than once a month',
:text_as_statement => 'less than once a month'
a_monthly 'at least every month',
:text_as_statement => 'at least every month',
:requirement => ['pilot_8']
a_weekly 'at least every week',
:text_as_statement => 'at least every week',
:requirement => ['standard_17']
a_daily 'at least every day',
:text_as_statement => 'at least every day',
:requirement => ['exemplar_5']
label_pilot_8 'You should <strong>create a new dataset release every month</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_8'
dependency :rule => 'A and B and (C and D and E)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_monthly
condition_D :q_frequentSeriesPublication, '!=', :a_weekly
condition_E :q_frequentSeriesPublication, '!=', :a_daily
label_standard_17 'You should <strong>create a new dataset release every week</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_17'
dependency :rule => 'A and B and (C and D)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_weekly
condition_D :q_frequentSeriesPublication, '!=', :a_daily
label_exemplar_5 'You should <strong>create a new dataset release every day</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_5'
dependency :rule => 'A and B and (C)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_frequentChanges, '==', :a_true
condition_C :q_frequentSeriesPublication, '!=', :a_daily
q_seriesPublicationDelay 'How long is the delay between when you create a dataset and when you publish it?',
:discussion_topic => :seriesPublicationDelay,
:display_on_certificate => true,
:text_as_statement => 'The lag between creation and publication of this data is',
:pick => :one
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_extreme 'longer than the gap between releases',
:text_as_statement => 'longer than the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes more than a day for it to be published.'
a_reasonable 'about the same as the gap between releases',
:text_as_statement => 'about the same as the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes about a day for it to be published.',
:requirement => ['pilot_9']
a_good 'less than half the gap between releases',
:text_as_statement => 'less than half the gap between releases',
:help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes less than twelve hours for it to be published.',
:requirement => ['standard_18']
a_minimal 'there is minimal or no delay',
:text_as_statement => 'minimal',
:help_text => 'Choose this if you publish within a few seconds or a few minutes.',
:requirement => ['exemplar_6']
label_pilot_9 'You should <strong>have a reasonable delay between when you create and publish a dataset</strong> that is less than the gap between releases so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_9'
dependency :rule => 'A and (B and C and D)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_reasonable
condition_C :q_seriesPublicationDelay, '!=', :a_good
condition_D :q_seriesPublicationDelay, '!=', :a_minimal
label_standard_18 'You should <strong>have a short delay between when you create and publish a dataset</strong> that is less than half the gap between releases so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_18'
dependency :rule => 'A and (B and C)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_good
condition_C :q_seriesPublicationDelay, '!=', :a_minimal
label_exemplar_6 'You should <strong>have minimal or no delay between when you create and publish a dataset</strong> so people keep their copies up-to-date and accurate.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_6'
dependency :rule => 'A and (B)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_seriesPublicationDelay, '!=', :a_minimal
q_provideDumps 'Do you also publish dumps of this dataset?',
:discussion_topic => :provideDumps,
:display_on_certificate => true,
:text_as_statement => 'The curator publishes',
:help_text => 'A dump is an extract of the whole dataset into a file that people can download. This lets people do analysis that\'s different to analysis with API access.',
:pick => :one
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'dumps of the data',
:requirement => ['standard_19']
label_standard_19 'You should <strong>let people download your entire dataset</strong> so that they can do more complete and accurate analysis with all the data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_19'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_false
q_dumpFrequency 'How frequently do you create a new database dump?',
:discussion_topic => :dumpFrequency,
:display_on_certificate => true,
:text_as_statement => 'Database dumps are created',
:help_text => 'Faster access to more frequent extracts of the whole dataset means people can get started quicker with the most up-to-date data.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
a_rarely 'less frequently than once a month',
:text_as_statement => 'less frequently than once a month'
a_monthly 'at least every month',
:text_as_statement => 'at least every month',
:requirement => ['pilot_10']
a_weekly 'within a week of any change',
:text_as_statement => 'within a week of any change',
:requirement => ['standard_20']
a_daily 'within a day of any change',
:text_as_statement => 'within a day of any change',
:requirement => ['exemplar_7']
label_pilot_10 'You should <strong>create a new database dump every month</strong> so that people have the latest data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_10'
dependency :rule => 'A and B and C and (D and E and F)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_monthly
condition_E :q_dumpFrequency, '!=', :a_weekly
condition_F :q_dumpFrequency, '!=', :a_daily
label_standard_20 'You should <strong>create a new database dump within a week of any change</strong> so that people have less time to wait for the latest data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_20'
dependency :rule => 'A and B and C and (D and E)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_weekly
condition_E :q_dumpFrequency, '!=', :a_daily
label_exemplar_7 'You should <strong>create a new database dump within a day of any change</strong> so that people find it easier to get the latest data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_7'
dependency :rule => 'A and B and C and (D)'
condition_A :q_releaseType, '==', :a_service
condition_B :q_serviceType, '==', :a_changing
condition_C :q_provideDumps, '==', :a_true
condition_D :q_dumpFrequency, '!=', :a_daily
q_corrected 'Will your data be corrected if it has errors?',
:discussion_topic => :corrected,
:display_on_certificate => true,
:text_as_statement => 'Any errors in this data are',
:help_text => 'It\'s good practice to fix errors in your data especially if you use it yourself. When you make corrections, people need to be told about them.',
:pick => :one
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_timeSensitive, '!=', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'corrected',
:requirement => ['standard_21']
label_standard_21 'You should <strong>correct data when people report errors</strong> so everyone benefits from improvements in accuracy.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_21'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_timeSensitive, '!=', :a_true
condition_C :q_corrected, '==', :a_false
label_group_8 'Quality',
:help_text => 'how much people can rely on your data',
:customer_renderer => '/partials/fieldset'
q_qualityUrl 'Where do you document issues with the quality of this data?',
:discussion_topic => :qualityUrl,
:display_on_certificate => true,
:text_as_statement => 'Data quality is documented at',
:help_text => 'Give a URL where people can find out about the quality of your data. People accept that errors are inevitable, from equipment malfunctions or mistakes that happen in system migrations. You should be open about quality so people can judge how much to rely on this data.'
a_1 'Data Quality Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Data Quality Documentation URL',
:requirement => ['standard_22']
label_standard_22 'You should <strong>document any known issues with your data quality</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_22'
dependency :rule => 'A'
condition_A :q_qualityUrl, '==', {:string_value => '', :answer_reference => '1'}
q_qualityControlUrl 'Where is your quality control process described?',
:discussion_topic => :qualityControlUrl,
:display_on_certificate => true,
:text_as_statement => 'Quality control processes are described at',
:help_text => 'Give a URL for people to learn about ongoing checks on your data, either automatic or manual. This reassures them that you take quality seriously and encourages improvements that benefit everyone.'
a_1 'Quality Control Process Description URL',
:string,
:input_type => :url,
:placeholder => 'Quality Control Process Description URL',
:requirement => ['exemplar_8']
label_exemplar_8 'You should <strong>document your quality control process</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_8'
dependency :rule => 'A'
condition_A :q_qualityControlUrl, '==', {:string_value => '', :answer_reference => '1'}
label_group_9 'Guarantees',
:help_text => 'how much people can depend on your dataโs availability',
:customer_renderer => '/partials/fieldset'
q_backups 'Do you take offsite backups?',
:discussion_topic => :backups,
:display_on_certificate => true,
:text_as_statement => 'The data is',
:help_text => 'Taking a regular offsite backup helps ensure that the data won\'t be lost in the case of accident.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'backed up offsite',
:requirement => ['standard_23']
label_standard_23 'You should <strong>take a result offsite backup</strong> so that the data won\'t be lost if an accident happens.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_23'
dependency :rule => 'A'
condition_A :q_backups, '==', :a_false
q_slaUrl 'Where do you describe any guarantees about service availability?',
:discussion_topic => :slaUrl,
:display_on_certificate => true,
:text_as_statement => 'Service availability is described at',
:help_text => 'Give a URL for a page that describes what guarantees you have about your service being available for people to use. For example you might have a guaranteed uptime of 99.5%, or you might provide no guarantees.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Service Availability Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Service Availability Documentation URL',
:requirement => ['standard_24']
label_standard_24 'You should <strong>describe what guarantees you have around service availability</strong> so that people know how much they can rely on it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_24'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_slaUrl, '==', {:string_value => '', :answer_reference => '1'}
q_statusUrl 'Where do you give information about the current status of the service?',
:discussion_topic => :statusUrl,
:display_on_certificate => true,
:text_as_statement => 'Service status is given at',
:help_text => 'Give a URL for a page that tells people about the current status of your service, including any faults you are aware of.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Service Status URL',
:string,
:input_type => :url,
:placeholder => 'Service Status URL',
:requirement => ['exemplar_9']
label_exemplar_9 'You should <strong>have a service status page</strong> that tells people about the current status of your service.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_9'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_statusUrl, '==', {:string_value => '', :answer_reference => '1'}
q_onGoingAvailability 'How long will this data be available for?',
:discussion_topic => :onGoingAvailability,
:display_on_certificate => true,
:text_as_statement => 'The data is available',
:pick => :one
a_experimental 'it might disappear at any time',
:text_as_statement => 'experimentally and might disappear at any time'
a_short 'it\'s available experimentally but should be around for another year or so',
:text_as_statement => 'experimentally for another year or so',
:requirement => ['pilot_11']
a_medium 'it\'s in your medium-term plans so should be around for a couple of years',
:text_as_statement => 'for at least a couple of years',
:requirement => ['standard_25']
a_long 'it\'s part of your day-to-day operations so will stay published for a long time',
:text_as_statement => 'for a long time',
:requirement => ['exemplar_10']
label_pilot_11 'You should <strong>guarantee that your data will be available in this form for at least a year</strong> so that people can decide how much to rely on your data.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_11'
dependency :rule => 'A and B and C'
condition_A :q_onGoingAvailability, '!=', :a_short
condition_B :q_onGoingAvailability, '!=', :a_medium
condition_C :q_onGoingAvailability, '!=', :a_long
label_standard_25 'You should <strong>guarantee that your data will be available in this form in the medium-term</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_25'
dependency :rule => 'A and B'
condition_A :q_onGoingAvailability, '!=', :a_medium
condition_B :q_onGoingAvailability, '!=', :a_long
label_exemplar_10 'You should <strong>guarantee that your data will be available in this form in the long-term</strong> so that people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_10'
dependency :rule => 'A'
condition_A :q_onGoingAvailability, '!=', :a_long
end
section_technical 'Technical Information',
:description => 'Locations, formats and trust' do
label_group_11 'Locations',
:help_text => 'how people can access your data',
:customer_renderer => '/partials/fieldset'
q_datasetUrl 'Where is your dataset?',
:discussion_topic => :datasetUrl,
:display_on_certificate => true,
:text_as_statement => 'This data is published at',
:help_text => 'Give a URL to the dataset itself. Open data should be linked to directly on the web so people can easily find and reuse it.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_oneoff
a_1 'Dataset URL',
:string,
:input_type => :url,
:placeholder => 'Dataset URL',
:requirement => ['basic_9', 'pilot_12']
label_basic_9 'You must <strong>provide either a URL to your data or a URL to documentation</strong> about it so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_9'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'}
label_pilot_12 'You should <strong>have a URL that is a direct link to the data itself</strong> so that people can access it easily.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_12'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_oneoff
condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'}
q_versionManagement 'How do you publish a series of the same dataset?',
:discussion_topic => :versionManagement,
:requirement => ['basic_10'],
:pick => :any
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_series
a_current 'as a single URL that\'s regularly updated',
:help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current dataset.',
:requirement => ['standard_26']
a_template 'as consistent URLs for each release',
:help_text => 'Choose this if your dataset URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['pilot_13']
a_list 'as a list of releases',
:help_text => 'Choose this if you have a list of datasets on a web page or a feed (like Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['standard_27']
label_standard_26 'You should <strong>have a single persistent URL to download the current version of your data</strong> so that people can access it easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_26'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_current
label_pilot_13 'You should <strong>use a consistent pattern for different release URLs</strong> so that people can download each one automatically.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_13'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_template
label_standard_27 'You should <strong>have a document or feed with a list of available releases</strong> so people can create scripts to download them all.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_27'
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '!=', :a_list
label_basic_10 'You must <strong>provide access to releases of your data through a URL</strong> that gives the current version, a discoverable series of URLs or through a documentation page so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_10'
dependency :rule => 'A and (B and C and D and E)'
condition_A :q_releaseType, '==', :a_series
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_versionManagement, '!=', :a_current
condition_D :q_versionManagement, '!=', :a_template
condition_E :q_versionManagement, '!=', :a_list
q_currentDatasetUrl 'Where is your current dataset?',
:discussion_topic => :currentDatasetUrl,
:display_on_certificate => true,
:text_as_statement => 'The current dataset is available at',
:help_text => 'Give a single URL to the most recent version of the dataset. The content at this URL should change each time a new version is released.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_current
a_1 'Current Dataset URL',
:string,
:input_type => :url,
:placeholder => 'Current Dataset URL',
:required => :required
q_versionsTemplateUrl 'What format do dataset release URLs follow?',
:discussion_topic => :versionsTemplateUrl,
:display_on_certificate => true,
:text_as_statement => 'Releases follow this consistent URL pattern',
:help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_template
a_1 'Version Template URL',
:string,
:input_type => :text,
:placeholder => 'Version Template URL',
:required => :required
q_versionsUrl 'Where is your list of dataset releases?',
:discussion_topic => :versionsUrl,
:display_on_certificate => true,
:text_as_statement => 'Releases of this data are listed at',
:help_text => 'Give a URL to a page or feed with a machine-readable list of datasets. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_series
condition_B :q_versionManagement, '==', :a_list
a_1 'Version List URL',
:string,
:input_type => :url,
:placeholder => 'Version List URL',
:required => :required
q_endpointUrl 'Where is the endpoint for your API?',
:discussion_topic => :endpointUrl,
:display_on_certificate => true,
:text_as_statement => 'The API service endpoint is',
:help_text => 'Give a URL that\'s a starting point for people\'s scripts to access your API. This should be a service description document that helps the script to work out which services exist.'
dependency :rule => 'A'
condition_A :q_releaseType, '==', :a_service
a_1 'Endpoint URL',
:string,
:input_type => :url,
:placeholder => 'Endpoint URL',
:requirement => ['basic_11', 'standard_28']
label_basic_11 'You must <strong>provide either an API endpoint URL or a URL to its documentation</strong> so that people can find it.',
:custom_renderer => '/partials/requirement_basic',
:requirement => 'basic_11'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'}
condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'}
label_standard_28 'You should <strong>have a service description document or single entry point for your API</strong> so that people can access it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_28'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'}
q_dumpManagement 'How do you publish database dumps?',
:discussion_topic => :dumpManagement,
:pick => :any
dependency :rule => 'A and B'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
a_current 'as a single URL that\'s regularly updated',
:help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current database dump.',
:requirement => ['standard_29']
a_template 'as consistent URLs for each release',
:help_text => 'Choose this if your database dump URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['exemplar_11']
a_list 'as a list of releases',
:help_text => 'Choose this if you have a list of database dumps on a web page or a feed (such as Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.',
:requirement => ['exemplar_12']
label_standard_29 'You should <strong>have a single persistent URL to download the current dump of your database</strong> so that people can find it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_29'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_current
label_exemplar_11 'You should <strong>use a consistent pattern for database dump URLs</strong> so that people can can download each one automatically.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_11'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_template
label_exemplar_12 'You should <strong>have a document or feed with a list of available database dumps</strong> so people can create scripts to download them all',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_12'
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '!=', :a_list
q_currentDumpUrl 'Where is the current database dump?',
:discussion_topic => :currentDumpUrl,
:display_on_certificate => true,
:text_as_statement => 'The most recent database dump is always available at',
:help_text => 'Give a URL to the most recent dump of the database. The content at this URL should change each time a new database dump is created.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_current
a_1 'Current Dump URL',
:string,
:input_type => :url,
:placeholder => 'Current Dump URL',
:required => :required
q_dumpsTemplateUrl 'What format do database dump URLs follow?',
:discussion_topic => :dumpsTemplateUrl,
:display_on_certificate => true,
:text_as_statement => 'Database dumps follow the consistent URL pattern',
:help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_template
a_1 'Dump Template URL',
:string,
:input_type => :text,
:placeholder => 'Dump Template URL',
:required => :required
q_dumpsUrl 'Where is your list of available database dumps?',
:discussion_topic => :dumpsUrl,
:display_on_certificate => true,
:text_as_statement => 'A list of database dumps is at',
:help_text => 'Give a URL to a page or feed with a machine-readable list of database dumps. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A and B and C'
condition_A :q_releaseType, '==', :a_service
condition_B :q_provideDumps, '==', :a_true
condition_C :q_dumpManagement, '==', :a_list
a_1 'Dump List URL',
:string,
:input_type => :url,
:placeholder => 'Dump List URL',
:required => :required
q_changeFeedUrl 'Where is your feed of changes?',
:discussion_topic => :changeFeedUrl,
:display_on_certificate => true,
:text_as_statement => 'A feed of changes to this data is at',
:help_text => 'Give a URL to a page or feed that provides a machine-readable list of the previous versions of the database dumps. Use the URL of the first page which should link to the rest of the pages.',
:required => :required
dependency :rule => 'A'
condition_A :q_changeFeed, '==', :a_true
a_1 'Change Feed URL',
:string,
:input_type => :url,
:placeholder => 'Change Feed URL',
:required => :required
label_group_12 'Formats',
:help_text => 'how people can work with your data',
:customer_renderer => '/partials/fieldset'
q_machineReadable 'Is this data machine-readable?',
:discussion_topic => :machineReadable,
:display_on_certificate => true,
:text_as_statement => 'This data is',
:help_text => 'People prefer data formats which are easily processed by a computer, for speed and accuracy. For example, a scanned photocopy of a spreadsheet would not be machine-readable but a CSV file would be.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable',
:requirement => ['pilot_14']
label_pilot_14 'You should <strong>provide your data in a machine-readable format</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_14'
dependency :rule => 'A'
condition_A :q_machineReadable, '==', :a_false
q_openStandard 'Is this data in a standard open format?',
:discussion_topic => :openStandard,
:display_on_certificate => true,
:text_as_statement => 'The format of this data is',
:help_text => 'Open standards are created through a fair, transparent and collaborative process. Anyone can implement them and thereโs lots of support so itโs easier for you to share data with more people. For example, XML, CSV and JSON are open standards.',
:help_text_more_url => 'https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/183962/Open-Standards-Principles-FINAL.pdf',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'a standard open format',
:requirement => ['standard_30']
label_standard_30 'You should <strong>provide your data in an open standard format</strong> so that people can use widely available tools to process it more easily.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_30'
dependency :rule => 'A'
condition_A :q_openStandard, '==', :a_false
q_dataType 'What kind of data do you publish?',
:discussion_topic => :dataType,
:pick => :any
a_documents 'human-readable documents',
:help_text => 'Choose this if your data is meant for human consumption. For example; policy documents, white papers, reports and meeting minutes. These usually have some structure to them but are mostly text.'
a_statistical 'statistical data like counts, averages and percentages',
:help_text => 'Choose this if your data is statistical or numeric data like counts, averages or percentages. Like census results, traffic flow information or crime statistics for example.'
a_geographic 'geographic information, such as points and boundaries',
:help_text => 'Choose this if your data can be plotted on a map as points, boundaries or lines.'
a_structured 'other kinds of structured data',
:help_text => 'Choose this if your data is structured in other ways. Like event details, railway timetables, contact information or anything that can be interpreted as data, and analysed and presented in multiple ways.'
q_documentFormat 'Do your human-readable documents include formats that',
:discussion_topic => :documentFormat,
:display_on_certificate => true,
:text_as_statement => 'Documents are published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_documents
a_semantic 'describe semantic structure like HTML, Docbook or Markdown',
:text_as_statement => 'in a semantic format',
:help_text => 'These formats label structures like chapters, headings and tables that make it easy to automatically create summaries like tables of contents and glossaries. They also make it easy to apply different styles to the document so its appearance changes.',
:requirement => ['standard_31']
a_format 'describe information on formatting like OOXML or PDF',
:text_as_statement => 'in a display format',
:help_text => 'These formats emphasise appearance like fonts, colours and positioning of different elements within the page. These are good for human consumption, but aren\'t as easy for people to process automatically and change style.',
:requirement => ['pilot_15']
a_unsuitable 'aren\'t meant for documents like Excel, JSON or CSV',
:text_as_statement => 'in a format unsuitable for documents',
:help_text => 'These formats better suit tabular or structured data.'
label_standard_31 'You should <strong>publish documents in a format that exposes semantic structure</strong> so that people can display them in different styles.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_31'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_documents
condition_B :q_documentFormat, '!=', :a_semantic
label_pilot_15 'You should <strong>publish documents in a format designed specifically for them</strong> so that they\'re easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_15'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_documents
condition_B :q_documentFormat, '!=', :a_semantic
condition_C :q_documentFormat, '!=', :a_format
q_statisticalFormat 'Does your statistical data include formats that',
:discussion_topic => :statisticalFormat,
:display_on_certificate => true,
:text_as_statement => 'Statistical data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_statistical
a_statistical 'expose the structure of statistical hypercube data like <a href="http://sdmx.org/">SDMX</a> or <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a>',
:text_as_statement => 'in a statistical data format',
:help_text => 'Individual observations in hypercubes relate to a particular measure and a set of dimensions. Each observation may also be related to annotations that give extra context. Formats like <a href="http://sdmx.org/">SDMX</a> and <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a> are designed to express this underlying structure.',
:requirement => ['exemplar_13']
a_tabular 'treat statistical data as a table like CSV',
:text_as_statement => 'in a tabular data format',
:help_text => 'These formats arrange statistical data within a table of rows and columns. This lacks extra context about the underlying hypercube but is easy to process.',
:requirement => ['standard_32']
a_format 'focus on the format of tabular data like Excel',
:text_as_statement => 'in a presentation format',
:help_text => 'Spreadsheets use formatting like italic or bold text, and indentation within fields to describe its appearance and underlying structure. This styling helps people to understand the meaning of your data but makes it less suitable for computers to process.',
:requirement => ['pilot_16']
a_unsuitable 'aren\'t meant for statistical or tabular data like Word or PDF',
:text_as_statement => 'in a format unsuitable for statistical data',
:help_text => 'These formats don\'t suit statistical data because they obscure the underlying structure of the data.'
label_exemplar_13 'You should <strong>publish statistical data in a format that exposes dimensions and measures</strong> so that it\'s easy to analyse.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_13'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
label_standard_32 'You should <strong>publish tabular data in a format that exposes tables of data</strong> so that it\'s easy to analyse.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_32'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
condition_C :q_statisticalFormat, '!=', :a_tabular
label_pilot_16 'You should <strong>publish tabular data in a format designed for that purpose</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_16'
dependency :rule => 'A and (B and C and D)'
condition_A :q_dataType, '==', :a_statistical
condition_B :q_statisticalFormat, '!=', :a_statistical
condition_C :q_statisticalFormat, '!=', :a_tabular
condition_D :q_statisticalFormat, '!=', :a_format
q_geographicFormat 'Does your geographic data include formats that',
:discussion_topic => :geographicFormat,
:display_on_certificate => true,
:text_as_statement => 'Geographic data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_geographic
a_specific 'are designed for geographic data like <a href="http://www.opengeospatial.org/standards/kml/">KML</a> or <a href="http://www.geojson.org/">GeoJSON</a>',
:text_as_statement => 'in a geographic data format',
:help_text => 'These formats describe points, lines and boundaries, and expose structures in the data which make it easier to process automatically.',
:requirement => ['exemplar_14']
a_generic 'keeps data structured like JSON, XML or CSV',
:text_as_statement => 'in a generic data format',
:help_text => 'Any format that stores normal structured data can express geographic data too, particularly if it only holds data about points.',
:requirement => ['pilot_17']
a_unsuitable 'aren\'t designed for geographic data like Word or PDF',
:text_as_statement => 'in a format unsuitable for geographic data',
:help_text => 'These formats don\'t suit geographic data because they obscure the underlying structure of the data.'
label_exemplar_14 'You should <strong>publish geographic data in a format designed that purpose</strong> so that people can use widely available tools to process it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_14'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_geographic
condition_B :q_geographicFormat, '!=', :a_specific
label_pilot_17 'You should <strong>publish geographic data as structured data</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_17'
dependency :rule => 'A and (B and C)'
condition_A :q_dataType, '==', :a_geographic
condition_B :q_geographicFormat, '!=', :a_specific
condition_C :q_geographicFormat, '!=', :a_generic
q_structuredFormat 'Does your structured data include formats that',
:discussion_topic => :structuredFormat,
:display_on_certificate => true,
:text_as_statement => 'Structured data is published',
:pick => :one
dependency :rule => 'A'
condition_A :q_dataType, '==', :a_structured
a_suitable 'are designed for structured data like JSON, XML, Turtle or CSV',
:text_as_statement => 'in a structured data format',
:help_text => 'These formats organise data into a basic structure of things which have values for a known set of properties. These formats are easy for computers to process automatically.',
:requirement => ['pilot_18']
a_unsuitable 'aren\'t designed for structured data like Word or PDF',
:text_as_statement => 'in a format unsuitable for structured data',
:help_text => 'These formats don\'t suit this kind of data because they obscure its underlying structure.'
label_pilot_18 'You should <strong>publish structured data in a format designed that purpose</strong> so that it\'s easy to process.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_18'
dependency :rule => 'A and (B)'
condition_A :q_dataType, '==', :a_structured
condition_B :q_structuredFormat, '!=', :a_suitable
q_identifiers 'Does your data use persistent identifiers?',
:discussion_topic => :identifiers,
:display_on_certificate => true,
:text_as_statement => 'The data includes',
:help_text => 'Data is usually about real things like schools or roads or uses a coding scheme. If data from different sources use the same persistent and unique identifier to refer to the same things, people can combine sources easily to create more useful data. Identifiers might be GUIDs, DOIs or URLs.',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'persistent identifiers',
:requirement => ['standard_33']
label_standard_33 'You should <strong>use identifiers for things in your data</strong> so that they can be easily related with other data about those things.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_33'
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_false
q_resolvingIds 'Can the identifiers in your data be used to find extra information?',
:discussion_topic => :resolvingIds,
:display_on_certificate => true,
:text_as_statement => 'The persistent identifiers',
:pick => :one
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_true
a_false 'no, the identifiers can\'t be used to find extra information',
:text_as_statement => ''
a_service 'yes, there is a service that people can use to resolve the identifiers',
:text_as_statement => 'resolve using a service',
:help_text => 'Online services can be used to give people information about identifiers such as GUIDs or DOIs which can\'t be directly accessed in the way that URLs are.',
:requirement => ['standard_34']
a_resolvable 'yes, the identifiers are URLs that resolve to give information',
:text_as_statement => 'resolve because they are URLs',
:help_text => 'URLs are useful for both people and computers. People can put a URL into their browser and read more information, like <a href="http://opencorporates.com/companies/gb/08030289">companies</a> and <a href="http://data.ordnancesurvey.co.uk/doc/postcodeunit/EC2A4JE">postcodes</a>. Computers can also process this extra information using scripts to access the underlying data.',
:requirement => ['exemplar_15']
label_standard_34 'You should <strong>provide a service to resolve the identifiers you use</strong> so that people can find extra information about them.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_34'
dependency :rule => 'A and (B and C)'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '!=', :a_service
condition_C :q_resolvingIds, '!=', :a_resolvable
label_exemplar_15 'You should <strong>link to a web page of information about each of the things in your data</strong> so that people can easily find and share that information.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_15'
dependency :rule => 'A and (B)'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '!=', :a_resolvable
q_resolutionServiceURL 'Where is the service that is used to resolve the identifiers?',
:discussion_topic => :resolutionServiceURL,
:display_on_certificate => true,
:text_as_statement => 'The identifier resolution service is at',
:help_text => 'The resolution service should take an identifier as a query parameter and give back some information about the thing it identifies.'
dependency :rule => 'A and B'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '==', :a_service
a_1 'Identifier Resolution Service URL',
:string,
:input_type => :url,
:placeholder => 'Identifier Resolution Service URL',
:requirement => ['standard_35']
label_standard_35 'You should <strong>have a URL through which identifiers can be resolved</strong> so that more information about them can be found by a computer.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_35'
dependency :rule => 'A and B and C'
condition_A :q_identifiers, '==', :a_true
condition_B :q_resolvingIds, '==', :a_service
condition_C :q_resolutionServiceURL, '==', {:string_value => '', :answer_reference => '1'}
q_existingExternalUrls 'Is there third-party information about things in your data on the web?',
:discussion_topic => :existingExternalUrls,
:help_text => 'Sometimes other people outside your control provide URLs to the things your data is about. For example, your data might have postcodes in it that link to the Ordnance Survey website.',
:pick => :one,
:required => :exemplar
dependency :rule => 'A'
condition_A :q_identifiers, '==', :a_true
a_false 'no'
a_true 'yes'
q_reliableExternalUrls 'Is that third-party information reliable?',
:discussion_topic => :reliableExternalUrls,
:help_text => 'If a third-party provides public URLs about things in your data, they probably take steps to ensure data quality and reliability. This is a measure of how much you trust their processes to do that. Look for their open data certificate or similar hallmarks to help make your decision.',
:pick => :one,
:required => :exemplar
dependency :rule => 'A and B'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
a_false 'no'
a_true 'yes'
q_externalUrls 'Does your data use those third-party URLs?',
:discussion_topic => :externalUrls,
:display_on_certificate => true,
:text_as_statement => 'Third-party URLs are',
:help_text => 'You should use third-party URLs that resolve to information about the things your data describes. This reduces duplication and helps people combine data from different sources to make it more useful.',
:pick => :one
dependency :rule => 'A and B and C'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
condition_C :q_reliableExternalUrls, '==', :a_true
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'referenced in this data',
:requirement => ['exemplar_16']
label_exemplar_16 'You should <strong>use URLs to third-party information in your data</strong> so that it\'s easy to combine with other data that uses those URLs.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_16'
dependency :rule => 'A and B and C and D'
condition_A :q_identifiers, '==', :a_true
condition_B :q_existingExternalUrls, '==', :a_true
condition_C :q_reliableExternalUrls, '==', :a_true
condition_D :q_externalUrls, '==', :a_false
label_group_13 'Trust',
:help_text => 'how much trust people can put in your data',
:customer_renderer => '/partials/fieldset'
q_provenance 'Do you provide machine-readable provenance for your data?',
:discussion_topic => :provenance,
:display_on_certificate => true,
:text_as_statement => 'The provenance of this data is',
:help_text => 'This about the origins of how your data was created and processed before it was published. It builds trust in the data you publish because people can trace back how it has been handled.',
:help_text_more_url => 'http://www.w3.org/TR/prov-primer/',
:pick => :one
a_false 'no',
:text_as_statement => ''
a_true 'yes',
:text_as_statement => 'machine-readable',
:requirement => ['exemplar_17']
label_exemplar_17 'You should <strong>provide a machine-readable provenance trail</strong> about your data so that people can trace how it was processed.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_17'
dependency :rule => 'A'
condition_A :q_provenance, '==', :a_false
q_digitalCertificate 'Where do you describe how people can verify that data they receive comes from you?',
:discussion_topic => :digitalCertificate,
:display_on_certificate => true,
:text_as_statement => 'This data can be verified using',
:help_text => 'If you deliver important data to people they should be able to check that what they receive is the same as what you published. For example, you can digitally sign the data you publish, so people can tell if it has been tampered with.'
a_1 'Verification Process URL',
:string,
:input_type => :url,
:placeholder => 'Verification Process URL',
:requirement => ['exemplar_18']
label_exemplar_18 'You should <strong>describe how people can check that the data they receive is the same as what you published</strong> so that they can trust it.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_18'
dependency :rule => 'A'
condition_A :q_digitalCertificate, '==', {:string_value => '', :answer_reference => '1'}
end
section_social 'Social Information',
:description => 'Documentation, support and services' do
label_group_15 'Documentation',
:help_text => 'how you help people understand the context and content of your data',
:customer_renderer => '/partials/fieldset'
q_documentationMetadata 'Does your data documentation include machine-readable data for:',
:discussion_topic => :documentationMetadata,
:display_on_certificate => true,
:text_as_statement => 'The documentation includes machine-readable data for',
:pick => :any
dependency :rule => 'A'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
a_title 'title',
:text_as_statement => 'title',
:requirement => ['standard_36']
a_description 'description',
:text_as_statement => 'description',
:requirement => ['standard_37']
a_issued 'release date',
:text_as_statement => 'release date',
:requirement => ['standard_38']
a_modified 'modification date',
:text_as_statement => 'modification date',
:requirement => ['standard_39']
a_accrualPeriodicity 'frequency of releases',
:text_as_statement => 'release frequency',
:requirement => ['standard_40']
a_identifier 'identifier',
:text_as_statement => 'identifier',
:requirement => ['standard_41']
a_landingPage 'landing page',
:text_as_statement => 'landing page',
:requirement => ['standard_42']
a_language 'language',
:text_as_statement => 'language',
:requirement => ['standard_43']
a_publisher 'publisher',
:text_as_statement => 'publisher',
:requirement => ['standard_44']
a_spatial 'spatial/geographical coverage',
:text_as_statement => 'spatial/geographical coverage',
:requirement => ['standard_45']
a_temporal 'temporal coverage',
:text_as_statement => 'temporal coverage',
:requirement => ['standard_46']
a_theme 'theme(s)',
:text_as_statement => 'theme(s)',
:requirement => ['standard_47']
a_keyword 'keyword(s) or tag(s)',
:text_as_statement => 'keyword(s) or tag(s)',
:requirement => ['standard_48']
a_distribution 'distribution(s)',
:text_as_statement => 'distribution(s)'
label_standard_36 'You should <strong>include a machine-readable data title in your documentation</strong> so that people know how to refer to it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_36'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_title
label_standard_37 'You should <strong>include a machine-readable data description in your documentation</strong> so that people know what it contains.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_37'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_description
label_standard_38 'You should <strong>include a machine-readable data release date in your documentation</strong> so that people know how timely it is.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_38'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_issued
label_standard_39 'You should <strong>include a machine-readable last modification date in your documentation</strong> so that people know they have the latest data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_39'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_modified
label_standard_40 'You should <strong>provide machine-readable metadata about how frequently you release new versions of your data</strong> so people know how often you update it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_40'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_accrualPeriodicity
label_standard_41 'You should <strong>include a canonical URL for the data in your machine-readable documentation</strong> so that people know how to access it consistently.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_41'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_identifier
label_standard_42 'You should <strong>include a canonical URL to the machine-readable documentation itself</strong> so that people know how to access to it consistently.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_42'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_landingPage
label_standard_43 'You should <strong>include the data language in your machine-readable documentation</strong> so that people who search for it will know whether they can understand it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_43'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_language
label_standard_44 'You should <strong>indicate the data publisher in your machine-readable documentation</strong> so people can decide how much to trust your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_44'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_publisher
label_standard_45 'You should <strong>include the geographic coverage in your machine-readable documentation</strong> so that people understand where your data applies to.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_45'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_spatial
label_standard_46 'You should <strong>include the time period in your machine-readable documentation</strong> so that people understand when your data applies to.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_46'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_temporal
label_standard_47 'You should <strong>include the subject in your machine-readable documentation</strong> so that people know roughly what your data is about.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_47'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_theme
label_standard_48 'You should <strong>include machine-readable keywords or tags in your documentation</strong> to help people search within the data effectively.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_48'
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '!=', :a_keyword
q_distributionMetadata 'Does your documentation include machine-readable metadata for each distribution on:',
:discussion_topic => :distributionMetadata,
:display_on_certificate => true,
:text_as_statement => 'The documentation about each distribution includes machine-readable data for',
:pick => :any
dependency :rule => 'A and B'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
a_title 'title',
:text_as_statement => 'title',
:requirement => ['standard_49']
a_description 'description',
:text_as_statement => 'description',
:requirement => ['standard_50']
a_issued 'release date',
:text_as_statement => 'release date',
:requirement => ['standard_51']
a_modified 'modification date',
:text_as_statement => 'modification date',
:requirement => ['standard_52']
a_rights 'rights statement',
:text_as_statement => 'rights statement',
:requirement => ['standard_53']
a_accessURL 'URL to access the data',
:text_as_statement => 'a URL to access the data',
:help_text => 'This metadata should be used when your data isn\'t available as a download, like an API for example.'
a_downloadURL 'URL to download the dataset',
:text_as_statement => 'a URL to download the dataset'
a_byteSize 'size in bytes',
:text_as_statement => 'size in bytes'
a_mediaType 'type of download media',
:text_as_statement => 'type of download media'
label_standard_49 'You should <strong>include machine-readable titles within your documentation</strong> so people know how to refer to each data distribution.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_49'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_title
label_standard_50 'You should <strong>include machine-readable descriptions within your documentation</strong> so people know what each data distribution contains.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_50'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_description
label_standard_51 'You should <strong>include machine-readable release dates within your documentation</strong> so people know how current each distribution is.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_51'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_issued
label_standard_52 'You should <strong>include machine-readable last modification dates within your documentation</strong> so people know whether their copy of a data distribution is up-to-date.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_52'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_modified
label_standard_53 'You should <strong>include a machine-readable link to the applicable rights statement</strong> so people can find out what they can do with a data distribution.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_53'
dependency :rule => 'A and B and C'
condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'}
condition_B :q_documentationMetadata, '==', :a_distribution
condition_C :q_distributionMetadata, '!=', :a_rights
q_technicalDocumentation 'Where is the technical documentation for the data?',
:discussion_topic => :technicalDocumentation,
:display_on_certificate => true,
:text_as_statement => 'The technical documentation for the data is at'
a_1 'Technical Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Technical Documentation URL',
:requirement => ['pilot_19']
label_pilot_19 'You should <strong>provide technical documentation for the data</strong> so that people understand how to use it.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_19'
dependency :rule => 'A'
condition_A :q_technicalDocumentation, '==', {:string_value => '', :answer_reference => '1'}
q_vocabulary 'Do the data formats use vocabularies or schemas?',
:discussion_topic => :vocabulary,
:help_text => 'Formats like CSV, JSON, XML or Turtle use custom vocabularies or schemas which say what columns or properties the data contains.',
:pick => :one,
:required => :standard
a_false 'no'
a_true 'yes'
q_schemaDocumentationUrl 'Where is documentation about your data vocabularies?',
:discussion_topic => :schemaDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The vocabularies used by this data are documented at'
dependency :rule => 'A'
condition_A :q_vocabulary, '==', :a_true
a_1 'Schema Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Schema Documentation URL',
:requirement => ['standard_54']
label_standard_54 'You should <strong>document any vocabulary you use within your data</strong> so that people know how to interpret it.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_54'
dependency :rule => 'A and B'
condition_A :q_vocabulary, '==', :a_true
condition_B :q_schemaDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
q_codelists 'Are there any codes used in this data?',
:discussion_topic => :codelists,
:help_text => 'If your data uses codes to refer to things like geographical areas, spending categories or diseases for example, these need to be explained to people.',
:pick => :one,
:required => :standard
a_false 'no'
a_true 'yes'
q_codelistDocumentationUrl 'Where are any codes in your data documented?',
:discussion_topic => :codelistDocumentationUrl,
:display_on_certificate => true,
:text_as_statement => 'The codes in this data are documented at'
dependency :rule => 'A'
condition_A :q_codelists, '==', :a_true
a_1 'Codelist Documentation URL',
:string,
:input_type => :url,
:placeholder => 'Codelist Documentation URL',
:requirement => ['standard_55']
label_standard_55 'You should <strong>document the codes used within your data</strong> so that people know how to interpret them.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_55'
dependency :rule => 'A and B'
condition_A :q_codelists, '==', :a_true
condition_B :q_codelistDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'}
label_group_16 'Support',
:help_text => 'how you communicate with people who use your data',
:customer_renderer => '/partials/fieldset'
q_contactUrl 'Where can people find out how to contact someone with questions about this data?',
:discussion_topic => :contactUrl,
:display_on_certificate => true,
:text_as_statement => 'Find out how to contact someone about this data at',
:help_text => 'Give a URL for a page that describes how people can contact someone if they have questions about the data.'
a_1 'Contact Documentation',
:string,
:input_type => :url,
:placeholder => 'Contact Documentation',
:requirement => ['pilot_20']
label_pilot_20 'You should <strong>provide contact information for people to send questions</strong> about your data to.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_20'
dependency :rule => 'A'
condition_A :q_contactUrl, '==', {:string_value => '', :answer_reference => '1'}
q_improvementsContact 'Where can people find out how to improve the way your data is published?',
:discussion_topic => :improvementsContact,
:display_on_certificate => true,
:text_as_statement => 'Find out how to suggest improvements to publication at'
a_1 'Improvement Suggestions URL',
:string,
:input_type => :url,
:placeholder => 'Improvement Suggestions URL',
:requirement => ['pilot_21']
label_pilot_21 'You should <strong>provide instructions about how suggest improvements</strong> to the way you publish data so you can discover what people need.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_21'
dependency :rule => 'A'
condition_A :q_improvementsContact, '==', {:string_value => '', :answer_reference => '1'}
q_dataProtectionUrl 'Where can people find out how to contact someone with questions about privacy?',
:discussion_topic => :dataProtectionUrl,
:display_on_certificate => true,
:text_as_statement => 'Find out where to send questions about privacy at'
a_1 'Confidentiality Contact Documentation',
:string,
:input_type => :url,
:placeholder => 'Confidentiality Contact Documentation',
:requirement => ['pilot_22']
label_pilot_22 'You should <strong>provide contact information for people to send questions about privacy</strong> and disclosure of personal details to.',
:custom_renderer => '/partials/requirement_pilot',
:requirement => 'pilot_22'
dependency :rule => 'A'
condition_A :q_dataProtectionUrl, '==', {:string_value => '', :answer_reference => '1'}
q_socialMedia 'Do you use social media to connect with people who use your data?',
:discussion_topic => :socialMedia,
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['standard_56']
label_standard_56 'You should <strong>use social media to reach people who use your data</strong> and discover how your data is being used',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_56'
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_false
repeater 'Account' do
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_true
q_account 'Which social media accounts can people reach you on?',
:discussion_topic => :account,
:display_on_certificate => true,
:text_as_statement => 'Contact the curator through these social media accounts',
:help_text => 'Give URLs to your social media accounts, like your Twitter or Facebook profile page.',
:required => :required
dependency :rule => 'A'
condition_A :q_socialMedia, '==', :a_true
a_1 'Social Media URL',
:string,
:input_type => :url,
:required => :required,
:placeholder => 'Social Media URL'
end
q_forum 'Where should people discuss this dataset?',
:discussion_topic => :forum,
:display_on_certificate => true,
:text_as_statement => 'Discuss this data at',
:help_text => 'Give a URL to your forum or mailing list where people can talk about your data.'
a_1 'Forum or Mailing List URL',
:string,
:input_type => :url,
:placeholder => 'Forum or Mailing List URL',
:requirement => ['standard_57']
label_standard_57 'You should <strong>tell people where they can discuss your data</strong> and support one another.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_57'
dependency :rule => 'A'
condition_A :q_forum, '==', {:string_value => '', :answer_reference => '1'}
q_correctionReporting 'Where can people find out how to request corrections to your data?',
:discussion_topic => :correctionReporting,
:display_on_certificate => true,
:text_as_statement => 'Find out how to request data corrections at',
:help_text => 'Give a URL where people can report errors they spot in your data.'
dependency :rule => 'A'
condition_A :q_corrected, '==', :a_true
a_1 'Correction Instructions URL',
:string,
:input_type => :url,
:placeholder => 'Correction Instructions URL',
:requirement => ['standard_58']
label_standard_58 'You should <strong>provide instructions about how people can report errors</strong> in your data.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_58'
dependency :rule => 'A and B'
condition_A :q_corrected, '==', :a_true
condition_B :q_correctionReporting, '==', {:string_value => '', :answer_reference => '1'}
q_correctionDiscovery 'Where can people find out how to get notifications of corrections to your data?',
:discussion_topic => :correctionDiscovery,
:display_on_certificate => true,
:text_as_statement => 'Find out how to get notifications about data corrections at',
:help_text => 'Give a URL where you describe how notifications about corrections are shared with people.'
dependency :rule => 'A'
condition_A :q_corrected, '==', :a_true
a_1 'Correction Notification URL',
:string,
:input_type => :url,
:placeholder => 'Correction Notification URL',
:requirement => ['standard_59']
label_standard_59 'You should <strong>provide a mailing list or feed with updates</strong> that people can use to keep their copies of your data up-to-date.',
:custom_renderer => '/partials/requirement_standard',
:requirement => 'standard_59'
dependency :rule => 'A and B'
condition_A :q_corrected, '==', :a_true
condition_B :q_correctionDiscovery, '==', {:string_value => '', :answer_reference => '1'}
q_engagementTeam 'Do you have anyone who actively builds a community around this data?',
:discussion_topic => :engagementTeam,
:help_text => 'A community engagement team will engage through social media, blogging, and arrange hackdays or competitions to encourage people to use the data.',
:help_text_more_url => 'http://theodi.org/guide/engaging-reusers',
:pick => :one
a_false 'no'
a_true 'yes',
:requirement => ['exemplar_19']
label_exemplar_19 'You should <strong>build a community of people around your data</strong> to encourage wider use of your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_19'
dependency :rule => 'A'
condition_A :q_engagementTeam, '==', :a_false
q_engagementTeamUrl 'Where is their home page?',
:discussion_topic => :engagementTeamUrl,
:display_on_certificate => true,
:text_as_statement => 'Community engagement is done by',
:required => :required
dependency :rule => 'A'
condition_A :q_engagementTeam, '==', :a_true
a_1 'Community Engagement Team Home Page URL',
:string,
:input_type => :url,
:placeholder => 'Community Engagement Team Home Page URL',
:required => :required
label_group_17 'Services',
:help_text => 'how you give people access to tools they need to work with your data',
:customer_renderer => '/partials/fieldset'
q_libraries 'Where do you list tools to work with your data?',
:discussion_topic => :libraries,
:display_on_certificate => true,
:text_as_statement => 'Tools to help use this data are listed at',
:help_text => 'Give a URL that lists the tools you know or recommend people can use when they work with your data.'
a_1 'Tool URL',
:string,
:input_type => :url,
:placeholder => 'Tool URL',
:requirement => ['exemplar_20']
label_exemplar_20 'You should <strong>provide a list of software libraries and other readily-available tools</strong> so that people can quickly get to work with your data.',
:custom_renderer => '/partials/requirement_exemplar',
:requirement => 'exemplar_20'
dependency :rule => 'A'
condition_A :q_libraries, '==', {:string_value => '', :answer_reference => '1'}
end
end
| {
"content_hash": "4583cecb790224780aeeffbc075ae146",
"timestamp": "",
"source": "github",
"line_count": 2577,
"max_line_length": 729,
"avg_line_length": 54.47652308886302,
"alnum_prop": 0.6664767142022708,
"repo_name": "Motejl/open-data-certificate",
"id": "a722a138b831abfa85f4decd8b9b4f0677a58007",
"size": "140404",
"binary": false,
"copies": "5",
"ref": "refs/heads/staging",
"path": "surveys/generated/surveyor/odc_questionnaire.GL.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "127178"
},
{
"name": "Cucumber",
"bytes": "15259"
},
{
"name": "HTML",
"bytes": "199882"
},
{
"name": "JavaScript",
"bytes": "49604"
},
{
"name": "Ruby",
"bytes": "35781920"
},
{
"name": "Shell",
"bytes": "392"
},
{
"name": "XSLT",
"bytes": "82457"
}
],
"symlink_target": ""
} |
import { SerializedError, onUnexpectedError } from 'vs/base/common/errors';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { MainContext, MainThreadErrorsShape } from 'vs/workbench/api/common/extHost.protocol';
@extHostNamedCustomer(MainContext.MainThreadErrors)
export class MainThreadErrors implements MainThreadErrorsShape {
dispose(): void {
//
}
$onUnexpectedError(err: any | SerializedError): void {
if (err && err.$isError) {
const { name, message, stack } = err;
err = new Error();
err.message = message;
err.name = name;
err.stack = stack;
}
onUnexpectedError(err);
}
}
| {
"content_hash": "d629152585d15d02724b814b8c453fb6",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 94,
"avg_line_length": 27.166666666666668,
"alnum_prop": 0.7239263803680982,
"repo_name": "Microsoft/vscode",
"id": "9ccf414c1f492ab1709cf14b74c45851281bf56f",
"size": "1003",
"binary": false,
"copies": "6",
"ref": "refs/heads/ben/status-hover-fixes",
"path": "src/vs/workbench/api/browser/mainThreadErrors.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": "492430"
},
{
"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": "21066876"
},
{
"name": "Visual Basic",
"bytes": "893"
}
],
"symlink_target": ""
} |
package frame.interceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.token.TokenManager;
/**
* ้ฒๆญข่กจๅ้ๅคๆไบค
*
* @author hadong
*
* ๅจ่ทณ่ฝฌๅฐviewไนๅ,็ๆtoken
*
* TokenManager.createToken("jockillerToken", 30*60);
*
* ๅจ้กต้ขไธญๅ ๅ
ฅ้่ๅ
*
* <input type="hidden" name="jockillerToken" value="${jockillerToken}"/>
*
* ๅจformๆก็actionๆนๆณไธ้ขๅ ไธ
*
* Before(value = {TokenInterceptor.class })
*/
public class TokenInterceptor implements Interceptor {
public void intercept(Invocation inv) {
boolean token = TokenManager.validateToken(inv.getController(), "jockillerToken");
if (!token) {
inv.getController().renderText("่ฏทไธ่ฆ้ๅคๆไบค");
return;
}
inv.invoke();
}
}
| {
"content_hash": "863771f81f02925980adb70f919cbf70",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 84,
"avg_line_length": 23.38235294117647,
"alnum_prop": 0.6339622641509434,
"repo_name": "dhso/0513syr",
"id": "2baa0f26712c45c4901b1905c23bb2ba75021475",
"size": "877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/frame/interceptor/TokenInterceptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "839790"
},
{
"name": "HTML",
"bytes": "29983"
},
{
"name": "Java",
"bytes": "117960"
},
{
"name": "JavaScript",
"bytes": "677198"
}
],
"symlink_target": ""
} |
package org.onosproject.cpman.rest;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.junit.Test;
import org.onlab.metrics.MetricsComponent;
import org.onlab.metrics.MetricsFeature;
import org.onlab.metrics.MetricsReporter;
import org.onlab.metrics.MetricsService;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onlab.rest.BaseResource;
import org.onosproject.cpman.ControlPlaneMonitorService;
import org.onosproject.cpman.SystemInfo;
import org.onosproject.cpman.impl.SystemInfoFactory;
import org.onosproject.net.DeviceId;
import org.onosproject.rest.resources.ResourceTest;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import static org.easymock.EasyMock.anyInt;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* Unit test for ControlMetricsCollector.
*/
public class ControlMetricsCollectorResourceTest extends ResourceTest {
final ControlPlaneMonitorService mockControlPlaneMonitorService =
createMock(ControlPlaneMonitorService.class);
final MetricsService mockMetricsService = new MockMetricsService();
private static final String PREFIX = "collector";
/**
* Constructs a control metrics collector resource test instance.
*/
public ControlMetricsCollectorResourceTest() {
super(ResourceConfig.forApplicationClass(CPManWebApplication.class));
}
/**
* Sets up the global values for all the tests.
*/
@Before
public void setUpTest() {
ServiceDirectory testDirectory =
new TestServiceDirectory()
.add(ControlPlaneMonitorService.class, mockControlPlaneMonitorService)
.add(MetricsService.class, mockMetricsService);
BaseResource.setServiceDirectory(testDirectory);
}
/**
* Tests CPU metrics POST through REST API.
*/
@Test
public void testCpuMetricsPost() {
mockControlPlaneMonitorService.updateMetric(anyObject(), anyInt(),
(Optional<DeviceId>) anyObject());
expectLastCall().times(5);
replay(mockControlPlaneMonitorService);
basePostTest("cpu-metrics-post.json", PREFIX + "/cpu_metrics");
}
/**
* Tests memory metrics POST through REST API.
*/
@Test
public void testMemoryMetricsPost() {
mockControlPlaneMonitorService.updateMetric(anyObject(), anyInt(),
(Optional<DeviceId>) anyObject());
expectLastCall().times(4);
replay(mockControlPlaneMonitorService);
basePostTest("memory-metrics-post.json", PREFIX + "/memory_metrics");
}
/**
* Tests disk metrics POST through REST API.
*/
@Test
public void testDiskMetrics() {
mockControlPlaneMonitorService.updateMetric(anyObject(), anyInt(), anyString());
expectLastCall().times(4);
replay(mockControlPlaneMonitorService);
basePostTest("disk-metrics-post.json", PREFIX + "/disk_metrics");
}
/**
* Tests network metrics POST through REST API.
*/
@Test
public void testNetworkMetrics() {
mockControlPlaneMonitorService.updateMetric(anyObject(), anyInt(), anyString());
expectLastCall().times(8);
replay(mockControlPlaneMonitorService);
basePostTest("network-metrics-post.json", PREFIX + "/network_metrics");
}
@Test
public void testSystemInfoPost() {
basePostTest("system-info-post.json", PREFIX + "/system_info");
SystemInfo si = SystemInfoFactory.getInstance().getSystemInfo();
assertThat(si.cpuSpeed(), is(2048));
assertThat(si.coreCount(), is(6));
assertThat(si.cpuCount(), is(2));
assertThat(si.totalMemory(), is(4096));
}
private Response baseTest(String jsonFile, String path) {
final WebTarget wt = target();
InputStream jsonStream = ControlMetricsCollectorResourceTest.class
.getResourceAsStream(jsonFile);
assertThat(jsonStream, notNullValue());
return wt.path(path)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
}
private void basePostTest(String jsonFile, String path) {
Response response = baseTest(jsonFile, path);
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));
}
private class MockMetricsService implements MetricsService {
@Override
public MetricsComponent registerComponent(String name) {
MetricsComponent metricsComponent = new MetricsComponent(name);
return metricsComponent;
}
@Override
public MetricRegistry getMetricRegistry() {
return null;
}
@Override
public Counter createCounter(MetricsComponent component, MetricsFeature feature,
String metricName) {
return null;
}
@Override
public Histogram createHistogram(MetricsComponent component,
MetricsFeature feature, String metricName) {
return null;
}
@Override
public Timer createTimer(MetricsComponent component,
MetricsFeature feature, String metricName) {
return null;
}
@Override
public Meter createMeter(MetricsComponent component,
MetricsFeature feature, String metricName) {
return new Meter();
}
@Override
public <T extends Metric> T registerMetric(MetricsComponent component,
MetricsFeature feature,
String metricName, T metric) {
return null;
}
@Override
public void registerReporter(MetricsReporter reporter) {
}
@Override
public void unregisterReporter(MetricsReporter reporter) {
}
@Override
public void notifyReporters() {
}
@Override
public boolean removeMetric(MetricsComponent component,
MetricsFeature feature, String metricName) {
return false;
}
@Override
public Map<String, Timer> getTimers(MetricFilter filter) {
return Collections.emptyMap();
}
@Override
public Map<String, Gauge> getGauges(MetricFilter filter) {
return Collections.emptyMap();
}
@Override
public Map<String, Counter> getCounters(MetricFilter filter) {
return Collections.emptyMap();
}
@Override
public Map<String, Meter> getMeters(MetricFilter filter) {
return Collections.emptyMap();
}
@Override
public Map<String, Histogram> getHistograms(MetricFilter filter) {
return Collections.emptyMap();
}
@Override
public Map<String, Metric> getMetrics() {
return Collections.emptyMap();
}
@Override
public void removeMatching(MetricFilter filter) {
}
}
}
| {
"content_hash": "06cab7d578f2e1dec9246136d475c012",
"timestamp": "",
"source": "github",
"line_count": 253,
"max_line_length": 94,
"avg_line_length": 32.10671936758893,
"alnum_prop": 0.6532069432475687,
"repo_name": "y-higuchi/onos",
"id": "fe89335d71d756e3cc9543b3a9297f9d7b2f1ed7",
"size": "8740",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "apps/cpman/app/src/test/java/org/onosproject/cpman/rest/ControlMetricsCollectorResourceTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "200975"
},
{
"name": "HTML",
"bytes": "110139"
},
{
"name": "Java",
"bytes": "28623718"
},
{
"name": "JavaScript",
"bytes": "3404316"
},
{
"name": "Protocol Buffer",
"bytes": "8451"
},
{
"name": "Python",
"bytes": "141941"
},
{
"name": "Shell",
"bytes": "843"
}
],
"symlink_target": ""
} |
"""
WSGI config for {{ project_name }} project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/wsgi/
"""
from __future__ import absolute_import, unicode_literals
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.dev")
application = get_wsgi_application()
| {
"content_hash": "82be1ebd3861d6689feab0b85eed4697",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 82,
"avg_line_length": 27.22222222222222,
"alnum_prop": 0.746938775510204,
"repo_name": "nilnvoid/wagtail",
"id": "f58f6b154cd83f53b14b37d743094191dec4e768",
"size": "490",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "wagtail/project_template/project_name/wsgi.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "172932"
},
{
"name": "HTML",
"bytes": "291232"
},
{
"name": "JavaScript",
"bytes": "116614"
},
{
"name": "Makefile",
"bytes": "548"
},
{
"name": "Python",
"bytes": "2253627"
},
{
"name": "Shell",
"bytes": "7387"
}
],
"symlink_target": ""
} |
package org.springframework.boot.test.mock.mockito.example;
import java.security.Provider.Service;
/**
* Example bean for mocking tests that calls {@link Service}.
*
* @author Phillip Webb
*/
public class ExampleServiceCaller {
private final ExampleService service;
public ExampleServiceCaller(ExampleService service) {
this.service = service;
}
public ExampleService getService() {
return this.service;
}
public String sayGreeting() {
return "I say " + this.service.greeting();
}
}
| {
"content_hash": "edb3b0c1c2bed6382bd74274e0393a95",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 61,
"avg_line_length": 18.178571428571427,
"alnum_prop": 0.7367387033398821,
"repo_name": "lenicliu/spring-boot",
"id": "176fa3f5a822ce69176b5cfeabf0bafff9811e62",
"size": "1129",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleServiceCaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6954"
},
{
"name": "CSS",
"bytes": "5774"
},
{
"name": "FreeMarker",
"bytes": "2116"
},
{
"name": "Groovy",
"bytes": "39500"
},
{
"name": "HTML",
"bytes": "71567"
},
{
"name": "Java",
"bytes": "7577639"
},
{
"name": "JavaScript",
"bytes": "37789"
},
{
"name": "Ruby",
"bytes": "1305"
},
{
"name": "SQLPL",
"bytes": "20085"
},
{
"name": "Shell",
"bytes": "16416"
},
{
"name": "Smarty",
"bytes": "3276"
},
{
"name": "XSLT",
"bytes": "33894"
}
],
"symlink_target": ""
} |
var fs = require("fs");
module.exports = function(name) {
fs.mkdir(name, function(error) {
fs.mkdir(name + "/config", function(error) {
var copyTemplate = function(location) {
var read = fs.createReadStream(__dirname + '/templates/' + location);
var write = fs.createWriteStream(name + "/" + location);
read.pipe(write);
};
['config/application.js', 'config/routes.js'].forEach(copyTemplate);
fs.mkdir(name + "/config/initializers")
});
fs.mkdir(name + "/app", function(error) {
fs.mkdir(name + "/app/controllers");
fs.mkdir(name + "/app/views");
fs.mkdir(name + "/app/public");
});
});
}
| {
"content_hash": "1abf74ad6b70eebcab8ed01ee3f9010c",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 73,
"avg_line_length": 27.652173913043477,
"alnum_prop": 0.6242138364779874,
"repo_name": "penman/fluid",
"id": "1f5a29bf9d153992e916cbb325a54001fceeded3",
"size": "636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bin/generators/application/generator.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "12350"
}
],
"symlink_target": ""
} |
// Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for roles-and-actions-visualizer component.
*/
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormsModule } from '@angular/forms';
import { ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import { RolesAndActionsVisualizerComponent } from './roles-and-actions-visualizer.component';
import { UrlInterpolationService } from 'domain/utilities/url-interpolation.service';
import { MaterialModule } from 'modules/material.module';
import { AdminBackendApiService } from 'domain/admin/admin-backend-api.service';
describe('Roles and actions visualizer component', function() {
let component: RolesAndActionsVisualizerComponent;
let fixture: ComponentFixture<RolesAndActionsVisualizerComponent>;
let adminBackendApiService: AdminBackendApiService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
FormsModule,
MaterialModule
], declarations: [RolesAndActionsVisualizerComponent],
providers: [UrlInterpolationService],
}).compileComponents();
fixture = TestBed.createComponent(RolesAndActionsVisualizerComponent);
adminBackendApiService = TestBed.get(AdminBackendApiService);
component = fixture.componentInstance;
component.viewableRoles = ['MODERATOR', 'TRANSLATION_ADMIN'];
component.humanReadableRoles = {
MODERATOR: 'moderator',
FULL_USER: 'full user',
MOBILE_LEARNER: 'mobile learner'
};
component.roleToActions = {
MODERATOR: ['allowed action 1', 'allowed action 2'],
MOBILE_LEARNER: ['allowed action 3', 'allowed action 4'],
TRANSLATION_ADMIN: ['allowed action 5', 'allowed action 6'],
FULL_USER: ['allowed action 7', 'allowed action 8']
};
});
it('should intialize correct active role', function() {
component.ngOnInit();
expect(component.activeRole).toEqual('TRANSLATION_ADMIN');
});
it('should intialize roles with all the roles', function() {
component.ngOnInit();
expect(component.roles).toEqual(
['FULL_USER', 'MOBILE_LEARNER', 'MODERATOR', 'TRANSLATION_ADMIN']);
});
it('should intialize roleToReadableActions correctly', function() {
component.ngOnInit();
expect(component.roleToReadableActions).toEqual({
MODERATOR: ['Allowed action 1', 'Allowed action 2'],
MOBILE_LEARNER: ['Allowed action 3', 'Allowed action 4'],
TRANSLATION_ADMIN: ['Allowed action 5', 'Allowed action 6'],
FULL_USER: ['Allowed action 7', 'Allowed action 8']
});
});
it('should set active role correctly', function() {
component.ngOnInit();
component.activeRole = 'MOBILE_LEARNER';
component.activeTab = component.TAB_ASSIGNED_USERS;
component.setActiveRole('MODERATOR');
expect(component.activeRole).toEqual('MODERATOR');
expect(component.activeTab).toEqual(component.TAB_ACTIONS);
});
it('should update assignUsersToActiveRole when calling showAssignedUsers',
fakeAsync(() => {
spyOn(
adminBackendApiService, 'fetchUsersAssignedToRoleAsync').and.resolveTo({
usernames: ['userA', 'userB']
});
component.activeRole = 'MOBILE_LEARNER';
component.assignUsersToActiveRole = [];
component.showAssignedUsers();
tick();
expect(component.assignUsersToActiveRole).toEqual(['userA', 'userB']);
}));
});
| {
"content_hash": "cda362f9943ebfeab5e23da7fce551f5",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 94,
"avg_line_length": 37.361111111111114,
"alnum_prop": 0.7090458488228005,
"repo_name": "kevinlee12/oppia",
"id": "e3a5f2d5268d4bf859494ba24e9371249576bf27",
"size": "4035",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "core/templates/pages/admin-page/roles-tab/roles-and-actions-visualizer.component.spec.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "205771"
},
{
"name": "HTML",
"bytes": "1835761"
},
{
"name": "JavaScript",
"bytes": "1182599"
},
{
"name": "PEG.js",
"bytes": "71377"
},
{
"name": "Python",
"bytes": "13670639"
},
{
"name": "Shell",
"bytes": "2239"
},
{
"name": "TypeScript",
"bytes": "13024194"
}
],
"symlink_target": ""
} |
package org.apache.tinkerpop.gremlin.process.traversal.strategy.finalization;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.MatchStep;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public final class MatchAlgorithmStrategy extends AbstractTraversalStrategy<TraversalStrategy.FinalizationStrategy> implements TraversalStrategy.FinalizationStrategy {
private final Class<? extends MatchStep.MatchAlgorithm> matchAlgorithmClass;
private MatchAlgorithmStrategy(final Class<? extends MatchStep.MatchAlgorithm> matchAlgorithmClass) {
this.matchAlgorithmClass = matchAlgorithmClass;
}
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
for (final Step<?, ?> step : traversal.getSteps()) {
if (step instanceof MatchStep) {
((MatchStep) step).setMatchAlgorithm(this.matchAlgorithmClass);
}
}
}
public static Builder build() {
return new Builder();
}
@Override
public String toString() {
return StringFactory.traversalStrategyString(this);
}
public final static class Builder {
private Class<? extends MatchStep.MatchAlgorithm> matchAlgorithmClass = MatchStep.CountMatchAlgorithm.class;
private Builder() {
}
public Builder algorithm(final Class<? extends MatchStep.MatchAlgorithm> matchAlgorithmClass) {
this.matchAlgorithmClass = matchAlgorithmClass;
return this;
}
public MatchAlgorithmStrategy create() {
return new MatchAlgorithmStrategy(this.matchAlgorithmClass);
}
}
}
| {
"content_hash": "8ab19dd3bab21d777a0ffaf546cd4d14",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 167,
"avg_line_length": 35.31578947368421,
"alnum_prop": 0.7277694982613016,
"repo_name": "mike-tr-adamson/incubator-tinkerpop",
"id": "be3157574e267fcf9fa81c4c2c42dd59b408b0d3",
"size": "2818",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/finalization/MatchAlgorithmStrategy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4544"
},
{
"name": "Groovy",
"bytes": "382411"
},
{
"name": "Java",
"bytes": "6707824"
},
{
"name": "Python",
"bytes": "1481"
},
{
"name": "Shell",
"bytes": "32352"
}
],
"symlink_target": ""
} |
package org.quattor.pan.dml.data;
import java.io.ObjectStreamException;
import net.jcip.annotations.Immutable;
import org.quattor.pan.exceptions.EvaluationException;
/**
* Represents the undef value in the pan language.
*
* @author loomis
*
*/
@Immutable
public class Undef extends TransientElement {
public static final Undef VALUE = new Undef();
private Undef() {
}
public Object readResolve() throws ObjectStreamException {
return VALUE;
}
static public Undef getInstance() {
return VALUE;
}
@Override
public void checkValidReplacement(Element newValue)
throws EvaluationException {
// Anything can replace an undef value. This method doesn't need to do
// anything.
}
@Override
public String getTypeAsString() {
return "undef";
}
@Override
public int hashCode() {
return System.identityHashCode(VALUE);
}
@Override
public boolean equals(Object o) {
return (this == o);
}
@Override
public String toString() {
return "undef";
}
}
| {
"content_hash": "fcd5f031163da97f2ecf7eb3b4be533d",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 72,
"avg_line_length": 16.311475409836067,
"alnum_prop": 0.7195979899497488,
"repo_name": "quattor/pan",
"id": "ff6d7815cd1522399b1f0243dc6834358ac3aa0a",
"size": "1799",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "panc/src/main/java/org/quattor/pan/dml/data/Undef.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Clojure",
"bytes": "27791"
},
{
"name": "HTML",
"bytes": "17882"
},
{
"name": "Java",
"bytes": "1672415"
},
{
"name": "Pan",
"bytes": "26581489"
},
{
"name": "Perl",
"bytes": "25023"
},
{
"name": "PostScript",
"bytes": "59921"
},
{
"name": "Python",
"bytes": "52540"
},
{
"name": "Shell",
"bytes": "1513"
},
{
"name": "Vim script",
"bytes": "12427"
}
],
"symlink_target": ""
} |
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<h4 class="title_page"> Edit blog </h4>
<form action="<?php echo base_url('admin/blog/update')?>" id="form" enctype="multipart/form-data" method="post" class="form-horizontal">
<div class="panel-body">
<input type="hidden" value="<?php echo $blog->id ?>" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-2">Title</label>
<div class="col-md-10">
<input name="title" class="form-control" type="text"
value="<?php echo $blog->title ?>">
<span class="help-block"><?php echo form_error('title'); ?></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Date</label>
<div class="col-md-10">
<input name="date" class="datepicker form-control" type="text"
value="<?php echo $blog->date ?>">
<span class="help-block"><?php echo form_error('date'); ?></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Status</label>
<div class="col-md-10">
<select name="status" class="form-control" >
<option <?php if ($blog->status == "Draft") echo "selected"; ?> value="Draft">Draft</option>
<option <?php if ($blog->status == "Publish") echo "selected"; ?> value="Publish">Publish</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Image (319px x 250px)</label>
<div class="col-md-2">
<img src="<?php echo base_url($blog->img_url) ?>" class="img_thumb_edit"></i>
</div>
<div class="col-md-3">
<input type="file" name="image" size="20" />
<span class="help-block">
<?php
if ($image_error) {
echo $image_error; }
else {
echo form_error('image'); }
?>
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Content</label>
<div class="col-md-10">
<textarea name="content" id="content" class="form-control" type="text" rows="6"><?php echo $blog->content ?></textarea>
<span class="help-block"><?php echo form_error('content'); ?></span>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<button type="submit" id="btnSave" class="btn btn-info"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('.datepicker').datepicker({
autoclose: true,
format: "yyyy/mm/dd",
todayHighlight: true,
orientation: "top auto",
todayBtn: true,
todayHighlight: true,
});
</script>
</body>
</html>
| {
"content_hash": "8db369d62dd68f0733531bc3bcc3b6fe",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 159,
"avg_line_length": 54.077777777777776,
"alnum_prop": 0.3416889254160674,
"repo_name": "asariujang/CI_OZINDO",
"id": "d10dc7694ccb62a56ba01e794902a10fc6115030",
"size": "4867",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/admin/blog_view_edit.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "70499"
},
{
"name": "HTML",
"bytes": "9803"
},
{
"name": "Hack",
"bytes": "10911"
},
{
"name": "JavaScript",
"bytes": "18253"
},
{
"name": "PHP",
"bytes": "4300748"
}
],
"symlink_target": ""
} |
#include "SDL_config.h"
/* Output raw audio data to a file. */
#if HAVE_STDIO_H
#include <stdio.h>
#endif
#include "SDL_rwops.h"
#include "SDL_timer.h"
#include "SDL_audio.h"
#include "../SDL_audiomem.h"
#include "../SDL_audio_c.h"
#include "../SDL_audiodev_c.h"
#include "SDL_diskaudio.h"
/* The tag name used by DISK audio */
#define DISKAUD_DRIVER_NAME "disk"
/* environment variables and defaults. */
#define DISKENVR_OUTFILE "SDL_DISKAUDIOFILE"
#define DISKDEFAULT_OUTFILE "sdlaudio.raw"
#define DISKENVR_WRITEDELAY "SDL_DISKAUDIODELAY"
#define DISKDEFAULT_WRITEDELAY 150
/* Audio driver functions */
static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec);
static void DISKAUD_WaitAudio(_THIS);
static void DISKAUD_PlayAudio(_THIS);
static Uint8 *DISKAUD_GetAudioBuf(_THIS);
static void DISKAUD_CloseAudio(_THIS);
static const char *DISKAUD_GetOutputFilename(void)
{
const char *envr = SDL_getenv(DISKENVR_OUTFILE);
return((envr != NULL) ? envr : DISKDEFAULT_OUTFILE);
}
/* Audio driver bootstrap functions */
static int DISKAUD_Available(void)
{
const char *envr = SDL_getenv("SDL_AUDIODRIVER");
if (envr && (SDL_strcmp(envr, DISKAUD_DRIVER_NAME) == 0)) {
return(1);
}
return(0);
}
static void DISKAUD_DeleteDevice(SDL_AudioDevice *device)
{
SDL_free(device->hidden);
SDL_free(device);
}
static SDL_AudioDevice *DISKAUD_CreateDevice(int devindex)
{
SDL_AudioDevice *this;
const char *envr;
/* Initialize all variables that we clean on shutdown */
this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
if ( this ) {
SDL_memset(this, 0, (sizeof *this));
this->hidden = (struct SDL_PrivateAudioData *)
SDL_malloc((sizeof *this->hidden));
}
if ( (this == NULL) || (this->hidden == NULL) ) {
SDL_OutOfMemory();
if ( this ) {
SDL_free(this);
}
return(0);
}
SDL_memset(this->hidden, 0, (sizeof *this->hidden));
envr = SDL_getenv(DISKENVR_WRITEDELAY);
this->hidden->write_delay = (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;
/* Set the function pointers */
this->OpenAudio = DISKAUD_OpenAudio;
this->WaitAudio = DISKAUD_WaitAudio;
this->PlayAudio = DISKAUD_PlayAudio;
this->GetAudioBuf = DISKAUD_GetAudioBuf;
this->CloseAudio = DISKAUD_CloseAudio;
this->free = DISKAUD_DeleteDevice;
return this;
}
AudioBootStrap DISKAUD_bootstrap = {
DISKAUD_DRIVER_NAME, "direct-to-disk audio",
DISKAUD_Available, DISKAUD_CreateDevice
};
/* This function waits until it is possible to write a full sound buffer */
static void DISKAUD_WaitAudio(_THIS)
{
SDL_Delay(this->hidden->write_delay);
}
static void DISKAUD_PlayAudio(_THIS)
{
int written;
/* Write the audio data */
written = SDL_RWwrite(this->hidden->output,
this->hidden->mixbuf, 1,
this->hidden->mixlen);
/* If we couldn't write, assume fatal error for now */
if ( (Uint32)written != this->hidden->mixlen ) {
this->enabled = 0;
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Wrote %d bytes of audio data\n", written);
#endif
}
static Uint8 *DISKAUD_GetAudioBuf(_THIS)
{
return(this->hidden->mixbuf);
}
static void DISKAUD_CloseAudio(_THIS)
{
if ( this->hidden->mixbuf != NULL ) {
SDL_FreeAudioMem(this->hidden->mixbuf);
this->hidden->mixbuf = NULL;
}
if ( this->hidden->output != NULL ) {
SDL_RWclose(this->hidden->output);
this->hidden->output = NULL;
}
}
static int DISKAUD_OpenAudio(_THIS, SDL_AudioSpec *spec)
{
const char *fname = DISKAUD_GetOutputFilename();
/* Open the audio device */
this->hidden->output = SDL_RWFromFile(fname, "wb");
if ( this->hidden->output == NULL ) {
return(-1);
}
#if HAVE_STDIO_H
fprintf(stderr, "WARNING: You are using the SDL disk writer"
" audio driver!\n Writing to file [%s].\n", fname);
#endif
/* Allocate mixing buffer */
this->hidden->mixlen = spec->size;
this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
if ( this->hidden->mixbuf == NULL ) {
return(-1);
}
SDL_memset(this->hidden->mixbuf, spec->silence, spec->size);
/* We're ready to rock and roll. :-) */
return(0);
}
| {
"content_hash": "306ed6338540906c945a43305eb9ee2f",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 78,
"avg_line_length": 26.01829268292683,
"alnum_prop": 0.6510428872744317,
"repo_name": "balaam/dinodeck",
"id": "61e1652d53a2adad3dccb6d68c8284489b24396e",
"size": "5219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/sdl/src/audio/disk/SDL_diskaudio.c",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "38019"
},
{
"name": "Awk",
"bytes": "7930"
},
{
"name": "Batchfile",
"bytes": "11732"
},
{
"name": "C",
"bytes": "27785076"
},
{
"name": "C#",
"bytes": "163468"
},
{
"name": "C++",
"bytes": "6025450"
},
{
"name": "CMake",
"bytes": "1788859"
},
{
"name": "CSS",
"bytes": "9968"
},
{
"name": "DIGITAL Command Language",
"bytes": "35819"
},
{
"name": "Fortran",
"bytes": "1652"
},
{
"name": "HTML",
"bytes": "3549224"
},
{
"name": "Java",
"bytes": "124214"
},
{
"name": "JavaScript",
"bytes": "2980"
},
{
"name": "Lua",
"bytes": "332150"
},
{
"name": "M4",
"bytes": "101303"
},
{
"name": "Makefile",
"bytes": "2561291"
},
{
"name": "Objective-C",
"bytes": "294879"
},
{
"name": "Perl",
"bytes": "24942"
},
{
"name": "Python",
"bytes": "349168"
},
{
"name": "R",
"bytes": "5609"
},
{
"name": "Roff",
"bytes": "5189346"
},
{
"name": "Ruby",
"bytes": "11253"
},
{
"name": "Shell",
"bytes": "2525184"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Debug\EventDispatcherTraceableInterface;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* EventDataCollector.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class EventDataCollector extends DataCollector
{
protected $dispatcher;
public function setEventDispatcher(EventDispatcher $dispatcher)
{
if ($dispatcher instanceof EventDispatcherTraceableInterface) {
$this->dispatcher = $dispatcher;
}
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = array(
'called_listeners' => null !== $this->dispatcher ? $this->dispatcher->getCalledListeners() : array(),
'not_called_listeners' => null !== $this->dispatcher ? $this->dispatcher->getNotCalledListeners() : array(),
);
}
/**
* Gets the called listeners.
*
* @return array An array of called listeners
*
* @see EventDispatcherTraceableInterface
*/
public function getCalledListeners()
{
return $this->data['called_listeners'];
}
/**
* Gets the not called listeners.
*
* @return array An array of not called listeners
*
* @see EventDispatcherTraceableInterface
*/
public function getNotCalledListeners()
{
return $this->data['not_called_listeners'];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'events';
}
}
| {
"content_hash": "f553a93a33fb0f1c4608b2d1823873c0",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 120,
"avg_line_length": 25.675324675324674,
"alnum_prop": 0.6525037936267072,
"repo_name": "ShinichiU/mySymfony2study",
"id": "ba07ff83095c1e0b3c77806fcdf045a2b70cfd0a",
"size": "1977",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/EventDataCollector.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "32853"
},
{
"name": "Shell",
"bytes": "632"
}
],
"symlink_target": ""
} |
package authorizationsync
import (
"fmt"
"strings"
"testing"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
clienttesting "k8s.io/client-go/testing"
"k8s.io/client-go/tools/cache"
"k8s.io/kubernetes/pkg/apis/rbac"
"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
rbaclister "k8s.io/kubernetes/pkg/client/listers/rbac/internalversion"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
originlister "github.com/openshift/origin/pkg/authorization/generated/listers/authorization/internalversion"
)
func TestSyncRole(t *testing.T) {
tests := []struct {
name string
key string
startingRBAC []*rbac.Role
startingOrigin []*authorizationapi.Role
reactions map[reactionMatch]clienttesting.ReactionFunc
actionCheck func([]clienttesting.Action) error
expectedError string
}{
{
name: "no action on missing both",
key: "foo/resource-01",
actionCheck: func(actions []clienttesting.Action) error {
if len(actions) != 0 {
return fmt.Errorf("expected %v, got %v", 0, actions)
}
return nil
},
},
{
name: "simple create",
key: "foo/resource-01",
startingOrigin: []*authorizationapi.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
actionCheck: func(actions []clienttesting.Action) error {
action, err := ensureSingleCreateAction(actions)
if err != nil {
return err
}
if e, a := "resource-01", action.GetObject().(*rbac.Role).Name; e != a {
return fmt.Errorf("expected %v, got %v", e, a)
}
return nil
},
},
{
name: "simple create with normalization",
key: "foo/resource-01",
startingOrigin: []*authorizationapi.Role{
{
ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"},
Rules: []authorizationapi.PolicyRule{
{
Verbs: sets.NewString("GET"),
Resources: sets.NewString("PODS"),
APIGroups: []string{"V1"},
},
},
},
},
actionCheck: func(actions []clienttesting.Action) error {
action, err := ensureSingleCreateAction(actions)
if err != nil {
return err
}
rbacRole := action.GetObject().(*rbac.Role)
if e, a := "resource-01", rbacRole.Name; e != a {
return fmt.Errorf("expected %v, got %v", e, a)
}
expectedRBACRules := []rbac.PolicyRule{
{
Verbs: []string{"get"},
Resources: []string{"pods"},
APIGroups: []string{"v1"},
},
}
if !apiequality.Semantic.DeepEqual(expectedRBACRules, rbacRole.Rules) {
return fmt.Errorf("expected %v, got %v", expectedRBACRules, rbacRole.Rules)
}
return nil
},
},
{
name: "delete on missing origin",
key: "foo/resource-01",
startingRBAC: []*rbac.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
actionCheck: func(actions []clienttesting.Action) error {
action, err := ensureSingleDeleteAction(actions)
if err != nil {
return err
}
if e, a := "resource-01", action.GetName(); e != a {
return fmt.Errorf("expected %v, got %v", e, a)
}
return nil
},
},
{
name: "simple update",
key: "foo/resource-01",
startingRBAC: []*rbac.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
startingOrigin: []*authorizationapi.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01", Annotations: map[string]string{"foo": "different"}}},
},
actionCheck: func(actions []clienttesting.Action) error {
action, err := ensureSingleUpdateAction(actions)
if err != nil {
return err
}
if e, a := "resource-01", action.GetObject().(*rbac.Role).Name; e != a {
return fmt.Errorf("expected %v, got %v", e, a)
}
return nil
},
},
{
name: "no action on zero diff",
key: "foo/resource-01",
startingRBAC: []*rbac.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
startingOrigin: []*authorizationapi.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
actionCheck: func(actions []clienttesting.Action) error {
if len(actions) != 0 {
return fmt.Errorf("expected %v, got %v", 0, actions)
}
return nil
},
},
{
name: "invalid update",
key: "foo/resource-01",
startingRBAC: []*rbac.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01"}},
},
startingOrigin: []*authorizationapi.Role{
{ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "resource-01", Annotations: map[string]string{"foo": "different"}}},
},
actionCheck: func(actions []clienttesting.Action) error {
if len(actions) != 2 {
return fmt.Errorf("expected update then delete, got %v", actions)
}
if _, ok := actions[0].(clienttesting.UpdateAction); !ok {
return fmt.Errorf("expected update, got %v", actions)
}
if _, ok := actions[1].(clienttesting.DeleteAction); !ok {
return fmt.Errorf("expected delete, got %v", actions)
}
return nil
},
reactions: map[reactionMatch]clienttesting.ReactionFunc{
{verb: "update", resource: "roles"}: func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) {
return true, nil, apierrors.NewInvalid(rbac.Kind("Role"), "dummy", nil)
},
},
expectedError: "is invalid",
},
}
for _, tc := range tests {
objs := []runtime.Object{}
rbacIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})
originIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})
for _, obj := range tc.startingRBAC {
rbacIndexer.Add(obj)
objs = append(objs, obj)
}
for _, obj := range tc.startingOrigin {
originIndexer.Add(obj)
}
fakeClient := fake.NewSimpleClientset(objs...)
for reactionMatch, action := range tc.reactions {
fakeClient.PrependReactor(reactionMatch.verb, reactionMatch.resource, action)
}
c := &OriginRoleToRBACRoleController{
rbacClient: fakeClient.Rbac(),
rbacLister: rbaclister.NewRoleLister(rbacIndexer),
originLister: originlister.NewRoleLister(originIndexer),
}
err := c.syncRole(tc.key)
switch {
case len(tc.expectedError) == 0 && err == nil:
case len(tc.expectedError) == 0 && err != nil:
t.Errorf("%s: %v", tc.name, err)
case len(tc.expectedError) != 0 && err == nil:
t.Errorf("%s: missing %v", tc.name, tc.expectedError)
case len(tc.expectedError) != 0 && err != nil && !strings.Contains(err.Error(), tc.expectedError):
t.Errorf("%s: expected %v, got %v", tc.name, tc.expectedError, err)
}
if err := tc.actionCheck(fakeClient.Actions()); err != nil {
t.Errorf("%s: %v", tc.name, err)
}
}
}
| {
"content_hash": "9694bc67d558105fca3a02623cb7f58d",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 131,
"avg_line_length": 32.30275229357798,
"alnum_prop": 0.6512354444760011,
"repo_name": "detiber/origin",
"id": "086b67895f656c455159ecbc35019ba3a324332c",
"size": "7042",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pkg/authorization/controller/authorizationsync/origin_to_rbac_role_controller_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1842"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "19152975"
},
{
"name": "Groovy",
"bytes": "5288"
},
{
"name": "HTML",
"bytes": "74732"
},
{
"name": "Makefile",
"bytes": "22272"
},
{
"name": "Protocol Buffer",
"bytes": "657454"
},
{
"name": "Python",
"bytes": "33408"
},
{
"name": "Roff",
"bytes": "2049"
},
{
"name": "Ruby",
"bytes": "484"
},
{
"name": "Shell",
"bytes": "2186188"
},
{
"name": "Smarty",
"bytes": "626"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Symfony2PluginSettings">
<option name="directoryToApp" value="src" />
<option name="pluginEnabled" value="true" />
<option name="profilerCsvPath" value="" />
<option name="lastServiceGeneratorLanguage" value="yaml" />
</component>
</project> | {
"content_hash": "6e11fe12e9b58d917b240fe25644ce78",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 63,
"avg_line_length": 37.666666666666664,
"alnum_prop": 0.6814159292035398,
"repo_name": "tarlepp/symfony-flex-backend",
"id": "db5a581e303e45fade8248aca0a2251e25cceb19",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/symfony2.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2190"
},
{
"name": "Makefile",
"bytes": "30268"
},
{
"name": "PHP",
"bytes": "1586756"
},
{
"name": "Shell",
"bytes": "36370"
},
{
"name": "Smarty",
"bytes": "1262"
},
{
"name": "Twig",
"bytes": "991"
}
],
"symlink_target": ""
} |
package org.diirt.datasource.formula;
import java.util.Arrays;
import java.util.List;
import org.diirt.datasource.util.NullUtils;
import org.diirt.vtype.VBoolean;
import org.diirt.vtype.VNumber;
import org.diirt.vtype.ValueFactory;
import org.diirt.vtype.ValueUtil;
/**
* Abstract class for formula functions that take two {@link VNumber} as arguments
* and return a {@link VBoolean}.
* <p>
* This class takes care of:
* <ul>
* <li>extracting double value from {@code VNumber}</li>
* <li>null handling - returns null if one argument is null</li>
* <li>alarm handling - returns highest alarm</li>
* <li>time handling - returns latest time, or now if no time is available</li>
* <li>display handling - returns display none</li>
* </ul>
*
* @author carcassi
*/
public abstract class AbstractVNumberVNumberToVBooleanFormulaFunction implements FormulaFunction {
private final String name;
private final String description;
private final List<Class<?>> argumentTypes;
private final List<String> argumentNames;
/**
* Creates a new function.
*
* @param name function name; can't be null
* @param description function description; can't be null
* @param arg1Name first argument name; can't be null
* @param arg2Name second argument name; can't be null
*/
public AbstractVNumberVNumberToVBooleanFormulaFunction(String name, String description, String arg1Name, String arg2Name) {
// Validate parameters
if (name == null) {
throw new NullPointerException("Function name can't be null");
}
if (description == null) {
throw new NullPointerException("Function description can't be null");
}
if (arg1Name == null) {
throw new NullPointerException("First argument name can't be null");
}
if (arg2Name == null) {
throw new NullPointerException("Second argument name can't be null");
}
this.name = name;
this.description = description;
this.argumentTypes = Arrays.<Class<?>>asList(VNumber.class, VNumber.class);
this.argumentNames = Arrays.asList(arg1Name, arg2Name);
}
@Override
public final String getName() {
return name;
}
@Override
public final String getDescription() {
return description;
}
@Override
public final boolean isPure() {
return true;
}
@Override
public final boolean isVarArgs() {
return false;
}
@Override
public final List<Class<?>> getArgumentTypes() {
return argumentTypes;
}
@Override
public final List<String> getArgumentNames() {
return argumentNames;
}
@Override
public final Class<?> getReturnType() {
return VBoolean.class;
}
@Override
public final Object calculate(List<Object> args) {
if (NullUtils.containsNull(args)) {
return null;
}
VNumber arg1 = (VNumber) args.get(0);
VNumber arg2 = (VNumber) args.get(1);
return ValueFactory.newVBoolean(
calculate(arg1.getValue().doubleValue(), arg2.getValue().doubleValue()),
ValueUtil.highestSeverityOf(args, false),
ValueUtil.latestValidTimeOrNowOf(args));
}
/**
* Calculates the result based on the two arguments. This is the only
* method one has to implement.
*
* @param arg1 the first argument
* @param arg2 the second argument
* @return the result
*/
public abstract boolean calculate(double arg1, double arg2);
}
| {
"content_hash": "e02dc2203be5c39e72efa36510f11c94",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 127,
"avg_line_length": 29.330645161290324,
"alnum_prop": 0.6436623590871597,
"repo_name": "berryma4/diirt",
"id": "074c4b148b4409626ef3db515f9d33fbb28ad425",
"size": "3778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pvmanager/datasource-formula/src/main/java/org/diirt/datasource/formula/AbstractVNumberVNumberToVBooleanFormulaFunction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "314"
},
{
"name": "CSS",
"bytes": "75261"
},
{
"name": "GAP",
"bytes": "5847"
},
{
"name": "HTML",
"bytes": "423157"
},
{
"name": "Java",
"bytes": "4747777"
},
{
"name": "JavaScript",
"bytes": "1745584"
},
{
"name": "Shell",
"bytes": "3095"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.mediapackage.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.mediapackage.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListOriginEndpointsRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListOriginEndpointsRequestMarshaller {
private static final MarshallingInfo<String> CHANNELID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("channelId").build();
private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("maxResults").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("nextToken").build();
private static final ListOriginEndpointsRequestMarshaller instance = new ListOriginEndpointsRequestMarshaller();
public static ListOriginEndpointsRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ListOriginEndpointsRequest listOriginEndpointsRequest, ProtocolMarshaller protocolMarshaller) {
if (listOriginEndpointsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listOriginEndpointsRequest.getChannelId(), CHANNELID_BINDING);
protocolMarshaller.marshall(listOriginEndpointsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listOriginEndpointsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "c080aa9e7e7cc5d252c5fce3c15894d4",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 120,
"avg_line_length": 42.82,
"alnum_prop": 0.7585240541802896,
"repo_name": "aws/aws-sdk-java",
"id": "60e4ff5d719a9a98b9709a7368604f781fdccc8f",
"size": "2721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-mediapackage/src/main/java/com/amazonaws/services/mediapackage/model/transform/ListOriginEndpointsRequestMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/address_utils/parse_address.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/socket_windows.h"
bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); }
#endif /* GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) */
| {
"content_hash": "c7054a3b460eee1991c0d8301438e275",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 86,
"avg_line_length": 34.611111111111114,
"alnum_prop": 0.7399678972712681,
"repo_name": "donnadionne/grpc",
"id": "f76c6a4a12bcb91d44af94841ddb974584748aa6",
"size": "1225",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "5444"
},
{
"name": "Batchfile",
"bytes": "28628"
},
{
"name": "C",
"bytes": "6403510"
},
{
"name": "C#",
"bytes": "2620252"
},
{
"name": "C++",
"bytes": "14264354"
},
{
"name": "CMake",
"bytes": "499835"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "Cython",
"bytes": "302472"
},
{
"name": "DTrace",
"bytes": "147"
},
{
"name": "Dockerfile",
"bytes": "159399"
},
{
"name": "Go",
"bytes": "34794"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "6259"
},
{
"name": "JavaScript",
"bytes": "112392"
},
{
"name": "M4",
"bytes": "87664"
},
{
"name": "Makefile",
"bytes": "246627"
},
{
"name": "Objective-C",
"bytes": "694725"
},
{
"name": "Objective-C++",
"bytes": "77696"
},
{
"name": "PHP",
"bytes": "484892"
},
{
"name": "PowerShell",
"bytes": "3985"
},
{
"name": "Python",
"bytes": "3749620"
},
{
"name": "Ruby",
"bytes": "1045127"
},
{
"name": "Shell",
"bytes": "675777"
},
{
"name": "Starlark",
"bytes": "628488"
},
{
"name": "Swift",
"bytes": "8643"
},
{
"name": "XSLT",
"bytes": "9846"
}
],
"symlink_target": ""
} |
Clazz.load(["java.lang.RuntimeException"],"java.lang.TypeNotPresentException",null,function(){
c$=Clazz.decorateAsClass(function(){
this.$typeName=null;
Clazz.instantialize(this,arguments);
},java.lang,"TypeNotPresentException",RuntimeException);
Clazz.makeConstructor(c$,
function(typeName,cause){
Clazz.superConstructor(this,TypeNotPresentException,["Type "+typeName+" not present",cause]);
this.$typeName=typeName;
},"~S,Throwable");
Clazz.defineMethod(c$,"typeName",
function(){
return this.$typeName;
});
});
| {
"content_hash": "ee2c3e4d3cb906a5bcc79a97f7944f4d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 94,
"avg_line_length": 34.266666666666666,
"alnum_prop": 0.77431906614786,
"repo_name": "bas-rustenburg/jsmol-local",
"id": "19ad7a973b2519acb4b3d6ec2e6e2f85983e7183",
"size": "514",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "j2s/java/lang/TypeNotPresentException.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "926"
},
{
"name": "JavaScript",
"bytes": "6963665"
}
],
"symlink_target": ""
} |
๏ปฟ
#include <aws/inspector/model/ReportStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace Inspector
{
namespace Model
{
namespace ReportStatusMapper
{
static const int WORK_IN_PROGRESS_HASH = HashingUtils::HashString("WORK_IN_PROGRESS");
static const int FAILED_HASH = HashingUtils::HashString("FAILED");
static const int COMPLETED_HASH = HashingUtils::HashString("COMPLETED");
ReportStatus GetReportStatusForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == WORK_IN_PROGRESS_HASH)
{
return ReportStatus::WORK_IN_PROGRESS;
}
else if (hashCode == FAILED_HASH)
{
return ReportStatus::FAILED;
}
else if (hashCode == COMPLETED_HASH)
{
return ReportStatus::COMPLETED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ReportStatus>(hashCode);
}
return ReportStatus::NOT_SET;
}
Aws::String GetNameForReportStatus(ReportStatus enumValue)
{
switch(enumValue)
{
case ReportStatus::WORK_IN_PROGRESS:
return "WORK_IN_PROGRESS";
case ReportStatus::FAILED:
return "FAILED";
case ReportStatus::COMPLETED:
return "COMPLETED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace ReportStatusMapper
} // namespace Model
} // namespace Inspector
} // namespace Aws
| {
"content_hash": "8222860d19898044ec19491ff9fe2893",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 94,
"avg_line_length": 28.91891891891892,
"alnum_prop": 0.5976635514018691,
"repo_name": "jt70471/aws-sdk-cpp",
"id": "cde0870e09e721f6ff8a0a2b56fe9b90135a3244",
"size": "2259",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-inspector/source/model/ReportStatus.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13452"
},
{
"name": "C++",
"bytes": "278594037"
},
{
"name": "CMake",
"bytes": "653931"
},
{
"name": "Dockerfile",
"bytes": "5555"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "302182"
},
{
"name": "Python",
"bytes": "110380"
},
{
"name": "Shell",
"bytes": "4674"
}
],
"symlink_target": ""
} |
[![NPM version][npm-image]][npm-url]
[![Unix Build Status][travis-image]][travis-url]
[![Windows Build Status][appveyor-image]][appveyor-url]
[![Coveralls Status][coveralls-image]][coveralls-url]
[![Dependency Status][depstat-image]][depstat-url]
**Unbend** Flatten tree into an object with `{ '/complete/path/to/each': value }`
E.g. this useful for parametric http routing
## Install
npm install --save unbend
## Usage
unbend( Object, [ config ] )
```js
const unbend = require('unbend')
const source = {
route: {
inner: {
func: () => {},
str : 'string'
},
list: [ 'some data', {} ]
},
def: null
}
unbend( source )
```
And that will turn into
```js
const expected = {
'/route/inner/func': () => {},
'/route/inner/str' : 'string',
'/route/list' : [ 'some data', {} ],
'/def' : null
}
```
See [test data file](https://github.com/zerobias/unbend/blob/master/test/test-data.js) for complete examples
## Configuration
Unbend supports optional config object at second argument.
### Default config
```js
const config = {
separator : '/',
skipFirstSeparator: false,
parseArray : false
}
```
### Custom separators
> unbend(tree, { separator: '.' })
```js
const source = {
route: {
inner: {
func: () => {},
str : 'string'
}
},
def: null
}
unbend( source, { separator: '.' } )
//And that will turn into
const expected = {
'.route.inner.func': () => {},
'.route.inner.str' : 'string',
'.def' : null
}
```
### Convert nested arrays
> unbend(tree, { parseArray: true })
```js
const unbend = require('unbend')
const source = {
list: [
'any',
{ },
null,
{ 'field': 'inside array' }
]
}
unbend( source, { parseArray: true } )
//And that will turn into
const expected = {
'/list/0' : 'any',
'/list/2' : null,
'/list/3/field': 'inside array'
}
```
### Skip first separator
> unbend(tree, { skipFirstSeparator: true })
```js
const source = {
route: {
inner: {
func: () => {},
str : 'string'
}
},
def: null
}
unbend( source, { skipFirstSeparator: true } )
//And that will turn into
const expected = {
'route/inner/func': () => {},
'route/inner/str' : 'string',
'def' : null
}
```
## License
MIT ยฉ [Zero Bias](https://github.com/zerobias)
[npm-url]: https://npmjs.org/package/unbend
[npm-image]: https://img.shields.io/npm/v/unbend.svg?style=flat-square
[travis-url]: https://travis-ci.org/zerobias/unbend
[travis-image]: https://img.shields.io/travis/zerobias/unbend.svg?style=flat-square&label=unix
[appveyor-url]: https://ci.appveyor.com/project/zerobias/unbend
[appveyor-image]: https://img.shields.io/appveyor/ci/zerobias/unbend.svg?style=flat-square&label=windows
[coveralls-url]: https://coveralls.io/r/zerobias/unbend
[coveralls-image]: https://img.shields.io/coveralls/zerobias/unbend.svg?style=flat-square
[depstat-url]: https://david-dm.org/zerobias/unbend
[depstat-image]: https://david-dm.org/zerobias/unbend.svg?style=flat-square | {
"content_hash": "0410f9e07c7881ffbcf23c7742334387",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 108,
"avg_line_length": 19.556962025316455,
"alnum_prop": 0.610032362459547,
"repo_name": "zerobias/unbend",
"id": "abb5851dc7df89ea8badb44468269a09e18e549f",
"size": "3101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5750"
}
],
"symlink_target": ""
} |
#homepage-url-field {
bottom: 1px;
display: block;
margin-left: 10px;
position: relative;
}
| {
"content_hash": "90a718acff3a1477df507b7f1915127f",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 21,
"avg_line_length": 12.75,
"alnum_prop": 0.6568627450980392,
"repo_name": "junmin-zhu/chromium-rivertrail",
"id": "d32713e08e39c81fc4068d7a8198fe88a5e0c880",
"size": "273",
"binary": false,
"copies": "6",
"ref": "refs/heads/v8-binding",
"path": "chrome/browser/resources/options/home_page_overlay.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75806807"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "145161929"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "1546515"
},
{
"name": "JavaScript",
"bytes": "18675242"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "6981387"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "926245"
},
{
"name": "Python",
"bytes": "8088373"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3239"
},
{
"name": "Shell",
"bytes": "1513486"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
} |
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _jsxWrapper = function _jsxWrapper(func, args) {
return {
__jsxDOMWrapper: true,
func: func,
args: args
};
};
var _hasOwn = Object.prototype.hasOwnProperty;
var _renderArbitrary = function _renderArbitrary(child) {
var type = _typeof(child);
if (type === "number" || type === "string" || type === "object" && child instanceof String) {
text(child);
} else if (Array.isArray(child)) {
for (var i = 0; i < child.length; i++) {
_renderArbitrary(child[i]);
}
} else if (type === "object") {
if (child.__jsxDOMWrapper) {
var func = child.func,
args = child.args;
if (args) {
func.apply(this, args);
} else {
func();
}
} else if (String(child) === "[object Object]") {
for (var prop in child) {
if (_hasOwn.call(child, i)) _renderArbitrary(child[i]);
}
}
}
};
var _li$statics = ["key", ""],
_li$wrapper = function _li$wrapper(_file$name, _file, _onclick, _file$name2) {
_li$statics[1] = _file$name;
elementOpen("li", _file$name, _li$statics, "file", _file, "onclick", _onclick);
_renderArbitrary(_file$name2);
return elementClose("li");
};
function render() {
// @incremental-dom disable-fastRoot
elementOpen("ul");
_renderArbitrary(files.map(function (file) {
return _jsxWrapper(_li$wrapper, [file.name, file, function (e) {
return fileClicked(e, file);
}, file.name]);
}));
return elementClose("ul");
} | {
"content_hash": "ef6fece2c0df5e3443048b5caa8bc178",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 351,
"avg_line_length": 29.950819672131146,
"alnum_prop": 0.5938697318007663,
"repo_name": "jridgewell/babel-plugin-transform-incremental-dom",
"id": "da0e8485a17a5d874169e88025a13d1fcf564c00",
"size": "1827",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/fixtures/fast-root/comments/disable-inline/function-level/expected.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "56557"
}
],
"symlink_target": ""
} |
namespace Twilio.Base
{
public abstract class Resource {}
} | {
"content_hash": "37ec91b79a6ebf19bb39a7a55e3ebfb4",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 37,
"avg_line_length": 15.75,
"alnum_prop": 0.7301587301587301,
"repo_name": "twilio/twilio-csharp",
"id": "69354a900dfdeff4d24cad6365f7bba994931d69",
"size": "63",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Twilio/Base/Resource.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "13879265"
},
{
"name": "Dockerfile",
"bytes": "1137"
},
{
"name": "Makefile",
"bytes": "1970"
}
],
"symlink_target": ""
} |
/** @file */ // Doxygen marker
/* Base library of extensions to iOS frameworks to support cocos3d. */
#import "CC3Environment.h"
#if CC3_IOS
#import <UIKit/UIGestureRecognizer.h>
#import <UIKit/UIColor.h>
#import "CC3OpenGLFoundation.h"
// Define when compiling with lower SDK's
#ifndef __IPHONE_5_0
# define __IPHONE_5_0 50000
#endif
#ifndef __IPHONE_6_0
# define __IPHONE_6_0 60000
#endif
#ifndef __IPHONE_7_0
# define __IPHONE_7_0 70000
#endif
/** iOS equivalents for OSX declaration */
#define NSEvent NSObject
#pragma mark -
#pragma mark Gesture Recognizer extensions
/** Extension category to support cocos3d functionality. */
@interface UIGestureRecognizer (CC3)
/** Cancels this gesture recognizer. */
-(void) cancel;
/**
* Returns the location of the gesture in the view to which this recognizer is attached.
*
* This is a convenience property that returns the same result as invoking
* locationInView: with the value of the view property of this recognizer.
*/
@property(nonatomic, readonly) CGPoint location;
/** Returns the name of the current value of the state property. */
@property(nonatomic, readonly) NSString* stateName;
@end
/** Extension category to support cocos3d functionality. */
@interface UIPanGestureRecognizer (CC3)
/**
* Returns the translation of the gesture in the view to which this recognizer is attached.
*
* This is a convenience property that returns the same result as invoking
* translationInView: with the value of the view property of this recognizer.
*/
@property(nonatomic, readonly) CGPoint translation;
/**
* Returns the velocity of the gesture in the view to which this recognizer is attached.
*
* This is a convenience property that returns the same result as invoking
* velocityInView: with the value of the view property of this recognizer.
*/
@property(nonatomic, readonly) CGPoint velocity;
@end
#pragma mark -
#pragma mark UIKit extensions
/** For consistency, add compilation support for UIInterfaceOrientationMask for SDK's below iOS 6.0. */
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_6_0
typedef enum {
UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
} UIInterfaceOrientationMask;
#endif
/** Returns the UIInterfaceOrientationMask corresponding to the specified UIInterfaceOrientation. */
static inline UIInterfaceOrientationMask CC3UIInterfaceOrientationMaskFromUIInterfaceOrientation(UIInterfaceOrientation uiOrientation) {
switch (uiOrientation) {
case UIInterfaceOrientationLandscapeLeft:
return UIInterfaceOrientationMaskLandscapeLeft;
case UIInterfaceOrientationLandscapeRight:
return UIInterfaceOrientationMaskLandscapeRight;
case UIInterfaceOrientationPortraitUpsideDown:
return UIInterfaceOrientationMaskPortraitUpsideDown;
case UIInterfaceOrientationPortrait:
default:
return UIInterfaceOrientationMaskPortrait;
}
}
/** Returns whether the specified UIInterfaceOrientationMask includes the specified UIInterfaceOrientation. */
static inline BOOL CC3UIInterfaceOrientationMaskIncludesUIOrientation(NSUInteger uiOrientationMask,
UIInterfaceOrientation uiOrientation) {
return (uiOrientationMask & CC3UIInterfaceOrientationMaskFromUIInterfaceOrientation(uiOrientation)) != 0;
}
/**
* Returns the UIDeviceOrientation corresponding to the specified UIInterfaceOrientation.
*
* For landscape mode, device orientation is the opposite to the UI orientation (Left <=> Right),
* otherwise the device orientation is the same as the UI orientation.
*/
static inline UIDeviceOrientation CC3UIDeviceOrientationFromUIInterfaceOrientation(UIInterfaceOrientation uiOrientation) {
switch (uiOrientation) {
case UIInterfaceOrientationLandscapeLeft:
return UIDeviceOrientationLandscapeRight;
case UIInterfaceOrientationLandscapeRight:
return UIDeviceOrientationLandscapeLeft;
case UIInterfaceOrientationPortrait:
return UIDeviceOrientationPortrait;
case UIInterfaceOrientationPortraitUpsideDown:
return UIDeviceOrientationPortraitUpsideDown;
default:
return UIDeviceOrientationUnknown;
}
}
#pragma mark -
#pragma mark UIView extensions
@interface UIView (CC3)
/** Returns this view's controller, or nil if it doesn't have one. */
@property(nonatomic, readonly) UIViewController* viewController;
@end
#pragma mark -
#pragma mark UIViewController extensions
@interface UIViewController (CC3)
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_5_0
/** Add to prior versions of iOS to support forward compatibility. */
-(void) viewDidLayoutSubviews;
#endif
@end
#pragma mark -
#pragma mark UIColor extensions
/** Extension category to support cocos3d functionality. */
@interface UIColor(CC3)
/** Returns a transparent ccColor4F struct containing the RGBA values for this color. */
-(ccColor4F) asCCColor4F;
/** Returns an autoreleased UIColor instance created from the RGBA values in the specified ccColor4F. */
+(UIColor*) colorWithCCColor4F: (ccColor4F) rgba;
@end
#pragma mark -
#pragma mark Open GL Context
/** GL context under iOS */
#define CC3GLContext EAGLContext
/** Extension category to support cocos3d functionality. */
@interface EAGLContext (CC3)
/** Ensures this GL context is the GL context for the currently running thread. */
-(void) ensureCurrentContext;
/** Clears the GL context for the currently running thread. */
+(void) clearCurrentContext;
/**
* Returns a GL context that shares GL content with this context.
*
* The returned context can be used wherever a separate GL context that shares common GL
* content with this is required. Typically, this method is used to retrieve a secondary
* GL context to be used for background loading on a different thread.
*/
-(CC3GLContext*) asSharedContext;
@end
#pragma mark -
#pragma mark Miscellaneous extensions and functions
/** Returns a string description of the specified UIInterfaceOrientation. */
NSString* NSStringFromUIInterfaceOrientation(UIInterfaceOrientation uiOrientation);
/** Returns a string description of the specified UIDeviceOrientation. */
NSString* NSStringFromUIDeviceOrientation(UIDeviceOrientation deviceOrientation);
#endif // CC3_IOS
| {
"content_hash": "63ff05d138160a05f8573ee300cf9111",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 202,
"avg_line_length": 33.19138755980861,
"alnum_prop": 0.796453798471962,
"repo_name": "ngrebenshikov/SisyphusHill",
"id": "137442a57601cefc6a5997c5787c26b42ab669eb",
"size": "8236",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pyramid-xcode/Pyramid/cocos3d/cocos3d/cocos3d/Platforms/iOS/CC3IOSExtensions.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "27014"
},
{
"name": "C",
"bytes": "6794924"
},
{
"name": "C++",
"bytes": "14126306"
},
{
"name": "Cuda",
"bytes": "94563"
},
{
"name": "D",
"bytes": "236"
},
{
"name": "FLUX",
"bytes": "8125"
},
{
"name": "JavaScript",
"bytes": "25197"
},
{
"name": "Lua",
"bytes": "21096"
},
{
"name": "M",
"bytes": "485840"
},
{
"name": "Matlab",
"bytes": "16538"
},
{
"name": "Objective-C",
"bytes": "9147666"
},
{
"name": "Objective-C++",
"bytes": "196758"
},
{
"name": "Python",
"bytes": "11022"
},
{
"name": "Ruby",
"bytes": "1433"
},
{
"name": "Shell",
"bytes": "42540"
},
{
"name": "TeX",
"bytes": "12612"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
<result>
<type>locality</type>
<type>political</type>
<formatted_address>3812 Groร-Siegharts, Austria</formatted_address>
<address_component>
<long_name>Groร-Siegharts</long_name>
<short_name>Groร-Siegharts</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Gemeinde Groร-Siegharts</long_name>
<short_name>Gemeinde Groร-Siegharts</short_name>
<type>administrative_area_level_3</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Waidhofen an der Thaya District</long_name>
<short_name>Waidhofen an der Thaya District</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Lower Austria</long_name>
<short_name>Lower Austria</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Austria</long_name>
<short_name>AT</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>3812</long_name>
<short_name>3812</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>48.7918512</lat>
<lng>15.4047628</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>48.7844998</lat>
<lng>15.3887554</lng>
</southwest>
<northeast>
<lat>48.7992015</lat>
<lng>15.4207702</lng>
</northeast>
</viewport>
</geometry>
<place_id>ChIJI6VcnHHGckcR-ULNBDMhuWs</place_id>
</result>
</GeocodeResponse>
| {
"content_hash": "b5afb4b9ff06804e965b5d5330010e36",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 69,
"avg_line_length": 28.532258064516128,
"alnum_prop": 0.6823063877897118,
"repo_name": "linkeddatalab/statspace",
"id": "763e72bfb1d0c92fcbe9b45ca99a1f52e9b40760",
"size": "1774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/datasources/ogd.ifs.tuwien.ac.at_sparql/areas/32200_32207.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24977"
},
{
"name": "HTML",
"bytes": "245851"
},
{
"name": "Java",
"bytes": "1177495"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66a.c
Label Definition File: CWE590_Free_Memory_Not_on_Heap__free.label.xml
Template File: sources-sink-66a.tmpl.c
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: alloca Data buffer is allocated on the stack with alloca()
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
/* bad function declaration */
void CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66b_badSink(char * dataArray[]);
void CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66_bad()
{
char * data;
char * dataArray[5];
data = NULL; /* Initialize data */
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
char * dataBuffer = (char *)ALLOCA(100*sizeof(char));
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
/* put data in array */
dataArray[2] = data;
CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66b_badSink(dataArray);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66b_goodG2BSink(char * dataArray[]);
static void goodG2B()
{
char * data;
char * dataArray[5];
data = NULL; /* Initialize data */
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL)
{
printLine("malloc() failed");
exit(1);
}
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
dataArray[2] = data;
CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66b_goodG2BSink(dataArray);
}
void CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "3bf31a1b587037d839e907ebe9b38d06",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 109,
"avg_line_length": 30.135922330097088,
"alnum_prop": 0.6288659793814433,
"repo_name": "JianpingZeng/xcc",
"id": "af77f4c24fd130f63cb51ca08797e78008bd6909",
"size": "3104",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s04/CWE590_Free_Memory_Not_on_Heap__free_char_alloca_66a.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace System.Windows.Forms {
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms.Layout;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms.Internal;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu"]/*' />
[Designer("System.Windows.Forms.Design.ToolStripDropDownDesigner, " + AssemblyRef.SystemDesign)]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class ToolStripDropDownMenu : ToolStripDropDown {
private static Padding ImagePadding = new Padding(2);
private static Padding TextPadding = new Padding(8,1,9,1);
private static Padding CheckPadding = new Padding(5,2,2,2);
private static Padding ArrowPadding = new Padding(0,0,8,0);
// This is totally a UI Fudge - if we have an image or check margin with
// no image or checks in it use this - which is consistent with office
// and an image margin with a 16x16 icon in it.
private static int DefaultImageMarginWidth = 25; // 24+1px border
private static int DefaultImageAndCheckMarginWidth = 47; // 46+1px border
private Size maxItemSize = Size.Empty;
private Rectangle checkRectangle = Rectangle.Empty;
private Rectangle imageRectangle = Rectangle.Empty;
private Rectangle arrowRectangle = Rectangle.Empty;
private Rectangle textRectangle = Rectangle.Empty;
private Rectangle imageMarginBounds = Rectangle.Empty;
private int paddingToTrim = 0;
private int tabWidth = -1;
private ToolStripScrollButton upScrollButton = null;
private ToolStripScrollButton downScrollButton = null;
private int scrollAmount = 0;
private int indexOfFirstDisplayedItem = -1;
private BitVector32 state = new BitVector32();
private static readonly int stateShowImageMargin = BitVector32.CreateMask();
private static readonly int stateShowCheckMargin = BitVector32.CreateMask(stateShowImageMargin);
private static readonly int stateMaxItemSizeValid = BitVector32.CreateMask(stateShowCheckMargin);
private static readonly Size DefaultImageSize = new Size(16, 16);
private static bool isScalingInitialized = false;
private static Size ScaledDefaultImageSize = DefaultImageSize;
private static int ScaledDefaultImageMarginWidth = DefaultImageMarginWidth;
private static int ScaledDefaultImageAndCheckMarginWidth = DefaultImageAndCheckMarginWidth;
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.ToolStripDropDownMenu"]/*' />
/// <devdoc>
/// Summary of ToolStripDropDown.
/// </devdoc>
public ToolStripDropDownMenu(){
}
/// <devdoc>
/// Constructor to autogenerate
/// </devdoc>
internal ToolStripDropDownMenu(ToolStripItem ownerItem, bool isAutoGenerated) : base(ownerItem,isAutoGenerated) {
if (!isScalingInitialized) {
if (DpiHelper.IsScalingRequired) {
ScaledDefaultImageSize = DpiHelper.LogicalToDeviceUnits(DefaultImageSize);
ScaledDefaultImageMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageMarginWidth);
ScaledDefaultImageAndCheckMarginWidth = DpiHelper.LogicalToDeviceUnitsX(DefaultImageAndCheckMarginWidth);
}
isScalingInitialized = true;
}
}
internal override bool AllItemsVisible {
get {
return !RequiresScrollButtons;
}
set {
RequiresScrollButtons = !value;
}
}
internal Rectangle ArrowRectangle {
get {
return arrowRectangle;
}
}
internal Rectangle CheckRectangle {
get {
return checkRectangle;
}
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.DefaultPadding"]/*' />
protected override Padding DefaultPadding {
get {
RightToLeft rightToLeft = RightToLeft;
int textPadding = (rightToLeft == RightToLeft.Yes) ? TextPadding.Right : TextPadding.Left;
int padding = (ShowCheckMargin || ShowImageMargin) ? textPadding + ImageMargin.Width : textPadding;
// scooch in all the items by the margin.
if (rightToLeft == RightToLeft.Yes) {
return new Padding(1,2,padding,2);
}
return new Padding(padding,2,1,2);
}
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.DisplayRectangle"]/*' />
public override Rectangle DisplayRectangle {
get {
Rectangle rect = base.DisplayRectangle;
if (GetToolStripState(STATE_SCROLLBUTTONS)) {
rect.Y += UpScrollButton.Height + UpScrollButton.Margin.Vertical;
rect.Height -= UpScrollButton.Height + UpScrollButton.Margin.Vertical + DownScrollButton.Height + DownScrollButton.Margin.Vertical;
// Because we're going to draw the scroll buttons on top of the padding, we need to add it back in here.
rect = LayoutUtils.InflateRect(rect, new Padding(0, this.Padding.Top, 0, this.Padding.Bottom));
}
return rect;
}
}
private ToolStripScrollButton DownScrollButton {
get {
if (downScrollButton == null) {
downScrollButton = new ToolStripScrollButton(false);
downScrollButton.ParentInternal = this;
}
return downScrollButton;
}
}
/// <devdoc>
/// the rectangle representing
/// </devdoc>
internal Rectangle ImageRectangle {
get {
return imageRectangle;
}
}
internal int PaddingToTrim {
get {
return paddingToTrim;
}
set {
if (paddingToTrim != value) {
paddingToTrim = value;
AdjustSize();
}
}
}
/// <devdoc>
/// the rectangle representing the color stripe in the menu - this will appear as AffectedBounds
/// in the ToolStripRenderEventArgs
/// </devdoc>
internal Rectangle ImageMargin {
get {
imageMarginBounds.Height =this.Height;
return imageMarginBounds;
}
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.LayoutEngine"]/*' />
public override LayoutEngine LayoutEngine {
get {
return ToolStripDropDownLayoutEngine.LayoutInstance;
}
}
[
DefaultValue(ToolStripLayoutStyle.Flow)
]
public new ToolStripLayoutStyle LayoutStyle {
get { return base.LayoutStyle; }
set { base.LayoutStyle = value; }
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.MaxItemSize"]/*' />
protected internal override Size MaxItemSize {
get {
if (!state[stateMaxItemSizeValid]) {
CalculateInternalLayoutMetrics();
}
return maxItemSize;
}
}
/// <include file='doc\WinBarDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.ShowImageMargin"]/*' />
[
DefaultValue(true),
SRDescription(SR.ToolStripDropDownMenuShowImageMarginDescr),
SRCategory(SR.CatAppearance)
]
public bool ShowImageMargin {
get {
return state[stateShowImageMargin];
}
set {
if (value != state[stateShowImageMargin]) {
state[stateShowImageMargin] = value;
LayoutTransaction.DoLayout(this, this, PropertyNames.ShowImageMargin);
}
}
}
/// <include file='doc\WinBarDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.ShowCheckMargin"]/*' />
[
DefaultValue(false),
SRDescription(SR.ToolStripDropDownMenuShowCheckMarginDescr),
SRCategory(SR.CatAppearance)
]
public bool ShowCheckMargin {
get {
return state[stateShowCheckMargin];
}
set {
if (value != state[stateShowCheckMargin]) {
state[stateShowCheckMargin] = value;
LayoutTransaction.DoLayout(this, this, PropertyNames.ShowCheckMargin);
}
}
}
internal Rectangle TextRectangle {
get {
return textRectangle;
}
}
private ToolStripScrollButton UpScrollButton {
get {
if (upScrollButton == null) {
upScrollButton = new ToolStripScrollButton(true);
upScrollButton.ParentInternal = this;
}
return upScrollButton;
}
}
/// <devdoc> this takes a native menu and builds up a managed toolstrip around it.
/// Scenario: showing the items from the SystemMenu.
/// targetWindow is the window to send WM_COMMAND, WM_SYSCOMMAND to
/// hmenu is a handle to the native menu
///
///
internal static ToolStripDropDownMenu FromHMenu(IntPtr hmenu, IWin32Window targetWindow) {
ToolStripDropDownMenu managedDropDown = new ToolStripDropDownMenu();
managedDropDown.SuspendLayout();
HandleRef menuHandle = new HandleRef(null, hmenu);
int count = UnsafeNativeMethods.GetMenuItemCount(menuHandle);
ToolStripItem itemToAdd;
// surf through the items in the collection, building up TSMenuItems and TSSeparators
// corresponding to the native menu.
for (int i = 0; i < count; i++) {
// peek at the i'th item.
NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW();
info.cbSize = Marshal.SizeOf(typeof(NativeMethods.MENUITEMINFO_T_RW));
info.fMask = NativeMethods.MIIM_FTYPE;
info.fType = NativeMethods.MIIM_FTYPE;
UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info);
if (info.fType == NativeMethods.MFT_SEPARATOR){
// its a separator.
itemToAdd = new ToolStripSeparator();
}
else {
// its a menu item... lets fish out the command id
info = new NativeMethods.MENUITEMINFO_T_RW();
info.cbSize = Marshal.SizeOf(typeof(NativeMethods.MENUITEMINFO_T_RW));
info.fMask = NativeMethods.MIIM_ID;
info.fType = NativeMethods.MIIM_ID;
UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info);
// create the managed object - toolstripmenu item knows how to grok hmenu for information.
itemToAdd = new ToolStripMenuItem(hmenu, info.wID, targetWindow);
// if there is a submenu fetch it.
info = new NativeMethods.MENUITEMINFO_T_RW();
info.cbSize = Marshal.SizeOf(typeof(NativeMethods.MENUITEMINFO_T_RW));
info.fMask = NativeMethods.MIIM_SUBMENU;
info.fType = NativeMethods.MIIM_SUBMENU;
UnsafeNativeMethods.GetMenuItemInfo(menuHandle, i, /*fByPosition=*/ true, info);
if (info.hSubMenu != IntPtr.Zero) {
// set the dropdown to be the items from the submenu
((ToolStripMenuItem)itemToAdd).DropDown = FromHMenu(info.hSubMenu, targetWindow);
}
}
managedDropDown.Items.Add(itemToAdd);
}
managedDropDown.ResumeLayout();
return managedDropDown;
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // using "\t" to figure out the width of tab
private void CalculateInternalLayoutMetrics() {
Size maxTextSize = Size.Empty;
Size maxImageSize = Size.Empty;
Size maxCheckSize = ScaledDefaultImageSize;
Size maxArrowSize = Size.Empty;
Size maxNonMenuItemSize = Size.Empty;
// determine Text Metrics
for (int i = 0; i < Items.Count; i++) {
ToolStripItem item = Items[i];
ToolStripMenuItem menuItem = item as ToolStripMenuItem;
if (menuItem != null) {
Size menuItemTextSize = menuItem.GetTextSize();
if (menuItem.ShowShortcutKeys) {
Size shortcutTextSize = menuItem.GetShortcutTextSize();
if (tabWidth == -1) {
tabWidth = TextRenderer.MeasureText("\t", this.Font).Width;
}
menuItemTextSize.Width += tabWidth + shortcutTextSize.Width;
menuItemTextSize.Height = Math.Max(menuItemTextSize.Height, shortcutTextSize.Height);
}
// we truly only care about the maximum size we find.
maxTextSize.Width = Math.Max(maxTextSize.Width, menuItemTextSize.Width);
maxTextSize.Height = Math.Max(maxTextSize.Height, menuItemTextSize.Height);
// determine Image Metrics
Size imageSize = Size.Empty;
if (menuItem.Image != null) {
imageSize = (menuItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) ? ImageScalingSize : menuItem.Image.Size;
}
maxImageSize.Width = Math.Max(maxImageSize.Width, imageSize.Width);
maxImageSize.Height = Math.Max(maxImageSize.Height, imageSize.Height);
if (menuItem.CheckedImage != null) {
Size checkedImageSize = menuItem.CheckedImage.Size;
maxCheckSize.Width = Math.Max(checkedImageSize.Width, maxCheckSize.Width);
maxCheckSize.Height = Math.Max(checkedImageSize.Height, maxCheckSize.Height);
}
}
else if (!(item is ToolStripSeparator)) {
maxNonMenuItemSize.Height = Math.Max(item.Bounds.Height, maxNonMenuItemSize.Height);
maxNonMenuItemSize.Width = Math.Max(item.Bounds.Width, maxNonMenuItemSize.Width);
}
}
this.maxItemSize.Height = Math.Max(maxTextSize.Height + TextPadding.Vertical, Math.Max(maxCheckSize.Height + CheckPadding.Vertical, maxArrowSize.Height + ArrowPadding.Vertical));
if (ShowImageMargin) {
// only add in the image into the calculation if we're going to render it.
this.maxItemSize.Height = Math.Max(maxImageSize.Height + ImagePadding.Vertical, maxItemSize.Height);
}
bool useDefaultCheckMarginWidth = (ShowCheckMargin && (maxCheckSize.Width == 0));
bool useDefaultImageMarginWidth = (ShowImageMargin && (maxImageSize.Width == 0));
// Always save space for an arrow
maxArrowSize = new Size(10, maxItemSize.Height);
maxTextSize.Height = maxItemSize.Height - TextPadding.Vertical;
maxImageSize.Height = maxItemSize.Height - ImagePadding.Vertical;
maxCheckSize.Height = maxItemSize.Height - CheckPadding.Vertical;
// fixup if there are non-menu items that are larger than our normal menu items
maxTextSize.Width = Math.Max(maxTextSize.Width, maxNonMenuItemSize.Width);
Point nextPoint = Point.Empty;
int checkAndImageMarginWidth = 0;
int extraImageWidth = Math.Max(0, maxImageSize.Width - ScaledDefaultImageSize.Width);
if (ShowCheckMargin && ShowImageMargin) {
// double column - check margin then image margin
// default to 46px - grow if necessary.
checkAndImageMarginWidth = ScaledDefaultImageAndCheckMarginWidth;
// add in the extra space for the image... since the check size is locked down to 16x16.
checkAndImageMarginWidth += extraImageWidth;
// align the checkmark
nextPoint = new Point(CheckPadding.Left, CheckPadding.Top);
checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, maxCheckSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter);
// align the image rectangle
nextPoint.X = checkRectangle.Right + CheckPadding.Right + ImagePadding.Left;
nextPoint.Y = ImagePadding.Top;
imageRectangle = LayoutUtils.Align(maxImageSize, new Rectangle(nextPoint.X, nextPoint.Y, maxImageSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter);
}
else if (ShowCheckMargin) {
// no images should be shown in a ShowCheckMargin only scenario.
// default to 24px - grow if necessary.
checkAndImageMarginWidth = ScaledDefaultImageMarginWidth;
// align the checkmark
nextPoint = new Point(1,CheckPadding.Top);
// nextPoint = new Point(CheckPadding.Left, CheckPadding.Top);
checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth, maxItemSize.Height), ContentAlignment.MiddleCenter);
imageRectangle = Rectangle.Empty;
}
else if (ShowImageMargin) {
// checks and images render in the same area.
// default to 24px - grow if necessary.
checkAndImageMarginWidth = ScaledDefaultImageMarginWidth;
// add in the extra space for the image... since the check size is locked down to 16x16.
checkAndImageMarginWidth += extraImageWidth;
// NOTE due to the Padding property, we're going to have to recalc the vertical alignment in ToolStripMenuItemInternalLayout.
// Dont fuss here over the Y, X is what's critical.
// check and image rect are the same - take the max of the image size and the check size and align
nextPoint = new Point(1,CheckPadding.Top);
checkRectangle = LayoutUtils.Align(LayoutUtils.UnionSizes(maxCheckSize,maxImageSize), new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth-1, maxItemSize.Height), ContentAlignment.MiddleCenter);
// align the image
imageRectangle = checkRectangle;
}
else {
checkAndImageMarginWidth = 0;
}
nextPoint.X = checkAndImageMarginWidth+1;
// calculate space for image
// if we didnt have a check - make sure to ignore check padding
// consider: should we constrain to a reasonable width?
//imageMarginBounds = new Rectangle(0, 0, Math.Max(imageMarginWidth,DefaultImageMarginWidth), this.Height);
imageMarginBounds = new Rectangle(0,0,checkAndImageMarginWidth, this.Height);
// calculate space for shortcut and text
nextPoint.X = imageMarginBounds.Right+ TextPadding.Left;
nextPoint.Y = TextPadding.Top;
textRectangle = new Rectangle(nextPoint, maxTextSize);
// calculate space for arrow
nextPoint.X = textRectangle.Right+ TextPadding.Right +ArrowPadding.Left;
nextPoint.Y = ArrowPadding.Top;
arrowRectangle = new Rectangle(nextPoint, maxArrowSize);
// calculate space required for all of these pieces
this.maxItemSize.Width = (arrowRectangle.Right + ArrowPadding.Right) - imageMarginBounds.Left;
this.Padding = DefaultPadding;
int trimPadding = imageMarginBounds.Width;
if (RightToLeft == RightToLeft.Yes) {
// reverse the rectangle alignment in RightToLeft.Yes
trimPadding += TextPadding.Right;
int width = maxItemSize.Width;
checkRectangle.X = width - checkRectangle.Right;
imageRectangle.X = width - imageRectangle.Right;
textRectangle.X = width - textRectangle.Right;
arrowRectangle.X = width - arrowRectangle.Right;
imageMarginBounds.X = width - imageMarginBounds.Right;
}
else {
trimPadding += TextPadding.Left;
}
// VSWhidbey 339274 - we need to make sure that the text really appears vertically centered - this can be a problem in
// systems which force the text rectangle to be odd.
// force this to be an even height.
this.maxItemSize.Height += this.maxItemSize.Height%2;
textRectangle.Y = LayoutUtils.VAlign(textRectangle.Size, new Rectangle(Point.Empty, maxItemSize), ContentAlignment.MiddleCenter).Y;
textRectangle.Y += (textRectangle.Height %2); // if the height is odd, push down by one px, see 339274 for picture
state[stateMaxItemSizeValid]=true;
this.PaddingToTrim = trimPadding;
}
internal override void ChangeSelection(ToolStripItem nextItem) {
if (nextItem != null) {
Rectangle displayRect = DisplayRectangle;
if (!displayRect.Contains(displayRect.X, nextItem.Bounds.Top)
|| !displayRect.Contains(displayRect.X, nextItem.Bounds.Bottom)) {
int delta;
if (displayRect.Y > nextItem.Bounds.Top) {
delta = nextItem.Bounds.Top - displayRect.Y;
}
else {
delta = nextItem.Bounds.Bottom - (displayRect.Y + displayRect.Height);
// Now adjust so that the item at the top isn't truncated.
int index = this.Items.IndexOf(nextItem);
while (index >= 0) {
// we need to roll back to the index which is visible
if ( (this.Items[index].Visible && displayRect.Contains(displayRect.X, this.Items[index].Bounds.Top - delta))
|| !this.Items[index].Visible) {
--index;
}
else {
break;
}
}
if (index >= 0) {
if (displayRect.Contains(displayRect.X, this.Items[index].Bounds.Bottom - delta)) {
// We found an item which is truncated at the top.
delta += (this.Items[index].Bounds.Bottom - delta) - displayRect.Top;
}
}
}
this.ScrollInternal(delta);
this.UpdateScrollButtonStatus();
}
}
base.ChangeSelection(nextItem);
}
protected internal override ToolStripItem CreateDefaultItem(string text, Image image, EventHandler onClick) {
if (text == "-") {
return new ToolStripSeparator();
}
else {
return new ToolStripMenuItem(text,image,onClick);
}
}
internal override ToolStripItem GetNextItem(ToolStripItem start, ArrowDirection direction, bool rtlAware) {
// for up/down we dont care about flipping left/right tab should still take you down.
return GetNextItem(start, direction);
}
internal override void Initialize() {
base.Initialize();
this.Padding = DefaultPadding;
FlowLayoutSettings settings = FlowLayout.CreateSettings(this);
settings.FlowDirection = FlowDirection.TopDown;
state[stateShowImageMargin] = true;
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.OnLayout"]/*' />
protected override void OnLayout(LayoutEventArgs e) {
if (!this.IsDisposed)
{
// We always layout as if we don't need scroll buttons.
// If we do, then we'll adjust the positions to match.
this.RequiresScrollButtons = false;
CalculateInternalLayoutMetrics();
base.OnLayout(e);
if (!this.RequiresScrollButtons) {
this.ResetScrollPosition();
}
}
}
protected override void OnFontChanged(EventArgs e) {
tabWidth = -1;
base.OnFontChanged(e);
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.OnPaintBackground"]/*' />
protected override void OnPaintBackground(PaintEventArgs e) {
base.OnPaintBackground(e);
if (ShowCheckMargin || ShowImageMargin) {
Renderer.DrawImageMargin(new ToolStripRenderEventArgs(e.Graphics, this, this.ImageMargin, SystemColors.Control));
}
}
internal override bool RequiresScrollButtons {
get {
return GetToolStripState(STATE_SCROLLBUTTONS);
}
set {
bool changed = (RequiresScrollButtons != value);
SetToolStripState(STATE_SCROLLBUTTONS, value);
if (changed) {
UpdateScrollButtonLocations();
if (this.Items.Count > 0) {
int delta = this.Items[0].Bounds.Top - this.DisplayRectangle.Top;
this.ScrollInternal(delta);
this.scrollAmount -= delta;
if (value) {
RestoreScrollPosition();
}
}
else {
this.scrollAmount = 0;
}
}
}
}
internal void ResetScrollPosition() {
this.scrollAmount = 0;
}
internal void RestoreScrollPosition() {
if (!RequiresScrollButtons || this.Items.Count == 0) {
return;
}
// We don't just scroll by the amount, because that might
// cause the bottom of the menu to be blank if some items have
// been removed/hidden since the last time we were displayed.
// This also deals with items of different height, so that we don't truncate
// and items under the top scrollbar.
Rectangle displayRectangle = this.DisplayRectangle;
int alreadyScrolled = displayRectangle.Top - this.Items[0].Bounds.Top;
int requiredScrollAmount = this.scrollAmount - alreadyScrolled;
int deltaToScroll = 0;
if (requiredScrollAmount > 0) {
for (int i = 0; i < this.Items.Count && deltaToScroll < requiredScrollAmount; ++i) {
if (this.Items[i].Available) {
Rectangle adjustedLastItemBounds = this.Items[this.Items.Count - 1].Bounds;
adjustedLastItemBounds.Y -= deltaToScroll;
if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top)
&& displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) {
// Scrolling this amount would make the last item visible, so don't scroll any more.
break;
}
// We use a delta between the tops, since it takes margin's and padding into account.
if (i < this.Items.Count - 1) {
deltaToScroll += this.Items[i + 1].Bounds.Top - this.Items[i].Bounds.Top;
}
else {
deltaToScroll += this.Items[i].Bounds.Height;
}
}
}
}
else {
for (int i = this.Items.Count - 1; i >= 0 && deltaToScroll > requiredScrollAmount; --i) {
if (this.Items[i].Available) {
Rectangle adjustedLastItemBounds = this.Items[0].Bounds;
adjustedLastItemBounds.Y -= deltaToScroll;
if (displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Top)
&& displayRectangle.Contains(displayRectangle.X, adjustedLastItemBounds.Bottom)) {
// Scrolling this amount would make the last item visible, so don't scroll any more.
break;
}
// We use a delta between the tops, since it takes margin's and padding into account.
if (i > 0) {
deltaToScroll -= this.Items[i].Bounds.Top - this.Items[i - 1].Bounds.Top;
}
else {
deltaToScroll -= this.Items[i].Bounds.Height;
}
}
}
}
this.ScrollInternal(deltaToScroll);
this.scrollAmount = this.DisplayRectangle.Top - this.Items[0].Bounds.Top;
UpdateScrollButtonLocations();
}
internal override void ScrollInternal(int delta) {
base.ScrollInternal(delta);
this.scrollAmount += delta;
}
internal void ScrollInternal(bool up) {
UpdateScrollButtonStatus();
// calling this to get ScrollWindowEx. In actuality it does nothing
// to change the display rect!
int delta;
if (this.indexOfFirstDisplayedItem == -1 || this.indexOfFirstDisplayedItem >= this.Items.Count) {
Debug.Fail("Why wasn't 'UpdateScrollButtonStatus called'? We don't have the item to scroll by");
int menuHeight = SystemInformation.MenuHeight;
delta = up ? -menuHeight : menuHeight;
}
else {
if (up) {
if (this.indexOfFirstDisplayedItem == 0) {
Debug.Fail("We're trying to scroll up, but the top item is displayed!!!");
delta = 0;
}
else {
ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem - 1];
ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem];
// We use a delta between the tops, since it takes margin's and padding into account.
delta = itemTop.Bounds.Top - itemBottom.Bounds.Top;
}
}
else {
if (this.indexOfFirstDisplayedItem == this.Items.Count - 1) {
Debug.Fail("We're trying to scroll down, but the top item is displayed!!!");
delta = 0;
}
ToolStripItem itemTop = this.Items[this.indexOfFirstDisplayedItem];
ToolStripItem itemBottom = this.Items[this.indexOfFirstDisplayedItem + 1];
// We use a delta between the tops, since it takes margin's and padding into account.
delta = itemBottom.Bounds.Top - itemTop.Bounds.Top;
}
}
ScrollInternal(delta);
UpdateScrollButtonLocations();
}
/// <include file='doc\ToolStripDropDownMenu.uex' path='docs/doc[@for="ToolStripDropDownMenu.SetDisplayedItems"]/*' />
protected override void SetDisplayedItems() {
base.SetDisplayedItems();
if (RequiresScrollButtons) {
this.DisplayedItems.Add(UpScrollButton);
this.DisplayedItems.Add(DownScrollButton);
UpdateScrollButtonLocations();
UpScrollButton.Visible = true;
DownScrollButton.Visible = true;
}
else {
UpScrollButton.Visible = false;
DownScrollButton.Visible = false;
}
}
private void UpdateScrollButtonLocations() {
if (GetToolStripState(STATE_SCROLLBUTTONS)) {
Size upSize = UpScrollButton.GetPreferredSize(Size.Empty);
//
Point upLocation = new Point(1, 0);
UpScrollButton.SetBounds(new Rectangle(upLocation, upSize));
Size downSize = DownScrollButton.GetPreferredSize(Size.Empty);
int height = GetDropDownBounds(this.Bounds).Height;
Point downLocation = new Point(1, height - downSize.Height);
DownScrollButton.SetBounds(new Rectangle(downLocation, downSize));
UpdateScrollButtonStatus();
}
}
private void UpdateScrollButtonStatus() {
Rectangle displayRectangle = this.DisplayRectangle;
this.indexOfFirstDisplayedItem = -1;
int minY = int.MaxValue, maxY = 0;
for (int i = 0; i < this.Items.Count; ++i) {
ToolStripItem item = this.Items[i];
if (UpScrollButton == item) {
continue;
}
if (DownScrollButton == item) {
continue;
}
if (!item.Available) {
continue;
}
if (this.indexOfFirstDisplayedItem == -1 && displayRectangle.Contains(displayRectangle.X, item.Bounds.Top)) {
this.indexOfFirstDisplayedItem = i;
}
minY = Math.Min(minY, item.Bounds.Top);
maxY = Math.Max(maxY, item.Bounds.Bottom);
}
UpScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, minY);
DownScrollButton.Enabled = !displayRectangle.Contains(displayRectangle.X, maxY);
}
internal sealed class ToolStripDropDownLayoutEngine : FlowLayout {
public static ToolStripDropDownLayoutEngine LayoutInstance = new ToolStripDropDownLayoutEngine();
internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) {
Size preferredSize = base.GetPreferredSize(container, proposedConstraints);
ToolStripDropDownMenu dropDownMenu = container as ToolStripDropDownMenu;
if (dropDownMenu != null) {
preferredSize.Width = dropDownMenu.MaxItemSize.Width - dropDownMenu.PaddingToTrim;
}
return preferredSize;
}
}
}
}
| {
"content_hash": "2827259affed9a52b835b3270dd83ce3",
"timestamp": "",
"source": "github",
"line_count": 816,
"max_line_length": 225,
"avg_line_length": 48.745098039215684,
"alnum_prop": 0.5206154465004023,
"repo_name": "mind0n/hive",
"id": "d89b2dd7890d703c912671db282f77c558b49acc",
"size": "39776",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Cache/Libs/net46/ndp/fx/src/winforms/Managed/System/WinForms/ToolStripDropDownMenu.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "670329"
},
{
"name": "ActionScript",
"bytes": "7830"
},
{
"name": "ApacheConf",
"bytes": "47"
},
{
"name": "Batchfile",
"bytes": "18096"
},
{
"name": "C",
"bytes": "19746409"
},
{
"name": "C#",
"bytes": "258148996"
},
{
"name": "C++",
"bytes": "48534520"
},
{
"name": "CSS",
"bytes": "933736"
},
{
"name": "ColdFusion",
"bytes": "10780"
},
{
"name": "GLSL",
"bytes": "3935"
},
{
"name": "HTML",
"bytes": "4631854"
},
{
"name": "Java",
"bytes": "10881"
},
{
"name": "JavaScript",
"bytes": "10250558"
},
{
"name": "Logos",
"bytes": "1526844"
},
{
"name": "MAXScript",
"bytes": "18182"
},
{
"name": "Mathematica",
"bytes": "1166912"
},
{
"name": "Objective-C",
"bytes": "2937200"
},
{
"name": "PHP",
"bytes": "81898"
},
{
"name": "Perl",
"bytes": "9496"
},
{
"name": "PowerShell",
"bytes": "44339"
},
{
"name": "Python",
"bytes": "188058"
},
{
"name": "Shell",
"bytes": "758"
},
{
"name": "Smalltalk",
"bytes": "5818"
},
{
"name": "TypeScript",
"bytes": "50090"
}
],
"symlink_target": ""
} |
import { Party } from "./party";
import { Code } from "./code";
import { TransportMeans } from "./transport-means";
export class ShipmentStage {
constructor(
public transportModeCode: Code = new Code(),
public carrierParty: Party = new Party(),
public transportMeans: TransportMeans = new TransportMeans(),
public estimatedDeliveryDate: string = null
) { }
}
| {
"content_hash": "1c68a6f58e9ea1d5e340c50701b3492c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 69,
"avg_line_length": 30.846153846153847,
"alnum_prop": 0.6583541147132169,
"repo_name": "nimble-platform/frontend-service",
"id": "fb2e30f436c30b0666795974e20e00faf904d4a3",
"size": "1044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/catalogue/model/publish/shipment-stage.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "135821"
},
{
"name": "Dockerfile",
"bytes": "369"
},
{
"name": "HTML",
"bytes": "1305632"
},
{
"name": "JavaScript",
"bytes": "8243"
},
{
"name": "Shell",
"bytes": "1721"
},
{
"name": "TypeScript",
"bytes": "2729038"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (11.0.9) on Wed Oct 28 16:08:27 UTC 2020 -->
<title>AWTPolygonProducer (mxGraph 4.2.2 API Specification)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-10-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../jquery/jquery-3.5.1.js"></script>
<script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="AWTPolygonProducer (mxGraph 4.2.2 API Specification)";
}
}
catch(err) {
}
//-->
var data = {"i0":9,"i1":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AWTPolygonProducer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><p><b>mxGraph 4.2.2</b></p></div>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<!-- ======== START OF CLASS DATA ======== -->
<main role="main">
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="package-summary.html">com.mxgraph.util.svg</a></div>
<h2 title="Class AWTPolygonProducer" class="title">Class AWTPolygonProducer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">com.mxgraph.util.svg.AWTPolylineProducer</a></li>
<li>
<ul class="inheritance">
<li>com.mxgraph.util.svg.AWTPolygonProducer</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><code><a href="PointsHandler.html" title="interface in com.mxgraph.util.svg">PointsHandler</a></code>, <code><a href="ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></code></dd>
</dl>
<hr>
<pre>public class <span class="typeNameLabel">AWTPolygonProducer</span>
extends <a href="AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></pre>
<div class="block">This class produces a polygon shape from a reader.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a id="fields.inherited.from.class.com.mxgraph.util.svg.AWTPolylineProducer">
<!-- -->
</a>
<h3>Fields inherited from class com.mxgraph.util.svg.<a href="AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></h3>
<code><a href="AWTPolylineProducer.html#newPath">newPath</a>, <a href="AWTPolylineProducer.html#path">path</a>, <a href="AWTPolylineProducer.html#windingRule">windingRule</a></code></li>
</ul>
</li>
</ul>
</section>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="#%3Cinit%3E()">AWTPolygonProducer</a></span>()</code></th>
<td class="colLast"> </td>
</tr>
</table>
</li>
</ul>
</section>
<!-- ========== METHOD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static java.awt.Shape</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#createShape(java.lang.String,int)">createShape</a></span>​(java.lang.String text,
int wr)</code></th>
<td class="colLast">
<div class="block">Utility method for creating an ExtendedGeneralPath.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#endPoints()">endPoints</a></span>()</code></th>
<td class="colLast">
<div class="block">Implements <a href="PointsHandler.html#endPoints()"><code>PointsHandler.endPoints()</code></a>.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.com.mxgraph.util.svg.AWTPolylineProducer">
<!-- -->
</a>
<h3>Methods inherited from class com.mxgraph.util.svg.<a href="AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></h3>
<code><a href="AWTPolylineProducer.html#getShape()">getShape</a>, <a href="AWTPolylineProducer.html#getWindingRule()">getWindingRule</a>, <a href="AWTPolylineProducer.html#point(float,float)">point</a>, <a href="AWTPolylineProducer.html#setWindingRule(int)">setWindingRule</a>, <a href="AWTPolylineProducer.html#startPoints()">startPoints</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a id="<init>()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>AWTPolygonProducer</h4>
<pre>public AWTPolygonProducer()</pre>
</li>
</ul>
</li>
</ul>
</section>
<!-- ============ METHOD DETAIL ========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a id="createShape(java.lang.String,int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>createShape</h4>
<pre class="methodSignature">public static java.awt.Shape createShape​(java.lang.String text,
int wr)
throws <a href="ParseException.html" title="class in com.mxgraph.util.svg">ParseException</a></pre>
<div class="block">Utility method for creating an ExtendedGeneralPath.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>text</code> - The text representation of the path specification.</dd>
<dd><code>wr</code> - The winding rule to use for creating the path.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="ParseException.html" title="class in com.mxgraph.util.svg">ParseException</a></code></dd>
</dl>
</li>
</ul>
<a id="endPoints()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>endPoints</h4>
<pre class="methodSignature">public void endPoints()
throws <a href="ParseException.html" title="class in com.mxgraph.util.svg">ParseException</a></pre>
<div class="block">Implements <a href="PointsHandler.html#endPoints()"><code>PointsHandler.endPoints()</code></a>.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="PointsHandler.html#endPoints()">endPoints</a></code> in interface <code><a href="PointsHandler.html" title="interface in com.mxgraph.util.svg">PointsHandler</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="AWTPolylineProducer.html#endPoints()">endPoints</a></code> in class <code><a href="AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></code></dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="ParseException.html" title="class in com.mxgraph.util.svg">ParseException</a></code> - if an error occured while processing the
points</dd>
</dl>
</li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
</div>
</main>
<!-- ========= END OF CLASS DATA ========= -->
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AWTPolygonProducer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><p><b>mxGraph 4.2.2</b></p></div>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small><font size=1>Copyright (c) 2010-2017 <a href="http://www.jgraph.com/"
target="_blank">Gaudenz Alder, JGraph Ltd</a>. All rights reserved.</font></small></p>
</footer>
</body>
</html>
| {
"content_hash": "52dab205032ac2256c7f62ff62eaac85",
"timestamp": "",
"source": "github",
"line_count": 384,
"max_line_length": 524,
"avg_line_length": 37.364583333333336,
"alnum_prop": 0.6506830220239754,
"repo_name": "jgraph/mxgraph",
"id": "a7528f24c58080ab9934fed9052c516293d88bb4",
"size": "14348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/docs/com/mxgraph/util/svg/AWTPolygonProducer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "19603"
},
{
"name": "C#",
"bytes": "637723"
},
{
"name": "CSS",
"bytes": "105870"
},
{
"name": "HTML",
"bytes": "12279178"
},
{
"name": "Java",
"bytes": "2378617"
},
{
"name": "JavaScript",
"bytes": "5982641"
}
],
"symlink_target": ""
} |
<?php
namespace SoflomoTest\Mail\Service;
use PHPUnit_Framework_TestCase as TestCase;
use Soflomo\Mail\Module;
use Zend\Loader;
class ModuleTest extends TestCase
{
public function testModuleProvidesConfig()
{
$module = new Module;
$config = $module->getConfig();
$this->assertEquals('array', gettype($config));
}
public function testModuleAutoloader()
{
$module = new Module;
$actual = $module->getAutoloaderConfig();
$expected = [
Loader\AutoloaderFactory::STANDARD_AUTOLOADER => [
Loader\StandardAutoloader::LOAD_NS => [
'Soflomo\Mail' => realpath(__DIR__ . '/../../../src/Mail') . '/',
],
],
];
$this->assertEquals($expected, $actual);
}
}
| {
"content_hash": "d21a680c90f69875daff1505becc3b29",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 85,
"avg_line_length": 24.757575757575758,
"alnum_prop": 0.5630354957160343,
"repo_name": "juriansluiman/Soflomo-Mail",
"id": "48e35f9bf995ef7c34dd8ebda3cc8e0bd083e25a",
"size": "2593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/SoflomoTest/Mail/ModuleTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "110598"
}
],
"symlink_target": ""
} |
<div class='fossil-doc' data-title='coroutine::auto - Coroutine utilities'>
<style>
HTML {
background: #FFFFFF;
color: black;
}
BODY {
background: #FFFFFF;
color: black;
}
DIV.doctools {
margin-left: 10%;
margin-right: 10%;
}
DIV.doctools H1,DIV.doctools H2 {
margin-left: -5%;
}
H1, H2, H3, H4 {
margin-top: 1em;
font-family: sans-serif;
font-size: large;
color: #005A9C;
background: transparent;
text-align: left;
}
H1.doctools_title {
text-align: center;
}
UL,OL {
margin-right: 0em;
margin-top: 3pt;
margin-bottom: 3pt;
}
UL LI {
list-style: disc;
}
OL LI {
list-style: decimal;
}
DT {
padding-top: 1ex;
}
UL.doctools_toc,UL.doctools_toc UL, UL.doctools_toc UL UL {
font: normal 12pt/14pt sans-serif;
list-style: none;
}
LI.doctools_section, LI.doctools_subsection {
list-style: none;
margin-left: 0em;
text-indent: 0em;
padding: 0em;
}
PRE {
display: block;
font-family: monospace;
white-space: pre;
margin: 0%;
padding-top: 0.5ex;
padding-bottom: 0.5ex;
padding-left: 1ex;
padding-right: 1ex;
width: 100%;
}
PRE.doctools_example {
color: black;
background: #f5dcb3;
border: 1px solid black;
}
UL.doctools_requirements LI, UL.doctools_syntax LI {
list-style: none;
margin-left: 0em;
text-indent: 0em;
padding: 0em;
}
DIV.doctools_synopsis {
color: black;
background: #80ffff;
border: 1px solid black;
font-family: serif;
margin-top: 1em;
margin-bottom: 1em;
}
UL.doctools_syntax {
margin-top: 1em;
border-top: 1px solid black;
}
UL.doctools_requirements {
margin-bottom: 1em;
border-bottom: 1px solid black;
}
</style>
<hr> [
<a href="../../../../toc.html">Main Table Of Contents</a>
| <a href="../../../toc.html">Table Of Contents</a>
| <a href="../../../../index.html">Keyword Index</a>
| <a href="../../../../toc0.html">Categories</a>
| <a href="../../../../toc1.html">Modules</a>
| <a href="../../../../toc2.html">Applications</a>
] <hr>
<div class="doctools">
<h1 class="doctools_title">coroutine::auto(n) 1.1.3 tcllib "Coroutine utilities"</h1>
<div id="name" class="doctools_section"><h2><a name="name">Name</a></h2>
<p>coroutine::auto - Automatic event and IO coroutine awareness</p>
</div>
<div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2>
<ul class="doctools_toc">
<li class="doctools_section"><a href="#toc">Table Of Contents</a></li>
<li class="doctools_section"><a href="#synopsis">Synopsis</a></li>
<li class="doctools_section"><a href="#section1">Description</a></li>
<li class="doctools_section"><a href="#section2">Bugs, Ideas, Feedback</a></li>
<li class="doctools_section"><a href="#keywords">Keywords</a></li>
<li class="doctools_section"><a href="#category">Category</a></li>
<li class="doctools_section"><a href="#copyright">Copyright</a></li>
</ul>
</div>
<div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2>
<div class="doctools_synopsis">
<ul class="doctools_requirements">
<li>package require <b class="pkgname">Tcl 8.6</b></li>
<li>package require <b class="pkgname">coroutine::auto 1.1.3</b></li>
<li>package require <b class="pkgname">coroutine 1.1</b></li>
</ul>
</div>
</div>
<div id="section1" class="doctools_section"><h2><a name="section1">Description</a></h2>
<p>The <b class="package">coroutine::auto</b> package provides no commands or other
directly visible functionality.
Built on top of the package <b class="package"><a href="tcllib_coroutine.html">coroutine</a></b>, it intercepts various
builtin commands of the Tcl core to make any code using them
coroutine-oblivious, i.e. able to run inside and outside of a
coroutine without changes.</p>
<p>The commands so affected by this package are</p>
<dl class="doctools_definitions">
<dt><b class="cmd"><a href="../../../../index.html#key413">after</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key414">exit</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key415">gets</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key412">global</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key410">read</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key416">update</a></b></dt>
<dd></dd>
<dt><b class="cmd"><a href="../../../../index.html#key417">vwait</a></b></dt>
<dd></dd>
</dl>
</div>
<div id="section2" class="doctools_section"><h2><a name="section2">Bugs, Ideas, Feedback</a></h2>
<p>This document, and the package it describes, will undoubtedly contain
bugs and other problems.
Please report such in the category <em>coroutine</em> of the
<a href="http://core.tcl.tk/tcllib/reportlist">Tcllib Trackers</a>.
Please also report any ideas for enhancements you may have for either
package and/or documentation.</p>
</div>
<div id="keywords" class="doctools_section"><h2><a name="keywords">Keywords</a></h2>
<p><a href="../../../../index.html#key413">after</a>, <a href="../../../../index.html#key63">channel</a>, <a href="../../../../index.html#key219">coroutine</a>, <a href="../../../../index.html#key411">events</a>, <a href="../../../../index.html#key414">exit</a>, <a href="../../../../index.html#key415">gets</a>, <a href="../../../../index.html#key412">global</a>, <a href="../../../../index.html#key418">green threads</a>, <a href="../../../../index.html#key410">read</a>, <a href="../../../../index.html#key409">threads</a>, <a href="../../../../index.html#key416">update</a>, <a href="../../../../index.html#key417">vwait</a></p>
</div>
<div id="category" class="doctools_section"><h2><a name="category">Category</a></h2>
<p>Coroutine</p>
</div>
<div id="copyright" class="doctools_section"><h2><a name="copyright">Copyright</a></h2>
<p>Copyright © 2010-2014 Andreas Kupries <andreas_kupries@users.sourceforge.net></p>
</div>
</div>
| {
"content_hash": "75f8c5e5aebc3fd336ea6e4eeea1f8a5",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 632,
"avg_line_length": 35.81437125748503,
"alnum_prop": 0.6316669453268684,
"repo_name": "neverpanic/macports-base",
"id": "755260f95705991ed28cda5fb04c2bb89989f44f",
"size": "5982",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/tcllib-1.18/embedded/www/tcllib/files/modules/coroutine/coro_auto.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1021718"
},
{
"name": "M4",
"bytes": "92664"
},
{
"name": "Makefile",
"bytes": "27709"
},
{
"name": "Rich Text Format",
"bytes": "6806"
},
{
"name": "Shell",
"bytes": "39105"
},
{
"name": "Tcl",
"bytes": "1504725"
}
],
"symlink_target": ""
} |
package app.coolweather.com.coolweather.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import app.coolweather.com.coolweather.R;
import app.coolweather.com.coolweather.model.City;
import app.coolweather.com.coolweather.model.CoolWeatherDB;
import app.coolweather.com.coolweather.model.County;
import app.coolweather.com.coolweather.model.Province;
import app.coolweather.com.coolweather.util.HttpCallbackListener;
import app.coolweather.com.coolweather.util.HttpUtil;
import app.coolweather.com.coolweather.util.Utility;
/**
* Created by Ghost on 2016/5/16.
*/
public class ChooseAreaActivity extends Activity {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList = new ArrayList<String>();
/**
* ็ๅ่กจ
*/
private List<Province> provinceList;
/**
* ๅธๅ่กจ
*/
private List<City> cityList;
/**
* ๅฟๅ่กจ
*/
private List<County> countyList;
/**
* ้ไธญ็็ไปฝ
*/
private Province selectedProvince;
/**
* ้ไธญ็ๅๅธ
*/
private City selectedCity;
/**
* ๅฝๅ้ไธญ็็บงๅซ
*/
private int currentLevel;
/**
* ๆฏๅฆไปWeatherActivity ไธญ่ทณ่ฝฌ่ฟๆฅใ
*/
private boolean isFromWeatherActivity;
private long exitTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// ๅทฒ็ป้ๆฉไบๅๅธไธไธๆฏไปWeatherActivity ่ทณ่ฝฌ่ฟๆฅ๏ผๆไผ็ดๆฅ่ทณ่ฝฌๅฐWeatherActivity
if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(index);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(index);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String countyCode = countyList.get(index).getCountyCode();
Intent intent = new Intent(ChooseAreaActivity.this,
WeatherActivity.class);
intent.putExtra("county_code", countyCode);
startActivity(intent);
finish();
}
}
});
queryProvinces(); // ๅ ่ฝฝ็็บงๆฐๆฎ
}
/**
* ๆฅ่ฏขๅ
จๅฝๆๆ็็๏ผไผๅ
ไปๆฐๆฎๅบๆฅ่ฏข๏ผๅฆๆๆฒกๆๆฅ่ฏขๅฐๅๅปๆๅกๅจไธๆฅ่ฏขใ
*/
private void queryProvinces() {
provinceList = coolWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("ไธญๅฝ");
currentLevel = LEVEL_PROVINCE;
} else {
queryFromServer(null, "province");
}
}
/**
* ๆฅ่ฏข้ไธญ็ๅ
ๆๆ็ๅธ๏ผไผๅ
ไปๆฐๆฎๅบๆฅ่ฏข๏ผๅฆๆๆฒกๆๆฅ่ฏขๅฐๅๅปๆๅกๅจไธๆฅ่ฏขใ
*/
private void queryCities() {
cityList = coolWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
} else {
queryFromServer(selectedProvince.getProvinceCode(), "city");
}
}
/**
* ๆฅ่ฏข้ไธญๅธๅ
ๆๆ็ๅฟ๏ผไผๅ
ไปๆฐๆฎๅบๆฅ่ฏข๏ผๅฆๆๆฒกๆๆฅ่ฏขๅฐๅๅปๆๅกๅจไธๆฅ่ฏขใ
*/
private void queryCounties() {
countyList = coolWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
} else {
queryFromServer(selectedCity.getCityCode(), "county");
}
}
/**
* ๆ นๆฎไผ ๅ
ฅ็ไปฃๅทๅ็ฑปๅไปๆๅกๅจไธๆฅ่ฏข็ๅธๅฟๆฐๆฎใ
*/
private void queryFromServer(final String code, final String type) {
String address;
if (!TextUtils.isEmpty(code)) {
address = "http://www.weather.com.cn/data/list3/city" + code +
".xml";
} else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvincesResponse(coolWeatherDB,
response);
} else if ("city".equals(type)) {
result = Utility.handleCitiesResponse(coolWeatherDB,
response, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountiesResponse(coolWeatherDB,
response, selectedCity.getId());
}
if (result) {
// ้่ฟrunOnUiThread()ๆนๆณๅๅฐไธป็บฟ็จๅค็้ป่พ
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onError(Exception e) {
// ้่ฟrunOnUiThread()ๆนๆณๅๅฐไธป็บฟ็จๅค็้ป่พ
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this,
"ๅ ่ฝฝๅคฑ่ดฅ", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* ๆพ็คบ่ฟๅบฆๅฏน่ฏๆก
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("ๆญฃๅจๅ ่ฝฝ...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* ๅ
ณ้ญ่ฟๅบฆๅฏน่ฏๆก
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
/**
* ๆ่ทBackๆ้ฎ๏ผๆ นๆฎๅฝๅ็็บงๅซๆฅๅคๆญ๏ผๆญคๆถๅบ่ฏฅ่ฟๅๅธๅ่กจใ็ๅ่กจใ่ฟๆฏ็ดๆฅ้ๅบใ
*/
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else if (currentLevel == LEVEL_PROVINCE){
if((System.currentTimeMillis()-exitTime) > 2000){
Toast.makeText(this,"ๅๆไธๆฌก้ๅบ็จๅบ",Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
}else {
finish();
}
} else {
if (isFromWeatherActivity) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
}
finish();
}
}
}
| {
"content_hash": "8c2358f3ed58f1c8ee18c6a5bc4f1b9a",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 96,
"avg_line_length": 34.37090909090909,
"alnum_prop": 0.559775708844689,
"repo_name": "GentleSadness/coolweather",
"id": "de9322120f0da6096a9905474750b9c16fb939da",
"size": "10028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/app/coolweather/com/coolweather/activity/ChooseAreaActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "36598"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Perrouse est
un village
gรฉographiquement positionnรฉ dans le dรฉpartement de Haute-Saรดne en Franche-Comtรฉ. Elle totalisait 206 habitants en 2008.</p>
<p>ร cotรฉ de Perrouse sont positionnรฉes gรฉographiquement les communes de
<a href="{{VLROOT}}/immobilier/devecey_25200/">Devecey</a> ร 4 km, 1 439 habitants,
<a href="{{VLROOT}}/immobilier/palise_25444/">Palise</a> localisรฉe ร 3 km, 111 habitants,
<a href="{{VLROOT}}/immobilier/buthiers_70109/">Buthiers</a> ร 2 km, 312 habitants,
<a href="{{VLROOT}}/immobilier/aulx-les-cromary_70036/">Aulx-lรจs-Cromary</a> situรฉe ร 4 km, 150 habitants,
<a href="{{VLROOT}}/immobilier/boult_70085/">Boult</a> situรฉe ร 4 km, 519 habitants,
<a href="{{VLROOT}}/immobilier/merey-vieilley_25376/">Mรฉrey-Vieilley</a> ร 3 km, 100 habitants,
entre autres. De plus, Perrouse est situรฉe ร seulement treize km de <a href="{{VLROOT}}/immobilier/besanรงon_25056/">Besanรงon</a>.</p>
<p>Le parc d'habitations, ร Perrouse, รฉtait rรฉparti en 2011 en 16 appartements et 88 maisons soit
un marchรฉ plutรดt รฉquilibrรฉ.</p>
<p>Si vous pensez emmenager ร Perrouse, vous pourrez facilement trouver une maison ร vendre. </p>
<p>La commune offre quelques รฉquipements, elle propose entre autres un terrain de sport.</p>
</div>
| {
"content_hash": "d54c83e177cbf93d0bb682315ab3bea4",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 139,
"avg_line_length": 73.77777777777777,
"alnum_prop": 0.7379518072289156,
"repo_name": "donaldinou/frontend",
"id": "0ab1d0306c5a17a3330ccff081678b630ed4df31",
"size": "1362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/70407.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
layout: post
title: go lang, komut satฤฑrฤฑ aracฤฑ
categories:
- go
---
go dili gรผรงlรผ bir komut satฤฑrฤฑ aracฤฑ ile gelmektedir. ลimdi teker teker bu komutlarฤฑn ne iลe yaradฤฑklarฤฑna bakalฤฑm.
terminalinizden (kabuk, shell, artฤฑk ne diyorsanฤฑz :) `go` komutunu รงalฤฑลtฤฑrdฤฑฤฤฑnฤฑzda aลaฤฤฑdaki gibi bir รงฤฑktฤฑ alacaksฤฑnฤฑz.
{% highlight sh %}
โ alioygur.github.io git:(master) go
Go is a tool for managing Go source code.
Usage:
go command [arguments]
The commands are:
build compile packages and dependencies
clean remove object files
env print Go environment information
fix run go tool fix on packages
fmt run gofmt on package sources
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet run go tool vet on packages
Use "go help [command]" for more information about a command.
Additional help topics:
c calling between Go and C
gopath GOPATH environment variable
importpath import path syntax
packages description of package lists
testflag description of testing flags
testfunc description of testing functions
Use "go help [topic]" for more information about that topic.
{% endhighlight %}
bu `go` ya ait alt komutlarฤฑ ve nasฤฑl kullanabileceฤimizi kฤฑsaca รถzetlemektedir. ลimdi bakalฤฑm,
## go build
Go paketlerini derlemek iรงin kullanฤฑlan komuttur. Eฤer gerektiฤi durumlarda baฤฤฑmlฤฑ olan paketleride otomatik derler.
- Eฤer paket `main` deฤilde, bรถlรผm 1.2 deki gibi `mymath` ise, `go build` รงalฤฑลtฤฑฤฤฑnda hiรง birลey oluลturulmayacak. Eฤer `$GOPATH/pkg` iรงinde `.a` uzantฤฑlฤฑ derlemiล haline istiyorsanฤฑz, `go install` komutunu kullanabilirsiniz.
- Eฤer paket `main` ise, aynฤฑ dizin iรงinde รงalฤฑลtฤฑrฤฑlabilir haline oluลturcaktฤฑr. Eฤer oluลacak dosyanฤฑn `$GOPATH/bin` iรงinde olmasฤฑnฤฑ istiyorsanฤฑz, `go install` ya da `go build -o ${DฤฐZฤฐN_YOLU}/a.exe` olarak รงalฤฑลtฤฑrฤฑn.
- Dizinde birden fazla go dosyasฤฑ varsa, ve sadece birini derlemek istiyorsanฤฑz, `go build` komutuna dosya ismini argรผman olarak vermelisiniz. รrneฤin, `go build a.go`. `go build` argรผman almaz ise dizindeki bรผtรผm dosyalarฤฑ derleyecektir.
- Oluลacak dosyanฤฑn isminide รถnceden belirieyebilirsiniz. รrneฤin, `mathapp` projesinde (bรถlรผm 1.2'deki), `go build -o astaxie.exe` komutu `mathapp.exe` yerine `astaxie.exe` adฤฑnda bir dosya oluลturacaktฤฑr. รntanฤฑmlฤฑ isimlendirme ya dizin ismi ya da ilk kaynak kodu iรงeren dosya ismi olarak seรงilmiลtir.
( [Go Programlama Dili Kฤฑlavuzu](https://golang.org/ref/spec)'na gรถre , paket isimleri `package` anahtar kelimesinden sonra kaynak dosyanฤฑn ilk satฤฑrฤฑna yazฤฑlmalฤฑdฤฑr. Dizin ismi ile aynฤฑ olmasฤฑ zorunlu deฤildir, รงalฤฑลtฤฑrฤฑlabilir dosyanฤฑn ismi dizin ismi olacaktฤฑr.])
- `go build`, `_` ya da `.` ile baลlayan dosyalarฤฑ gรถrmezden gelir.
- Her iลletim sistemi iรงin ayrฤฑ dosyalar tutmak isterseniz, iลletim sistemi ismini ek olarak kullanabilirsiniz. รrneฤin, `array.go`'yu farklฤฑ sistemler iรงin yazacaksanฤฑz. Dosya isimleri aลaฤฤฑdaki gibi olabilir:
array_linux.go | array_darwin.go | array_windows.go | array_freebsd.go
`go build` iลletim sisteminize gรถre derleme iลlemini yapacaktฤฑr. รrneฤin, Linux kullanฤฑyorsanฤฑz sadece array_linux.go derleyip, diฤerlerini yoksayacaktฤฑr.
## go clean
Derleyici tarafฤฑndan oluลturulmuล aลaฤฤฑdaki dosyalarฤฑ temizler:
_obj/ // eski obje klasรถrรผ, Makefiles tarafฤฑndan oluลturulmuล
_test/ // eksi test klasรถrรผ, Makefiles tarafฤฑndan oluลturulmuล
_testmain.go // eski gotest dizini, Makefiles tarafฤฑndan oluลturulmuล
test.out // eski test dizini, Makefiles tarafฤฑndan oluลturulmuล
build.out // eksi test dizini, Makefiles tarafฤฑndan oluลturulmuล
*.[568ao] // obje dosyalarฤฑ, Makefiles tarafฤฑndan oluลturulmuล
DIR(.exe) // go build tarafฤฑdan oluลturulmuล
DIR.test(.exe) // go test -c tarafฤฑndan oluลturulmuล
MAINFILE(.exe) // go build MAINFILE.go tarafฤฑndan oluลturulmuล
Projelerimi Github'a gรถndermeden รถnce genellikle bu komutu รงalฤฑลtฤฑrฤฑrฤฑm. Yereldeki testler iรงin รถnemli, ama sรผrรผm takip iรงin gereksiz dosyalar.
## go fmt
รncede C/C++ ile รงalฤฑลmฤฑล olanlar, hangi kodlama stilinin daha iyi olduฤu konusundaki tartฤฑลmlarฤฑ biliyordur: K&R-stili ya da ANSI-stili. Go da ise, herkesin kullanmak zorunda olduฤu sadece bir kod stili vardฤฑr. รrneฤin, aรงma parantezleri satฤฑr sonlarฤฑnฤฑ yazฤฑlmalฤฑdฤฑr, yeni bir satฤฑrda yazฤฑlamazlar, eฤer bu kurala uymazsanฤฑz derleme hatasฤฑ alacaksฤฑnฤฑz! Neyse ki, bu kurallarฤฑ ezberlemek zorunda deฤilsiniz. `go fmt` bu iลi sizin yerinize yapacaktฤฑr. Terminalinizde `go fmt <dosya_ismi>.go` komutunu รงalฤฑลtฤฑrmanฤฑz yetecektir. Bir รงok IDE siz dosyayฤฑ kaydettiฤinizde otomatik olarak bu komutu รงalฤฑลtฤฑracaktฤฑr. IDE'ler hakkฤฑnda bir sonraki bรถlรผmde daha ayrฤฑntฤฑlฤฑ bilgi vereceฤim.
`gofmt` ลeklind deฤilde `go fmt -w` ลeklinde kullanmanฤฑz daha iyi olcaktฤฑr. `-w` parametresi formatladฤฑktan sonra deฤiลiklikleri kaydetcektir. `gofmt -w src` ise src altฤฑndaki butun dosyalarฤฑ formatlar.
## go get
Bu komut รผรงรผncรผ parti paketleri almanฤฑzฤฑ saฤlar. ลuanda; BitBucket, Github, Google Code ve Launchpad desteฤi sunuyor. Bu komutu รงalฤฑลtฤฑrdฤฑฤฤฑmฤฑzda iki ลey yapฤฑlฤฑyor. Birincisi Go kaynak kodunu indiriyor, ikinci olarakta `go install` komutunu รงalฤฑลtฤฑrฤฑyor. Bu komutu รงalฤฑลtฤฑrmadan รถnce, gerekli araรงlarฤฑ kurudฤunuzdan emin olun.
BitBucket (Mercurial Git)
Github (git)
Google Code (Git, Mercurial, Subversion)
Launchpad (Bazaar)
Bu komutu kullanmak iรงin, yukarฤฑdaki araรงlarฤฑ kurmuล olmanฤฑz lazฤฑm. `$PATH` deฤiลkenini ayarlamayฤฑda unutmayฤฑn. Bu arada, รถzel alan adlarฤฑnฤฑda destekliyor. `go help remote` komutu ile daha ayrฤฑntฤฑlฤฑ bilgi edinebilrsiniz.
## go install
Bu komut bรผtรผn paketleri derleyip oluลan dosyalarฤฑ, `$GOPATH/pkg` ya da `$GOPATH/bin` altฤฑna taลฤฑr.
## go test
Bu komut `*_test.go` ile biten dosyalarฤฑ derleyip รงalฤฑลtฤฑrฤฑr, gerekli bilgileri ekrana basar.
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
รntanฤฑmlฤฑ olarak bรผtรผn test dosyalarฤฑnฤฑ รงalฤฑลtฤฑrฤฑr. `go help testflag` komutunu kullanarak daha ayrฤฑntฤฑlฤฑ bilgi elde edebilirsiniz.
## go doc
Bir รงok insan Go iรงin รผรงรผncรผ parti bir dรถkรผmantasyona aracฤฑna gerek olamdฤฑฤฤฑnฤฑ dรผลรผnรผyor (aslฤฑna bakarsanฤฑz ben bir tane yazdฤฑm bile [CHM](https://github.com/astaxie/godoc)). Go dรถkรผmanlarฤฑ yรถnetmek iรงin รงok gรผรงlรผ bir araca sahip.
Peki bir paketin dรถkรผmantasyonuna nasฤฑl bakabiliriz? รrneฤin, Eฤer bir `builtin` paket hakkฤฑnda daha fazla bilgi istiyorsanฤฑz, `go doc builtin` komutunu iลinizi gรถrecektir. Benzer ลekilde, `go doc net/http` komutu ile `http` paketi hakkฤฑnda bilgi elde edebilirsiniz. Fonksiyonlar hakkฤฑnda daha ayrฤฑntฤฑlฤฑ bilgi istiyorsanฤฑz, `godoc fmt Printf` ve `godoc -src fmt Printf` komutlarฤฑ iลinizi gรถrecektir(`-src` fonksiyonun kodlarฤฑnฤฑ gรถstercektir).
`godoc -http=:8080` komutunu รงalฤฑลtฤฑrฤฑn, `127.0.0.1:8080` adresine gidin. `golang.org`'ฤฑn lokal versiyonunu gรถrmรผล olmanฤฑz gerekiyor. Sadece standart paketler hakkฤฑnda deฤil, `$GOPATH/pkg` altฤฑndaki bรผtรผn paketler iรงinde bilgileri bulabilirsiniz. Bรผyรผk รin Gรผvenlik duvarฤฑndan dรถkรผmantasyonlara eriลemeyenler iรงin.
## Diฤer komutlar
Go yukarฤฑda bahsettiklerimizden daha fazla komut sunuyor.
go fix // versiyon yรผkseltme
go version // Kulladฤฑฤฤฑnฤฑz Go sรผrรผmรผ bilgisi
go env // Go ile alakalฤฑ ortam deฤiลkenleri
go list // yรผklรผ paketlerin listesi
go run // paketi geรงiรงi olarak derleyip รงalฤฑลtฤฑrma
Go komutlarฤฑnin kendi dรถkรผmantasyonunda daha ayrฤฑntฤฑlฤฑ bilgi bulabilirsiniz. `go help <komut_ismi>` ile bu bilgilere eriลebilirsiniz.
kaynak: [https://github.com/astaxie/build-web-application-with-golang](https://github.com/astaxie/build-web-application-with-golang) | {
"content_hash": "bdfd859537c552ed3957e987c8765133",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 678,
"avg_line_length": 57.42446043165467,
"alnum_prop": 0.7614632924079178,
"repo_name": "alioygur/alioygur.github.io",
"id": "4339a0087b939ee6893ea1adc097f2d6aab72461",
"size": "8443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/22-04-2015-go-lang-komut-satiri-araci.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23687"
},
{
"name": "HTML",
"bytes": "9500"
},
{
"name": "JavaScript",
"bytes": "125"
},
{
"name": "Ruby",
"bytes": "229"
}
],
"symlink_target": ""
} |
package com.badlogic.gdx.backends.headless;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.File;
/** @author mzechner
* @author Nathan Sweet */
public final class HeadlessFileHandle extends FileHandle {
public HeadlessFileHandle(String fileName, FileType type) {
super(fileName, type);
}
public HeadlessFileHandle(File file, FileType type) {
super(file, type);
}
public FileHandle child (String name) {
if (file.getPath().length() == 0) return new HeadlessFileHandle(new File(name), type);
return new HeadlessFileHandle(new File(file, name), type);
}
public FileHandle sibling (String name) {
if (file.getPath().length() == 0) throw new GdxRuntimeException("Cannot get the sibling of the root.");
return new HeadlessFileHandle(new File(file.getParent(), name), type);
}
public FileHandle parent () {
File parent = file.getParentFile();
if (parent == null) {
if (type == FileType.Absolute)
parent = new File("/");
else
parent = new File("");
}
return new HeadlessFileHandle(parent, type);
}
public File file () {
if (type == FileType.External) return new File(HeadlessFiles.externalPath, file.getPath());
if (type == FileType.Local) return new File(HeadlessFiles.localPath, file.getPath());
return file;
}
}
| {
"content_hash": "b8ee5aca7752b749621be3053ccfb19e",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 105,
"avg_line_length": 28.5625,
"alnum_prop": 0.7169948942377826,
"repo_name": "srpepperoni/libGDX",
"id": "fb298972a6bbeccea72757e79b97480ec412393e",
"size": "2127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backends/gdx-backend-headless/src/com/badlogic/gdx/backends/headless/HeadlessFileHandle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "3962"
},
{
"name": "C",
"bytes": "8268332"
},
{
"name": "C++",
"bytes": "10339355"
},
{
"name": "CMake",
"bytes": "42744"
},
{
"name": "CSS",
"bytes": "57645"
},
{
"name": "DIGITAL Command Language",
"bytes": "35816"
},
{
"name": "GLSL",
"bytes": "75146"
},
{
"name": "Groff",
"bytes": "2333"
},
{
"name": "HTML",
"bytes": "1067547"
},
{
"name": "Java",
"bytes": "12399181"
},
{
"name": "JavaScript",
"bytes": "24"
},
{
"name": "Lua",
"bytes": "1417"
},
{
"name": "Makefile",
"bytes": "174927"
},
{
"name": "Objective-C",
"bytes": "62497"
},
{
"name": "Objective-C++",
"bytes": "58296"
},
{
"name": "OpenEdge ABL",
"bytes": "15076"
},
{
"name": "Perl",
"bytes": "12798"
},
{
"name": "Python",
"bytes": "179712"
},
{
"name": "Ragel in Ruby Host",
"bytes": "28515"
},
{
"name": "Shell",
"bytes": "348844"
}
],
"symlink_target": ""
} |
package kic
import (
"fmt"
"github.com/golang/glog"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
typed_core "k8s.io/client-go/kubernetes/typed/core/v1"
)
// ServiceTunnel ...
type ServiceTunnel struct {
sshPort string
sshKey string
v1Core typed_core.CoreV1Interface
sshConn *sshConn
}
// NewServiceTunnel ...
func NewServiceTunnel(sshPort, sshKey string, v1Core typed_core.CoreV1Interface) *ServiceTunnel {
return &ServiceTunnel{
sshPort: sshPort,
sshKey: sshKey,
v1Core: v1Core,
}
}
// Start ...
func (t *ServiceTunnel) Start(svcName, namespace string) ([]string, error) {
svc, err := t.v1Core.Services(namespace).Get(svcName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrapf(err, "Service %s was not found in %q namespace. You may select another namespace by using 'minikube service %s -n <namespace>", svcName, namespace, svcName)
}
t.sshConn, err = createSSHConnWithRandomPorts(svcName, t.sshPort, t.sshKey, svc)
if err != nil {
return nil, errors.Wrap(err, "creating ssh conn")
}
go func() {
err = t.sshConn.startAndWait()
if err != nil {
glog.Errorf("error starting ssh tunnel: %v", err)
}
}()
urls := make([]string, 0, len(svc.Spec.Ports))
for _, port := range t.sshConn.ports {
urls = append(urls, fmt.Sprintf("http://127.0.0.1:%d", port))
}
return urls, nil
}
// Stop ...
func (t *ServiceTunnel) Stop() error {
err := t.sshConn.stop()
if err != nil {
return errors.Wrap(err, "stopping ssh tunnel")
}
return nil
}
| {
"content_hash": "ffbcea3b30931ebd600c625c2dd8cd02",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 183,
"avg_line_length": 22.80597014925373,
"alnum_prop": 0.6845549738219895,
"repo_name": "dalehamel/minikube",
"id": "862debcc998fe3888ab1bdfeae4e4a098b57ffce",
"size": "2117",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/minikube/tunnel/kic/service_tunnel.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "759"
},
{
"name": "Go",
"bytes": "411971"
},
{
"name": "Makefile",
"bytes": "20531"
},
{
"name": "NSIS",
"bytes": "7851"
},
{
"name": "PowerShell",
"bytes": "1784"
},
{
"name": "Python",
"bytes": "7680"
},
{
"name": "Shell",
"bytes": "39099"
}
],
"symlink_target": ""
} |
package org.citygml4j.xml.adapter.ade;
import org.citygml4j.core.model.ade.ADEProperty;
import org.citygml4j.core.model.ade.generic.ADEGenericProperty;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;
public class ADESerializerHelper {
public static void writeADEProperty(Element element, ADEProperty property, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
if (element != null) {
writer.writeStartElement(element);
writeADEProperty(property, namespaces, writer);
writer.writeEndElement();
} else {
writeADEProperty(property, namespaces, writer);
}
}
public static void writeADEProperty(ADEProperty property, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
if (property instanceof ADEGenericProperty) {
writer.writeDOMElement(((ADEGenericProperty) property).getValue());
} else {
writer.writeObject(property, namespaces);
}
}
}
| {
"content_hash": "e8ce3dc39678d8f7c036b4483d5cf6bf",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 172,
"avg_line_length": 38.5625,
"alnum_prop": 0.7358184764991896,
"repo_name": "citygml4j/citygml4j",
"id": "de6ea70b5800f2fd313dd661e0586f9f0c7b83bb",
"size": "1944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "citygml4j-xml/src/main/java/org/citygml4j/xml/adapter/ade/ADESerializerHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3290705"
},
{
"name": "XSLT",
"bytes": "4104"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fc31312cb84ff53d4d1a1678641cd06c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "66a37003d61f0040b08f0a22090bbe14b07ccf6e",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Ellertonia/Ellertonia madagascariensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*************************************************************************/
/* rasterizer_canvas_rd.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#include "rasterizer_canvas_rd.h"
#include "core/math/math_funcs.h"
#include "core/project_settings.h"
#include "rasterizer_rd.h"
void RasterizerCanvasRD::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {
p_mat4[0] = p_transform.elements[0][0];
p_mat4[1] = p_transform.elements[0][1];
p_mat4[2] = 0;
p_mat4[3] = 0;
p_mat4[4] = p_transform.elements[1][0];
p_mat4[5] = p_transform.elements[1][1];
p_mat4[6] = 0;
p_mat4[7] = 0;
p_mat4[8] = 0;
p_mat4[9] = 0;
p_mat4[10] = 1;
p_mat4[11] = 0;
p_mat4[12] = p_transform.elements[2][0];
p_mat4[13] = p_transform.elements[2][1];
p_mat4[14] = 0;
p_mat4[15] = 1;
}
void RasterizerCanvasRD::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {
p_mat2x4[0] = p_transform.elements[0][0];
p_mat2x4[1] = p_transform.elements[1][0];
p_mat2x4[2] = 0;
p_mat2x4[3] = p_transform.elements[2][0];
p_mat2x4[4] = p_transform.elements[0][1];
p_mat2x4[5] = p_transform.elements[1][1];
p_mat2x4[6] = 0;
p_mat2x4[7] = p_transform.elements[2][1];
}
void RasterizerCanvasRD::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {
p_mat2x3[0] = p_transform.elements[0][0];
p_mat2x3[1] = p_transform.elements[0][1];
p_mat2x3[2] = p_transform.elements[1][0];
p_mat2x3[3] = p_transform.elements[1][1];
p_mat2x3[4] = p_transform.elements[2][0];
p_mat2x3[5] = p_transform.elements[2][1];
}
void RasterizerCanvasRD::_update_transform_to_mat4(const Transform &p_transform, float *p_mat4) {
p_mat4[0] = p_transform.basis.elements[0][0];
p_mat4[1] = p_transform.basis.elements[1][0];
p_mat4[2] = p_transform.basis.elements[2][0];
p_mat4[3] = 0;
p_mat4[4] = p_transform.basis.elements[0][1];
p_mat4[5] = p_transform.basis.elements[1][1];
p_mat4[6] = p_transform.basis.elements[2][1];
p_mat4[7] = 0;
p_mat4[8] = p_transform.basis.elements[0][2];
p_mat4[9] = p_transform.basis.elements[1][2];
p_mat4[10] = p_transform.basis.elements[2][2];
p_mat4[11] = 0;
p_mat4[12] = p_transform.origin.x;
p_mat4[13] = p_transform.origin.y;
p_mat4[14] = p_transform.origin.z;
p_mat4[15] = 1;
}
void RasterizerCanvasRD::_update_specular_shininess(const Color &p_transform, uint32_t *r_ss) {
*r_ss = uint32_t(CLAMP(p_transform.a * 255.0, 0, 255)) << 24;
*r_ss |= uint32_t(CLAMP(p_transform.b * 255.0, 0, 255)) << 16;
*r_ss |= uint32_t(CLAMP(p_transform.g * 255.0, 0, 255)) << 8;
*r_ss |= uint32_t(CLAMP(p_transform.r * 255.0, 0, 255));
}
RID RasterizerCanvasRD::_create_texture_binding(RID p_texture, RID p_normalmap, RID p_specular, RenderingServer::CanvasItemTextureFilter p_filter, RenderingServer::CanvasItemTextureRepeat p_repeat, RID p_multimesh) {
Vector<RD::Uniform> uniform_set;
{ // COLOR TEXTURE
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 1;
RID texture = storage->texture_get_rd_texture(p_texture);
if (!texture.is_valid()) {
//use default white texture
texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE);
}
u.ids.push_back(texture);
uniform_set.push_back(u);
}
{ // NORMAL TEXTURE
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2;
RID texture = storage->texture_get_rd_texture(p_normalmap);
if (!texture.is_valid()) {
//use default normal texture
texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_NORMAL);
}
u.ids.push_back(texture);
uniform_set.push_back(u);
}
{ // SPECULAR TEXTURE
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 3;
RID texture = storage->texture_get_rd_texture(p_specular);
if (!texture.is_valid()) {
//use default white texture
texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE);
}
u.ids.push_back(texture);
uniform_set.push_back(u);
}
{ // SAMPLER
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 4;
RID sampler = storage->sampler_rd_get_default(p_filter, p_repeat);
ERR_FAIL_COND_V(sampler.is_null(), RID());
u.ids.push_back(sampler);
uniform_set.push_back(u);
}
{ // MULTIMESH TEXTURE BUFFER
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE_BUFFER;
u.binding = 5;
u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_MULTIMESH_BUFFER));
uniform_set.push_back(u);
}
return RD::get_singleton()->uniform_set_create(uniform_set, shader.default_version_rd_shader, 0);
}
RasterizerCanvas::TextureBindingID RasterizerCanvasRD::request_texture_binding(RID p_texture, RID p_normalmap, RID p_specular, RenderingServer::CanvasItemTextureFilter p_filter, RenderingServer::CanvasItemTextureRepeat p_repeat, RID p_multimesh) {
if (p_filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT) {
p_filter = default_samplers.default_filter;
}
if (p_repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT) {
p_repeat = default_samplers.default_repeat;
}
TextureBindingKey key;
key.texture = p_texture;
key.normalmap = p_normalmap;
key.specular = p_specular;
key.multimesh = p_multimesh;
key.texture_filter = p_filter;
key.texture_repeat = p_repeat;
TextureBinding *binding;
TextureBindingID id;
{
TextureBindingID *idptr = bindings.texture_key_bindings.getptr(key);
if (!idptr) {
id = bindings.id_generator++;
bindings.texture_key_bindings[key] = id;
binding = memnew(TextureBinding);
binding->key = key;
binding->id = id;
bindings.texture_bindings[id] = binding;
} else {
id = *idptr;
binding = bindings.texture_bindings[id];
}
}
binding->reference_count++;
if (binding->to_dispose.in_list()) {
//was queued for disposal previously, but ended up reused.
bindings.to_dispose_list.remove(&binding->to_dispose);
}
if (binding->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(binding->uniform_set)) {
binding->uniform_set = _create_texture_binding(p_texture, p_normalmap, p_specular, p_filter, p_repeat, p_multimesh);
}
return id;
}
void RasterizerCanvasRD::free_texture_binding(TextureBindingID p_binding) {
TextureBinding **binding_ptr = bindings.texture_bindings.getptr(p_binding);
ERR_FAIL_COND(!binding_ptr);
TextureBinding *binding = *binding_ptr;
ERR_FAIL_COND(binding->reference_count == 0);
binding->reference_count--;
if (binding->reference_count == 0) {
bindings.to_dispose_list.add(&binding->to_dispose);
}
}
void RasterizerCanvasRD::_dispose_bindings() {
while (bindings.to_dispose_list.first()) {
TextureBinding *binding = bindings.to_dispose_list.first()->self();
if (binding->uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(binding->uniform_set)) {
RD::get_singleton()->free(binding->uniform_set);
}
bindings.texture_key_bindings.erase(binding->key);
bindings.texture_bindings.erase(binding->id);
bindings.to_dispose_list.remove(&binding->to_dispose);
memdelete(binding);
}
}
RasterizerCanvas::PolygonID RasterizerCanvasRD::request_polygon(const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, const Vector<int> &p_bones, const Vector<float> &p_weights) {
// Care must be taken to generate array formats
// in ways where they could be reused, so we will
// put single-occuring elements first, and repeated
// elements later. This way the generated formats are
// the same no matter the length of the arrays.
// This dramatically reduces the amount of pipeline objects
// that need to be created for these formats.
uint32_t vertex_count = p_points.size();
uint32_t stride = 2; //vertices always repeat
if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
stride += 4;
}
if ((uint32_t)p_uvs.size() == vertex_count) {
stride += 2;
}
if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
stride += 4;
}
uint32_t buffer_size = stride * p_points.size();
Vector<uint8_t> polygon_buffer;
polygon_buffer.resize(buffer_size * sizeof(float));
Vector<RD::VertexAttribute> descriptions;
descriptions.resize(4);
Vector<RID> buffers;
buffers.resize(4);
{
const uint8_t *r = polygon_buffer.ptr();
float *fptr = (float *)r;
uint32_t *uptr = (uint32_t *)r;
uint32_t base_offset = 0;
{ //vertices
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
vd.offset = base_offset * sizeof(float);
vd.location = RS::ARRAY_VERTEX;
vd.stride = stride * sizeof(float);
descriptions.write[0] = vd;
const Vector2 *points_ptr = p_points.ptr();
for (uint32_t i = 0; i < vertex_count; i++) {
fptr[base_offset + i * stride + 0] = points_ptr[i].x;
fptr[base_offset + i * stride + 1] = points_ptr[i].y;
}
base_offset += 2;
}
//colors
if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
vd.offset = base_offset * sizeof(float);
vd.location = RS::ARRAY_COLOR;
vd.stride = stride * sizeof(float);
descriptions.write[1] = vd;
if (p_colors.size() == 1) {
Color color = p_colors[0];
for (uint32_t i = 0; i < vertex_count; i++) {
fptr[base_offset + i * stride + 0] = color.r;
fptr[base_offset + i * stride + 1] = color.g;
fptr[base_offset + i * stride + 2] = color.b;
fptr[base_offset + i * stride + 3] = color.a;
}
} else {
const Color *color_ptr = p_colors.ptr();
for (uint32_t i = 0; i < vertex_count; i++) {
fptr[base_offset + i * stride + 0] = color_ptr[i].r;
fptr[base_offset + i * stride + 1] = color_ptr[i].g;
fptr[base_offset + i * stride + 2] = color_ptr[i].b;
fptr[base_offset + i * stride + 3] = color_ptr[i].a;
}
}
base_offset += 4;
} else {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
vd.offset = 0;
vd.location = RS::ARRAY_COLOR;
vd.stride = 0;
descriptions.write[1] = vd;
buffers.write[1] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_COLOR);
}
//uvs
if ((uint32_t)p_uvs.size() == vertex_count) {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
vd.offset = base_offset * sizeof(float);
vd.location = RS::ARRAY_TEX_UV;
vd.stride = stride * sizeof(float);
descriptions.write[2] = vd;
const Vector2 *uv_ptr = p_uvs.ptr();
for (uint32_t i = 0; i < vertex_count; i++) {
fptr[base_offset + i * stride + 0] = uv_ptr[i].x;
fptr[base_offset + i * stride + 1] = uv_ptr[i].y;
}
base_offset += 2;
} else {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
vd.offset = 0;
vd.location = RS::ARRAY_TEX_UV;
vd.stride = 0;
descriptions.write[2] = vd;
buffers.write[2] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_TEX_UV);
}
//bones
if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;
vd.offset = base_offset * sizeof(float);
vd.location = RS::ARRAY_BONES;
vd.stride = stride * sizeof(float);
descriptions.write[3] = vd;
const int *bone_ptr = p_bones.ptr();
const float *weight_ptr = p_weights.ptr();
for (uint32_t i = 0; i < vertex_count; i++) {
uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];
uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride + 2];
bone16w[0] = bone_ptr[i * 4 + 0];
bone16w[1] = bone_ptr[i * 4 + 1];
bone16w[2] = bone_ptr[i * 4 + 2];
bone16w[3] = bone_ptr[i * 4 + 3];
weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);
weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);
weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);
weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);
}
base_offset += 4;
} else {
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;
vd.offset = 0;
vd.location = RS::ARRAY_BONES;
vd.stride = 0;
descriptions.write[3] = vd;
buffers.write[3] = storage->mesh_get_default_rd_buffer(RasterizerStorageRD::DEFAULT_RD_BUFFER_BONES);
}
//check that everything is as it should be
ERR_FAIL_COND_V(base_offset != stride, 0); //bug
}
RD::VertexFormatID vertex_id = RD::get_singleton()->vertex_format_create(descriptions);
ERR_FAIL_COND_V(vertex_id == RD::INVALID_ID, 0);
PolygonBuffers pb;
pb.vertex_buffer = RD::get_singleton()->vertex_buffer_create(polygon_buffer.size(), polygon_buffer);
for (int i = 0; i < descriptions.size(); i++) {
if (buffers[i] == RID()) { //if put in vertex, use as vertex
buffers.write[i] = pb.vertex_buffer;
}
}
pb.vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), vertex_id, buffers);
if (p_indices.size()) {
//create indices, as indices were requested
Vector<uint8_t> index_buffer;
index_buffer.resize(p_indices.size() * sizeof(int32_t));
{
uint8_t *w = index_buffer.ptrw();
copymem(w, p_indices.ptr(), sizeof(int32_t) * p_indices.size());
}
pb.index_buffer = RD::get_singleton()->index_buffer_create(p_indices.size(), RD::INDEX_BUFFER_FORMAT_UINT32, index_buffer);
pb.indices = RD::get_singleton()->index_array_create(pb.index_buffer, 0, p_indices.size());
}
pb.vertex_format_id = vertex_id;
PolygonID id = polygon_buffers.last_id++;
polygon_buffers.polygons[id] = pb;
return id;
}
void RasterizerCanvasRD::free_polygon(PolygonID p_polygon) {
PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);
ERR_FAIL_COND(!pb_ptr);
PolygonBuffers &pb = *pb_ptr;
if (pb.indices.is_valid()) {
RD::get_singleton()->free(pb.indices);
}
if (pb.index_buffer.is_valid()) {
RD::get_singleton()->free(pb.index_buffer);
}
RD::get_singleton()->free(pb.vertex_array);
RD::get_singleton()->free(pb.vertex_buffer);
polygon_buffers.polygons.erase(p_polygon);
}
Size2i RasterizerCanvasRD::_bind_texture_binding(TextureBindingID p_binding, RD::DrawListID p_draw_list, uint32_t &flags) {
TextureBinding **texture_binding_ptr = bindings.texture_bindings.getptr(p_binding);
ERR_FAIL_COND_V(!texture_binding_ptr, Size2i());
TextureBinding *texture_binding = *texture_binding_ptr;
if (texture_binding->key.normalmap.is_valid()) {
flags |= FLAGS_DEFAULT_NORMAL_MAP_USED;
}
if (texture_binding->key.specular.is_valid()) {
flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
if (!RD::get_singleton()->uniform_set_is_valid(texture_binding->uniform_set)) {
//texture may have changed (erased or replaced, see if we can fix)
texture_binding->uniform_set = _create_texture_binding(texture_binding->key.texture, texture_binding->key.normalmap, texture_binding->key.specular, texture_binding->key.texture_filter, texture_binding->key.texture_repeat, texture_binding->key.multimesh);
ERR_FAIL_COND_V(!texture_binding->uniform_set.is_valid(), Size2i(1, 1));
}
RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, texture_binding->uniform_set, 0);
if (texture_binding->key.texture.is_valid()) {
return storage->texture_2d_get_size(texture_binding->key.texture);
} else {
return Size2i(1, 1);
}
}
////////////////////
void RasterizerCanvasRD::_render_item(RD::DrawListID p_draw_list, const Item *p_item, RD::FramebufferFormatID p_framebuffer_format, const Transform2D &p_canvas_transform_inverse, Item *¤t_clip, Light *p_lights, PipelineVariants *p_pipeline_variants) {
//create an empty push constant
PushConstant push_constant;
Transform2D base_transform = p_canvas_transform_inverse * p_item->final_transform;
_update_transform_2d_to_mat2x3(base_transform, push_constant.world);
Color base_color = p_item->final_modulate;
for (int i = 0; i < 4; i++) {
push_constant.modulation[i] = 0;
push_constant.ninepatch_margins[i] = 0;
push_constant.src_rect[i] = 0;
push_constant.dst_rect[i] = 0;
}
push_constant.flags = 0;
push_constant.color_texture_pixel_size[0] = 0;
push_constant.color_texture_pixel_size[1] = 0;
push_constant.pad[0] = 0;
push_constant.pad[1] = 0;
push_constant.lights[0] = 0;
push_constant.lights[1] = 0;
push_constant.lights[2] = 0;
push_constant.lights[3] = 0;
uint32_t base_flags = 0;
bool light_uniform_set_dirty = false;
if (!p_item->custom_data) {
p_item->custom_data = memnew(ItemStateData);
light_uniform_set_dirty = true;
}
ItemStateData *state_data = (ItemStateData *)p_item->custom_data;
Light *light_cache[DEFAULT_MAX_LIGHTS_PER_ITEM];
uint16_t light_count = 0;
PipelineLightMode light_mode;
{
Light *light = p_lights;
while (light) {
if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
uint32_t light_index = light->render_index_cache;
push_constant.lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
if (!light_uniform_set_dirty && (state_data->light_cache[light_count].light != light || state_data->light_cache[light_count].light_version != light->version)) {
light_uniform_set_dirty = true;
}
light_cache[light_count] = light;
light_count++;
if (light->mode == RS::CANVAS_LIGHT_MODE_MASK) {
base_flags |= FLAGS_USING_LIGHT_MASK;
}
if (light_count == state.max_lights_per_item) {
break;
}
}
light = light->next_ptr;
}
if (light_count != state_data->light_cache_count) {
light_uniform_set_dirty = true;
}
base_flags |= light_count << FLAGS_LIGHT_COUNT_SHIFT;
}
{
RID &canvas_item_state = light_count ? state_data->state_uniform_set_with_light : state_data->state_uniform_set;
bool invalid_uniform = canvas_item_state.is_valid() && !RD::get_singleton()->uniform_set_is_valid(canvas_item_state);
if (canvas_item_state.is_null() || invalid_uniform || (light_count > 0 && light_uniform_set_dirty)) {
//re create canvas state
Vector<RD::Uniform> uniforms;
if (state_data->state_uniform_set_with_light.is_valid() && !invalid_uniform) {
RD::get_singleton()->free(canvas_item_state);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 0;
u.ids.push_back(state.canvas_state_buffer);
uniforms.push_back(u);
}
if (false && p_item->skeleton.is_valid()) {
//bind skeleton stuff
} else {
//bind default
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE_BUFFER;
u.binding = 1;
u.ids.push_back(shader.default_skeleton_texture_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 2;
u.ids.push_back(shader.default_skeleton_uniform_buffer);
uniforms.push_back(u);
}
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 7;
u.ids.push_back(storage->global_variables_get_storage_buffer());
uniforms.push_back(u);
}
//validate and update lighs if they are being used
if (light_count > 0) {
//recreate uniform set
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 3;
u.ids.push_back(state.lights_uniform_buffer);
uniforms.push_back(u);
}
{
RD::Uniform u_lights;
u_lights.type = RD::UNIFORM_TYPE_TEXTURE;
u_lights.binding = 4;
RD::Uniform u_shadows;
u_shadows.type = RD::UNIFORM_TYPE_TEXTURE;
u_shadows.binding = 5;
//lights
for (uint32_t i = 0; i < state.max_lights_per_item; i++) {
if (i < light_count) {
CanvasLight *cl = canvas_light_owner.getornull(light_cache[i]->light_internal);
ERR_CONTINUE(!cl);
RID rd_texture;
if (cl->texture.is_valid()) {
rd_texture = storage->texture_get_rd_texture(cl->texture);
}
if (rd_texture.is_valid()) {
u_lights.ids.push_back(rd_texture);
} else {
u_lights.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
}
if (cl->shadow.texture.is_valid()) {
u_shadows.ids.push_back(cl->shadow.texture);
} else {
u_shadows.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK));
}
} else {
u_lights.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
u_shadows.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK));
}
}
uniforms.push_back(u_lights);
uniforms.push_back(u_shadows);
}
{
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 6;
u.ids.push_back(state.shadow_sampler);
uniforms.push_back(u);
}
canvas_item_state = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader_light, 2);
} else {
canvas_item_state = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, 2);
}
}
RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, canvas_item_state, 2);
}
light_mode = light_count > 0 ? PIPELINE_LIGHT_MODE_ENABLED : PIPELINE_LIGHT_MODE_DISABLED;
PipelineVariants *pipeline_variants = p_pipeline_variants;
bool reclip = false;
const Item::Command *c = p_item->commands;
while (c) {
push_constant.flags = base_flags; //reset on each command for sanity
push_constant.specular_shininess = 0xFFFFFFFF;
switch (c->type) {
case Item::Command::TYPE_RECT: {
const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
//bind pipeline
{
RID pipeline = pipeline_variants->variants[light_mode][PIPELINE_VARIANT_QUAD].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
}
//bind textures
Size2 texpixel_size;
{
texpixel_size = _bind_texture_binding(rect->texture_binding.binding_id, p_draw_list, push_constant.flags);
texpixel_size.x = 1.0 / texpixel_size.x;
texpixel_size.y = 1.0 / texpixel_size.y;
}
if (rect->specular_shininess.a < 0.999) {
push_constant.flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
_update_specular_shininess(rect->specular_shininess, &push_constant.specular_shininess);
Rect2 src_rect;
Rect2 dst_rect;
if (texpixel_size != Vector2()) {
push_constant.color_texture_pixel_size[0] = texpixel_size.x;
push_constant.color_texture_pixel_size[1] = texpixel_size.y;
src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * texpixel_size, rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1);
dst_rect = Rect2(rect->rect.position, rect->rect.size);
if (dst_rect.size.width < 0) {
dst_rect.position.x += dst_rect.size.width;
dst_rect.size.width *= -1;
}
if (dst_rect.size.height < 0) {
dst_rect.position.y += dst_rect.size.height;
dst_rect.size.height *= -1;
}
if (rect->flags & CANVAS_RECT_FLIP_H) {
src_rect.size.x *= -1;
}
if (rect->flags & CANVAS_RECT_FLIP_V) {
src_rect.size.y *= -1;
}
if (rect->flags & CANVAS_RECT_TRANSPOSE) {
dst_rect.size.x *= -1; // Encoding in the dst_rect.z uniform
}
if (rect->flags & CANVAS_RECT_CLIP_UV) {
push_constant.flags |= FLAGS_CLIP_RECT_UV;
}
} else {
dst_rect = Rect2(rect->rect.position, rect->rect.size);
if (dst_rect.size.width < 0) {
dst_rect.position.x += dst_rect.size.width;
dst_rect.size.width *= -1;
}
if (dst_rect.size.height < 0) {
dst_rect.position.y += dst_rect.size.height;
dst_rect.size.height *= -1;
}
src_rect = Rect2(0, 0, 1, 1);
texpixel_size = Vector2(1, 1);
}
push_constant.modulation[0] = rect->modulate.r * base_color.r;
push_constant.modulation[1] = rect->modulate.g * base_color.g;
push_constant.modulation[2] = rect->modulate.b * base_color.b;
push_constant.modulation[3] = rect->modulate.a * base_color.a;
push_constant.src_rect[0] = src_rect.position.x;
push_constant.src_rect[1] = src_rect.position.y;
push_constant.src_rect[2] = src_rect.size.width;
push_constant.src_rect[3] = src_rect.size.height;
push_constant.dst_rect[0] = dst_rect.position.x;
push_constant.dst_rect[1] = dst_rect.position.y;
push_constant.dst_rect[2] = dst_rect.size.width;
push_constant.dst_rect[3] = dst_rect.size.height;
push_constant.color_texture_pixel_size[0] = texpixel_size.x;
push_constant.color_texture_pixel_size[1] = texpixel_size.y;
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);
RD::get_singleton()->draw_list_draw(p_draw_list, true);
} break;
case Item::Command::TYPE_NINEPATCH: {
const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);
//bind pipeline
{
RID pipeline = pipeline_variants->variants[light_mode][PIPELINE_VARIANT_NINEPATCH].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
}
//bind textures
Size2 texpixel_size;
{
texpixel_size = _bind_texture_binding(np->texture_binding.binding_id, p_draw_list, push_constant.flags);
texpixel_size.x = 1.0 / texpixel_size.x;
texpixel_size.y = 1.0 / texpixel_size.y;
}
if (np->specular_shininess.a < 0.999) {
push_constant.flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
_update_specular_shininess(np->specular_shininess, &push_constant.specular_shininess);
Rect2 src_rect;
Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);
if (texpixel_size == Size2()) {
texpixel_size = Size2(1, 1);
src_rect = Rect2(0, 0, 1, 1);
} else {
if (np->source != Rect2()) {
src_rect = Rect2(np->source.position.x * texpixel_size.width, np->source.position.y * texpixel_size.height, np->source.size.x * texpixel_size.width, np->source.size.y * texpixel_size.height);
texpixel_size = Size2(1.0 / np->source.size.width, 1.0 / np->source.size.height);
} else {
src_rect = Rect2(0, 0, 1, 1);
}
}
push_constant.modulation[0] = np->color.r * base_color.r;
push_constant.modulation[1] = np->color.g * base_color.g;
push_constant.modulation[2] = np->color.b * base_color.b;
push_constant.modulation[3] = np->color.a * base_color.a;
push_constant.src_rect[0] = src_rect.position.x;
push_constant.src_rect[1] = src_rect.position.y;
push_constant.src_rect[2] = src_rect.size.width;
push_constant.src_rect[3] = src_rect.size.height;
push_constant.dst_rect[0] = dst_rect.position.x;
push_constant.dst_rect[1] = dst_rect.position.y;
push_constant.dst_rect[2] = dst_rect.size.width;
push_constant.dst_rect[3] = dst_rect.size.height;
push_constant.color_texture_pixel_size[0] = texpixel_size.x;
push_constant.color_texture_pixel_size[1] = texpixel_size.y;
push_constant.flags |= int(np->axis_x) << FLAGS_NINEPATCH_H_MODE_SHIFT;
push_constant.flags |= int(np->axis_y) << FLAGS_NINEPATCH_V_MODE_SHIFT;
if (np->draw_center) {
push_constant.flags |= FLAGS_NINEPACH_DRAW_CENTER;
}
push_constant.ninepatch_margins[0] = np->margin[MARGIN_LEFT];
push_constant.ninepatch_margins[1] = np->margin[MARGIN_TOP];
push_constant.ninepatch_margins[2] = np->margin[MARGIN_RIGHT];
push_constant.ninepatch_margins[3] = np->margin[MARGIN_BOTTOM];
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);
RD::get_singleton()->draw_list_draw(p_draw_list, true);
} break;
case Item::Command::TYPE_POLYGON: {
const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);
ERR_CONTINUE(!pb);
//bind pipeline
{
static const PipelineVariant variant[RS::PRIMITIVE_MAX] = { PIPELINE_VARIANT_ATTRIBUTE_POINTS, PIPELINE_VARIANT_ATTRIBUTE_LINES, PIPELINE_VARIANT_ATTRIBUTE_LINES_STRIP, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLES, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLE_STRIP };
ERR_CONTINUE(polygon->primitive < 0 || polygon->primitive >= RS::PRIMITIVE_MAX);
RID pipeline = pipeline_variants->variants[light_mode][variant[polygon->primitive]].get_render_pipeline(pb->vertex_format_id, p_framebuffer_format);
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
}
if (polygon->primitive == RS::PRIMITIVE_LINES) {
//not supported in most hardware, so pointless
//RD::get_singleton()->draw_list_set_line_width(p_draw_list, polygon->line_width);
}
//bind textures
Size2 texpixel_size;
{
texpixel_size = _bind_texture_binding(polygon->texture_binding.binding_id, p_draw_list, push_constant.flags);
texpixel_size.x = 1.0 / texpixel_size.x;
texpixel_size.y = 1.0 / texpixel_size.y;
}
if (polygon->specular_shininess.a < 0.999) {
push_constant.flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
_update_specular_shininess(polygon->specular_shininess, &push_constant.specular_shininess);
push_constant.modulation[0] = base_color.r;
push_constant.modulation[1] = base_color.g;
push_constant.modulation[2] = base_color.b;
push_constant.modulation[3] = base_color.a;
for (int j = 0; j < 4; j++) {
push_constant.src_rect[j] = 0;
push_constant.dst_rect[j] = 0;
push_constant.ninepatch_margins[j] = 0;
}
push_constant.color_texture_pixel_size[0] = texpixel_size.x;
push_constant.color_texture_pixel_size[1] = texpixel_size.y;
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, pb->vertex_array);
if (pb->indices.is_valid()) {
RD::get_singleton()->draw_list_bind_index_array(p_draw_list, pb->indices);
}
RD::get_singleton()->draw_list_draw(p_draw_list, pb->indices.is_valid());
} break;
case Item::Command::TYPE_PRIMITIVE: {
const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
//bind pipeline
{
static const PipelineVariant variant[4] = { PIPELINE_VARIANT_PRIMITIVE_POINTS, PIPELINE_VARIANT_PRIMITIVE_LINES, PIPELINE_VARIANT_PRIMITIVE_TRIANGLES, PIPELINE_VARIANT_PRIMITIVE_TRIANGLES };
ERR_CONTINUE(primitive->point_count == 0 || primitive->point_count > 4);
RID pipeline = pipeline_variants->variants[light_mode][variant[primitive->point_count - 1]].get_render_pipeline(RD::INVALID_ID, p_framebuffer_format);
RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
}
//bind textures
{
_bind_texture_binding(primitive->texture_binding.binding_id, p_draw_list, push_constant.flags);
}
if (primitive->specular_shininess.a < 0.999) {
push_constant.flags |= FLAGS_DEFAULT_SPECULAR_MAP_USED;
}
_update_specular_shininess(primitive->specular_shininess, &push_constant.specular_shininess);
RD::get_singleton()->draw_list_bind_index_array(p_draw_list, primitive_arrays.index_array[MIN(3, primitive->point_count) - 1]);
for (uint32_t j = 0; j < MIN(3, primitive->point_count); j++) {
push_constant.points[j * 2 + 0] = primitive->points[j].x;
push_constant.points[j * 2 + 1] = primitive->points[j].y;
push_constant.uvs[j * 2 + 0] = primitive->uvs[j].x;
push_constant.uvs[j * 2 + 1] = primitive->uvs[j].y;
Color col = primitive->colors[j] * base_color;
push_constant.colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
push_constant.colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
}
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
RD::get_singleton()->draw_list_draw(p_draw_list, true);
if (primitive->point_count == 4) {
for (uint32_t j = 1; j < 3; j++) {
//second half of triangle
push_constant.points[j * 2 + 0] = primitive->points[j + 1].x;
push_constant.points[j * 2 + 1] = primitive->points[j + 1].y;
push_constant.uvs[j * 2 + 0] = primitive->uvs[j + 1].x;
push_constant.uvs[j * 2 + 1] = primitive->uvs[j + 1].y;
Color col = primitive->colors[j + 1] * base_color;
push_constant.colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
push_constant.colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
}
RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
RD::get_singleton()->draw_list_draw(p_draw_list, true);
}
} break;
case Item::Command::TYPE_MESH:
case Item::Command::TYPE_MULTIMESH:
case Item::Command::TYPE_PARTICLES: {
ERR_PRINT("FIXME: Mesh, MultiMesh and Particles render commands are unimplemented currently, they need to be ported to the 4.0 rendering architecture.");
#ifndef _MSC_VER
#warning Item::Command types for Mesh, MultiMesh and Particles need to be implemented.
#endif
// See #if 0'ed code below to port from GLES3.
} break;
#if 0
case Item::Command::TYPE_MESH: {
Item::CommandMesh *mesh = static_cast<Item::CommandMesh *>(c);
_set_texture_rect_mode(false);
RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(mesh->texture, mesh->normal_map);
if (texture) {
Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
}
state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform * mesh->transform);
RasterizerStorageGLES3::Mesh *mesh_data = storage->mesh_owner.getornull(mesh->mesh);
if (mesh_data) {
for (int j = 0; j < mesh_data->surfaces.size(); j++) {
RasterizerStorageGLES3::Surface *s = mesh_data->surfaces[j];
// materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing
glBindVertexArray(s->array_id);
glVertexAttrib4f(RS::ARRAY_COLOR, mesh->modulate.r, mesh->modulate.g, mesh->modulate.b, mesh->modulate.a);
if (s->index_array_len) {
glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
} else {
glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
}
glBindVertexArray(0);
}
}
state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform);
} break;
case Item::Command::TYPE_MULTIMESH: {
Item::CommandMultiMesh *mmesh = static_cast<Item::CommandMultiMesh *>(c);
RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getornull(mmesh->multimesh);
if (!multi_mesh)
break;
RasterizerStorageGLES3::Mesh *mesh_data = storage->mesh_owner.getornull(multi_mesh->mesh);
if (!mesh_data)
break;
RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(mmesh->texture, mmesh->normal_map);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, multi_mesh->custom_data_format != RS::MULTIMESH_CUSTOM_DATA_NONE);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, true);
//reset shader and force rebind
state.using_texture_rect = true;
_set_texture_rect_mode(false);
if (texture) {
Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
}
int amount = MIN(multi_mesh->size, multi_mesh->visible_instances);
if (amount == -1) {
amount = multi_mesh->size;
}
for (int j = 0; j < mesh_data->surfaces.size(); j++) {
RasterizerStorageGLES3::Surface *s = mesh_data->surfaces[j];
// materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing
glBindVertexArray(s->instancing_array_id);
glBindBuffer(GL_ARRAY_BUFFER, multi_mesh->buffer); //modify the buffer
int stride = (multi_mesh->xform_floats + multi_mesh->color_floats + multi_mesh->custom_data_floats) * 4;
glEnableVertexAttribArray(8);
glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(0));
glVertexAttribDivisor(8, 1);
glEnableVertexAttribArray(9);
glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(4 * 4));
glVertexAttribDivisor(9, 1);
int color_ofs;
if (multi_mesh->transform_format == RS::MULTIMESH_TRANSFORM_3D) {
glEnableVertexAttribArray(10);
glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(8 * 4));
glVertexAttribDivisor(10, 1);
color_ofs = 12 * 4;
} else {
glDisableVertexAttribArray(10);
glVertexAttrib4f(10, 0, 0, 1, 0);
color_ofs = 8 * 4;
}
int custom_data_ofs = color_ofs;
switch (multi_mesh->color_format) {
case RS::MULTIMESH_COLOR_NONE: {
glDisableVertexAttribArray(11);
glVertexAttrib4f(11, 1, 1, 1, 1);
} break;
case RS::MULTIMESH_COLOR_8BIT: {
glEnableVertexAttribArray(11);
glVertexAttribPointer(11, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
glVertexAttribDivisor(11, 1);
custom_data_ofs += 4;
} break;
case RS::MULTIMESH_COLOR_FLOAT: {
glEnableVertexAttribArray(11);
glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs));
glVertexAttribDivisor(11, 1);
custom_data_ofs += 4 * 4;
} break;
}
switch (multi_mesh->custom_data_format) {
case RS::MULTIMESH_CUSTOM_DATA_NONE: {
glDisableVertexAttribArray(12);
glVertexAttrib4f(12, 1, 1, 1, 1);
} break;
case RS::MULTIMESH_CUSTOM_DATA_8BIT: {
glEnableVertexAttribArray(12);
glVertexAttribPointer(12, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
glVertexAttribDivisor(12, 1);
} break;
case RS::MULTIMESH_CUSTOM_DATA_FLOAT: {
glEnableVertexAttribArray(12);
glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(custom_data_ofs));
glVertexAttribDivisor(12, 1);
} break;
}
if (s->index_array_len) {
glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount);
} else {
glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount);
}
glBindVertexArray(0);
}
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, false);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, false);
state.using_texture_rect = true;
_set_texture_rect_mode(false);
} break;
case Item::Command::TYPE_PARTICLES: {
Item::CommandParticles *particles_cmd = static_cast<Item::CommandParticles *>(c);
RasterizerStorageGLES3::Particles *particles = storage->particles_owner.getornull(particles_cmd->particles);
if (!particles)
break;
if (particles->inactive && !particles->emitting)
break;
glVertexAttrib4f(RS::ARRAY_COLOR, 1, 1, 1, 1); //not used, so keep white
RenderingServerRaster::redraw_request();
storage->particles_request_process(particles_cmd->particles);
//enable instancing
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, true);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_PARTICLES, true);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, true);
//reset shader and force rebind
state.using_texture_rect = true;
_set_texture_rect_mode(false);
RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(particles_cmd->texture, particles_cmd->normal_map);
if (texture) {
Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
} else {
state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, Vector2(1.0, 1.0));
}
if (!particles->use_local_coords) {
Transform2D inv_xf;
inv_xf.set_axis(0, Vector2(particles->emission_transform.basis.get_axis(0).x, particles->emission_transform.basis.get_axis(0).y));
inv_xf.set_axis(1, Vector2(particles->emission_transform.basis.get_axis(1).x, particles->emission_transform.basis.get_axis(1).y));
inv_xf.set_origin(Vector2(particles->emission_transform.get_origin().x, particles->emission_transform.get_origin().y));
inv_xf.affine_invert();
state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform * inv_xf);
}
glBindVertexArray(data.particle_quad_array); //use particle quad array
glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]); //bind particle buffer
int stride = sizeof(float) * 4 * 6;
int amount = particles->amount;
if (particles->draw_order != RS::PARTICLES_DRAW_ORDER_LIFETIME) {
glEnableVertexAttribArray(8); //xform x
glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
glVertexAttribDivisor(8, 1);
glEnableVertexAttribArray(9); //xform y
glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
glVertexAttribDivisor(9, 1);
glEnableVertexAttribArray(10); //xform z
glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
glVertexAttribDivisor(10, 1);
glEnableVertexAttribArray(11); //color
glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, nullptr);
glVertexAttribDivisor(11, 1);
glEnableVertexAttribArray(12); //custom
glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
glVertexAttribDivisor(12, 1);
glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, amount);
} else {
//split
int split = int(Math::ceil(particles->phase * particles->amount));
if (amount - split > 0) {
glEnableVertexAttribArray(8); //xform x
glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 3));
glVertexAttribDivisor(8, 1);
glEnableVertexAttribArray(9); //xform y
glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 4));
glVertexAttribDivisor(9, 1);
glEnableVertexAttribArray(10); //xform z
glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 5));
glVertexAttribDivisor(10, 1);
glEnableVertexAttribArray(11); //color
glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + 0));
glVertexAttribDivisor(11, 1);
glEnableVertexAttribArray(12); //custom
glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(stride * split + sizeof(float) * 4 * 2));
glVertexAttribDivisor(12, 1);
glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, amount - split);
}
if (split > 0) {
glEnableVertexAttribArray(8); //xform x
glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 3));
glVertexAttribDivisor(8, 1);
glEnableVertexAttribArray(9); //xform y
glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 4));
glVertexAttribDivisor(9, 1);
glEnableVertexAttribArray(10); //xform z
glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 5));
glVertexAttribDivisor(10, 1);
glEnableVertexAttribArray(11); //color
glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, nullptr);
glVertexAttribDivisor(11, 1);
glEnableVertexAttribArray(12); //custom
glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(sizeof(float) * 4 * 2));
glVertexAttribDivisor(12, 1);
glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, split);
}
}
glBindVertexArray(0);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCE_CUSTOM, false);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_PARTICLES, false);
state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_INSTANCING, false);
state.using_texture_rect = true;
_set_texture_rect_mode(false);
} break;
#endif
case Item::Command::TYPE_TRANSFORM: {
const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
_update_transform_2d_to_mat2x3(base_transform * transform->xform, push_constant.world);
} break;
case Item::Command::TYPE_CLIP_IGNORE: {
const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);
if (current_clip) {
if (ci->ignore != reclip) {
if (ci->ignore) {
RD::get_singleton()->draw_list_disable_scissor(p_draw_list);
reclip = true;
} else {
RD::get_singleton()->draw_list_enable_scissor(p_draw_list, current_clip->final_clip_rect);
reclip = false;
}
}
}
} break;
}
c = c->next;
}
if (current_clip && reclip) {
//will make it re-enable clipping if needed afterwards
current_clip = nullptr;
}
}
void RasterizerCanvasRD::_render_items(RID p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, RID p_screen_uniform_set) {
Item *current_clip = nullptr;
Transform2D canvas_transform_inverse = p_canvas_transform_inverse;
RID framebuffer = storage->render_target_get_rd_framebuffer(p_to_render_target);
Vector<Color> clear_colors;
bool clear = false;
if (storage->render_target_is_clear_requested(p_to_render_target)) {
clear = true;
clear_colors.push_back(storage->render_target_get_clear_request_color(p_to_render_target));
storage->render_target_disable_clear_request(p_to_render_target);
}
#ifndef _MSC_VER
#warning TODO obtain from framebuffer format eventually when this is implemented
#endif
RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, clear ? RD::INITIAL_ACTION_CLEAR : RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD, clear_colors);
if (p_screen_uniform_set.is_valid()) {
RD::get_singleton()->draw_list_bind_uniform_set(draw_list, p_screen_uniform_set, 3);
}
RID prev_material;
PipelineVariants *pipeline_variants = &shader.pipeline_variants;
for (int i = 0; i < p_item_count; i++) {
Item *ci = items[i];
if (current_clip != ci->final_clip_owner) {
current_clip = ci->final_clip_owner;
//setup clip
if (current_clip) {
RD::get_singleton()->draw_list_enable_scissor(draw_list, current_clip->final_clip_rect);
} else {
RD::get_singleton()->draw_list_disable_scissor(draw_list);
}
}
if (ci->material != prev_material) {
MaterialData *material_data = nullptr;
if (ci->material.is_valid()) {
material_data = (MaterialData *)storage->material_get_data(ci->material, RasterizerStorageRD::SHADER_TYPE_2D);
}
if (material_data) {
if (material_data->shader_data->version.is_valid() && material_data->shader_data->valid) {
pipeline_variants = &material_data->shader_data->pipeline_variants;
if (material_data->uniform_set.is_valid()) {
RD::get_singleton()->draw_list_bind_uniform_set(draw_list, material_data->uniform_set, 1);
}
} else {
pipeline_variants = &shader.pipeline_variants;
}
} else {
pipeline_variants = &shader.pipeline_variants;
}
}
_render_item(draw_list, ci, fb_format, canvas_transform_inverse, current_clip, p_lights, pipeline_variants);
prev_material = ci->material;
}
RD::get_singleton()->draw_list_end();
}
void RasterizerCanvasRD::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, const Transform2D &p_canvas_transform) {
int item_count = 0;
//setup canvas state uniforms if needed
Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();
{
//update canvas state uniform buffer
State::Buffer state_buffer;
Size2i ssize = storage->render_target_get_size(p_to_render_target);
Transform screen_transform;
screen_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
screen_transform.scale(Vector3(2.0f / ssize.width, 2.0f / ssize.height, 1.0f));
_update_transform_to_mat4(screen_transform, state_buffer.screen_transform);
_update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);
Transform2D normal_transform = p_canvas_transform;
normal_transform.elements[0].normalize();
normal_transform.elements[1].normalize();
normal_transform.elements[2] = Vector2();
_update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);
state_buffer.canvas_modulate[0] = p_modulate.r;
state_buffer.canvas_modulate[1] = p_modulate.g;
state_buffer.canvas_modulate[2] = p_modulate.b;
state_buffer.canvas_modulate[3] = p_modulate.a;
Size2 render_target_size = storage->render_target_get_size(p_to_render_target);
state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
state_buffer.time = state.time;
RD::get_singleton()->buffer_update(state.canvas_state_buffer, 0, sizeof(State::Buffer), &state_buffer, true);
}
//setup lights if exist
{
Light *l = p_light_list;
uint32_t index = 0;
while (l) {
if (index == state.max_lights_per_render) {
l->render_index_cache = -1;
l = l->next_ptr;
continue;
}
CanvasLight *clight = canvas_light_owner.getornull(l->light_internal);
if (!clight) { //unused or invalid texture
l->render_index_cache = -1;
l = l->next_ptr;
ERR_CONTINUE(!clight);
}
Transform2D to_light_xform = (p_canvas_transform * l->light_shader_xform).affine_inverse();
Vector2 canvas_light_pos = p_canvas_transform.xform(l->xform.get_origin()); //convert light position to canvas coordinates, as all computation is done in canvas coords to avoid precision loss
state.light_uniforms[index].position[0] = canvas_light_pos.x;
state.light_uniforms[index].position[1] = canvas_light_pos.y;
_update_transform_2d_to_mat2x4(to_light_xform, state.light_uniforms[index].matrix);
_update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
state.light_uniforms[index].height = l->height * (p_canvas_transform.elements[0].length() + p_canvas_transform.elements[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
for (int i = 0; i < 4; i++) {
state.light_uniforms[index].shadow_color[i] = l->shadow_color[i];
state.light_uniforms[index].color[i] = l->color[i];
}
state.light_uniforms[index].color[3] = l->energy; //use alpha for energy, so base color can go separate
if (clight->shadow.texture.is_valid()) {
state.light_uniforms[index].shadow_pixel_size = (1.0 / clight->shadow.size) * (1.0 + l->shadow_smooth);
} else {
state.light_uniforms[index].shadow_pixel_size = 1.0;
}
state.light_uniforms[index].flags |= l->mode << LIGHT_FLAGS_BLEND_SHIFT;
state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
if (clight->shadow.texture.is_valid()) {
state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
}
l->render_index_cache = index;
index++;
l = l->next_ptr;
}
if (index > 0) {
RD::get_singleton()->buffer_update(state.lights_uniform_buffer, 0, sizeof(LightUniform) * index, &state.light_uniforms[0], true);
}
}
//fill the list until rendering is possible.
bool material_screen_texture_found = false;
Item *ci = p_item_list;
Rect2 back_buffer_rect;
bool backbuffer_copy = false;
RID screen_uniform_set;
while (ci) {
if (ci->copy_back_buffer) {
backbuffer_copy = true;
if (ci->copy_back_buffer->full) {
back_buffer_rect = Rect2();
} else {
back_buffer_rect = ci->copy_back_buffer->rect;
}
}
if (ci->material.is_valid()) {
MaterialData *md = (MaterialData *)storage->material_get_data(ci->material, RasterizerStorageRD::SHADER_TYPE_2D);
if (md && md->shader_data->valid) {
if (md->shader_data->uses_screen_texture) {
if (!material_screen_texture_found) {
backbuffer_copy = true;
back_buffer_rect = Rect2();
}
if (screen_uniform_set.is_null()) {
RID backbuffer_shader = shader.canvas_shader.version_get_shader(md->shader_data->version, 0); //any version is fine
screen_uniform_set = storage->render_target_get_back_buffer_uniform_set(p_to_render_target, backbuffer_shader);
}
}
if (md->last_frame != RasterizerRD::singleton->get_frame_number()) {
md->last_frame = RasterizerRD::singleton->get_frame_number();
if (!RD::get_singleton()->uniform_set_is_valid(md->uniform_set)) {
// uniform set may be gone because a dependency was erased. In this case, it will happen
// if a texture is deleted, so just re-create it.
storage->material_force_update_textures(ci->material, RasterizerStorageRD::SHADER_TYPE_2D);
}
}
}
}
if (backbuffer_copy) {
//render anything pending, including clearing if no items
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, screen_uniform_set);
item_count = 0;
storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect);
backbuffer_copy = false;
material_screen_texture_found = true; //after a backbuffer copy, screen texture makes no further copies
}
items[item_count++] = ci;
if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {
_render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list, screen_uniform_set);
//then reset
item_count = 0;
}
ci = ci->next;
}
}
RID RasterizerCanvasRD::light_create() {
CanvasLight canvas_light;
canvas_light.shadow.size = 0;
return canvas_light_owner.make_rid(canvas_light);
}
void RasterizerCanvasRD::light_set_texture(RID p_rid, RID p_texture) {
CanvasLight *cl = canvas_light_owner.getornull(p_rid);
ERR_FAIL_COND(!cl);
if (cl->texture == p_texture) {
return;
}
cl->texture = p_texture;
}
void RasterizerCanvasRD::light_set_use_shadow(RID p_rid, bool p_enable, int p_resolution) {
CanvasLight *cl = canvas_light_owner.getornull(p_rid);
ERR_FAIL_COND(!cl);
ERR_FAIL_COND(p_resolution < 64);
if (cl->shadow.texture.is_valid() == p_enable && p_resolution == cl->shadow.size) {
return;
}
if (cl->shadow.texture.is_valid()) {
RD::get_singleton()->free(cl->shadow.fb);
RD::get_singleton()->free(cl->shadow.depth);
RD::get_singleton()->free(cl->shadow.texture);
cl->shadow.fb = RID();
cl->shadow.texture = RID();
cl->shadow.depth = RID();
}
if (p_enable) {
Vector<RID> fb_textures;
{ //texture
RD::TextureFormat tf;
tf.type = RD::TEXTURE_TYPE_2D;
tf.width = p_resolution;
tf.height = 1;
tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
tf.format = RD::DATA_FORMAT_R32_SFLOAT;
cl->shadow.texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
fb_textures.push_back(cl->shadow.texture);
}
{
RD::TextureFormat tf;
tf.type = RD::TEXTURE_TYPE_2D;
tf.width = p_resolution;
tf.height = 1;
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_X8_D24_UNORM_PACK32, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_X8_D24_UNORM_PACK32 : RD::DATA_FORMAT_D32_SFLOAT;
//chunks to write
cl->shadow.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
fb_textures.push_back(cl->shadow.depth);
}
cl->shadow.fb = RD::get_singleton()->framebuffer_create(fb_textures);
}
cl->shadow.size = p_resolution;
}
void RasterizerCanvasRD::light_update_shadow(RID p_rid, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders) {
CanvasLight *cl = canvas_light_owner.getornull(p_rid);
ERR_FAIL_COND(cl->shadow.texture.is_null());
for (int i = 0; i < 4; i++) {
//make sure it remains orthogonal, makes easy to read angle later
//light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1));
Vector<Color> cc;
cc.push_back(Color(p_far, p_far, p_far, 1.0));
RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(cl->shadow.fb, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, cc, 1.0, 0, Rect2i((cl->shadow.size / 4) * i, 0, (cl->shadow.size / 4), 1));
CameraMatrix projection;
{
real_t fov = 90;
real_t nearp = p_near;
real_t farp = p_far;
real_t aspect = 1.0;
real_t ymax = nearp * Math::tan(Math::deg2rad(fov * 0.5));
real_t ymin = -ymax;
real_t xmin = ymin * aspect;
real_t xmax = ymax * aspect;
projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
}
Vector3 cam_target = Basis(Vector3(0, 0, Math_PI * 2 * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
projection = projection * CameraMatrix(Transform().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
ShadowRenderPushConstant push_constant;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
push_constant.projection[y * 4 + x] = projection.matrix[y][x];
}
}
static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };
push_constant.direction[0] = directions[i].x;
push_constant.direction[1] = directions[i].y;
push_constant.pad[0] = 0;
push_constant.pad[1] = 0;
/*if (i == 0)
*p_xform_cache = projection;*/
LightOccluderInstance *instance = p_occluders;
while (instance) {
OccluderPolygon *co = occluder_polygon_owner.getornull(instance->occluder);
if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {
instance = instance->next;
continue;
}
_update_transform_2d_to_mat2x4(p_light_xform * instance->xform_cache, push_constant.modelview);
RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[co->cull_mode]);
RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);
RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);
RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
RD::get_singleton()->draw_list_draw(draw_list, true);
instance = instance->next;
}
RD::get_singleton()->draw_list_end();
}
}
RID RasterizerCanvasRD::occluder_polygon_create() {
OccluderPolygon occluder;
occluder.point_count = 0;
occluder.cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
return occluder_polygon_owner.make_rid(occluder);
}
void RasterizerCanvasRD::occluder_polygon_set_shape_as_lines(RID p_occluder, const Vector<Vector2> &p_lines) {
OccluderPolygon *oc = occluder_polygon_owner.getornull(p_occluder);
ERR_FAIL_COND(!oc);
if (oc->point_count != p_lines.size() && oc->vertex_array.is_valid()) {
RD::get_singleton()->free(oc->vertex_array);
RD::get_singleton()->free(oc->vertex_buffer);
RD::get_singleton()->free(oc->index_array);
RD::get_singleton()->free(oc->index_buffer);
oc->vertex_array = RID();
oc->vertex_buffer = RID();
oc->index_array = RID();
oc->index_buffer = RID();
}
if (p_lines.size()) {
Vector<uint8_t> geometry;
Vector<uint8_t> indices;
int lc = p_lines.size();
geometry.resize(lc * 6 * sizeof(float));
indices.resize(lc * 3 * sizeof(uint16_t));
{
uint8_t *vw = geometry.ptrw();
float *vwptr = (float *)vw;
uint8_t *iw = indices.ptrw();
uint16_t *iwptr = (uint16_t *)iw;
const Vector2 *lr = p_lines.ptr();
const int POLY_HEIGHT = 16384;
for (int i = 0; i < lc / 2; i++) {
vwptr[i * 12 + 0] = lr[i * 2 + 0].x;
vwptr[i * 12 + 1] = lr[i * 2 + 0].y;
vwptr[i * 12 + 2] = POLY_HEIGHT;
vwptr[i * 12 + 3] = lr[i * 2 + 1].x;
vwptr[i * 12 + 4] = lr[i * 2 + 1].y;
vwptr[i * 12 + 5] = POLY_HEIGHT;
vwptr[i * 12 + 6] = lr[i * 2 + 1].x;
vwptr[i * 12 + 7] = lr[i * 2 + 1].y;
vwptr[i * 12 + 8] = -POLY_HEIGHT;
vwptr[i * 12 + 9] = lr[i * 2 + 0].x;
vwptr[i * 12 + 10] = lr[i * 2 + 0].y;
vwptr[i * 12 + 11] = -POLY_HEIGHT;
iwptr[i * 6 + 0] = i * 4 + 0;
iwptr[i * 6 + 1] = i * 4 + 1;
iwptr[i * 6 + 2] = i * 4 + 2;
iwptr[i * 6 + 3] = i * 4 + 2;
iwptr[i * 6 + 4] = i * 4 + 3;
iwptr[i * 6 + 5] = i * 4 + 0;
}
}
//if same buffer len is being set, just use BufferSubData to avoid a pipeline flush
if (oc->vertex_array.is_null()) {
//create from scratch
//vertices
oc->vertex_buffer = RD::get_singleton()->vertex_buffer_create(lc * 6 * sizeof(real_t), geometry);
Vector<RID> buffer;
buffer.push_back(oc->vertex_buffer);
oc->vertex_array = RD::get_singleton()->vertex_array_create(4 * lc / 2, shadow_render.vertex_format, buffer);
//indices
oc->index_buffer = RD::get_singleton()->index_buffer_create(3 * lc, RD::INDEX_BUFFER_FORMAT_UINT16, indices);
oc->index_array = RD::get_singleton()->index_array_create(oc->index_buffer, 0, 3 * lc);
} else {
//update existing
const uint8_t *vr = geometry.ptr();
RD::get_singleton()->buffer_update(oc->vertex_buffer, 0, geometry.size(), vr);
const uint8_t *ir = indices.ptr();
RD::get_singleton()->buffer_update(oc->index_buffer, 0, indices.size(), ir);
}
}
}
void RasterizerCanvasRD::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {
OccluderPolygon *oc = occluder_polygon_owner.getornull(p_occluder);
ERR_FAIL_COND(!oc);
oc->cull_mode = p_mode;
}
void RasterizerCanvasRD::ShaderData::set_code(const String &p_code) {
//compile
code = p_code;
valid = false;
ubo_size = 0;
uniforms.clear();
uses_screen_texture = false;
uses_material_samplers = false;
if (code == String()) {
return; //just invalid, but no error
}
ShaderCompilerRD::GeneratedCode gen_code;
int light_mode = LIGHT_MODE_NORMAL;
int blend_mode = BLEND_MODE_MIX;
uses_screen_texture = false;
ShaderCompilerRD::IdentifierActions actions;
actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_mode, BLEND_MODE_ADD);
actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MIX);
actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_mode, BLEND_MODE_SUB);
actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MUL);
actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_mode, BLEND_MODE_PMALPHA);
actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_mode, BLEND_MODE_DISABLED);
actions.render_mode_values["unshaded"] = Pair<int *, int>(&light_mode, LIGHT_MODE_UNSHADED);
actions.render_mode_values["light_only"] = Pair<int *, int>(&light_mode, LIGHT_MODE_LIGHT_ONLY);
actions.usage_flag_pointers["SCREEN_TEXTURE"] = &uses_screen_texture;
actions.uniforms = &uniforms;
RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
ERR_FAIL_COND(err != OK);
if (version.is_null()) {
version = canvas_singleton->shader.canvas_shader.version_create();
}
if (gen_code.texture_uniforms.size() || uses_screen_texture) { //requires the samplers
gen_code.defines.push_back("\n#define USE_MATERIAL_SAMPLERS\n");
uses_material_samplers = true;
}
#if 0
print_line("**compiling shader:");
print_line("**defines:\n");
for (int i = 0; i < gen_code.defines.size(); i++) {
print_line(gen_code.defines[i]);
}
print_line("\n**uniforms:\n" + gen_code.uniforms);
print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
print_line("\n**vertex_code:\n" + gen_code.vertex);
print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
print_line("\n**fragment_code:\n" + gen_code.fragment);
print_line("\n**light_code:\n" + gen_code.light);
#endif
canvas_singleton->shader.canvas_shader.version_set_code(version, gen_code.uniforms, gen_code.vertex_global, gen_code.vertex, gen_code.fragment_global, gen_code.light, gen_code.fragment, gen_code.defines);
ERR_FAIL_COND(!canvas_singleton->shader.canvas_shader.version_is_valid(version));
ubo_size = gen_code.uniform_total_size;
ubo_offsets = gen_code.uniform_offsets;
texture_uniforms = gen_code.texture_uniforms;
//update them pipelines
RD::PipelineColorBlendState::Attachment attachment;
switch (blend_mode) {
case BLEND_MODE_DISABLED: {
// nothing to do here, disabled by default
} break;
case BLEND_MODE_MIX: {
attachment.enable_blend = true;
attachment.alpha_blend_op = RD::BLEND_OP_ADD;
attachment.color_blend_op = RD::BLEND_OP_ADD;
attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
} break;
case BLEND_MODE_ADD: {
attachment.enable_blend = true;
attachment.alpha_blend_op = RD::BLEND_OP_ADD;
attachment.color_blend_op = RD::BLEND_OP_ADD;
attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE;
attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
} break;
case BLEND_MODE_SUB: {
attachment.enable_blend = true;
attachment.alpha_blend_op = RD::BLEND_OP_SUBTRACT;
attachment.color_blend_op = RD::BLEND_OP_SUBTRACT;
attachment.src_color_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE;
attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_SRC_ALPHA;
attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
} break;
case BLEND_MODE_MUL: {
attachment.enable_blend = true;
attachment.alpha_blend_op = RD::BLEND_OP_ADD;
attachment.color_blend_op = RD::BLEND_OP_ADD;
attachment.src_color_blend_factor = RD::BLEND_FACTOR_DST_COLOR;
attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ZERO;
attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_DST_ALPHA;
attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
} break;
case BLEND_MODE_PMALPHA: {
attachment.enable_blend = true;
attachment.alpha_blend_op = RD::BLEND_OP_ADD;
attachment.color_blend_op = RD::BLEND_OP_ADD;
attachment.src_color_blend_factor = RD::BLEND_FACTOR_ONE;
attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
} break;
}
RD::PipelineColorBlendState blend_state;
blend_state.attachments.push_back(attachment);
//update pipelines
for (int i = 0; i < PIPELINE_LIGHT_MODE_MAX; i++) {
for (int j = 0; j < PIPELINE_VARIANT_MAX; j++) {
RD::RenderPrimitive primitive[PIPELINE_VARIANT_MAX] = {
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_LINES,
RD::RENDER_PRIMITIVE_POINTS,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS,
RD::RENDER_PRIMITIVE_LINES,
RD::RENDER_PRIMITIVE_LINESTRIPS,
RD::RENDER_PRIMITIVE_POINTS,
};
ShaderVariant shader_variants[PIPELINE_LIGHT_MODE_MAX][PIPELINE_VARIANT_MAX] = {
{ //non lit
SHADER_VARIANT_QUAD,
SHADER_VARIANT_NINEPATCH,
SHADER_VARIANT_PRIMITIVE,
SHADER_VARIANT_PRIMITIVE,
SHADER_VARIANT_PRIMITIVE_POINTS,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES_POINTS },
{ //lit
SHADER_VARIANT_QUAD_LIGHT,
SHADER_VARIANT_NINEPATCH_LIGHT,
SHADER_VARIANT_PRIMITIVE_LIGHT,
SHADER_VARIANT_PRIMITIVE_LIGHT,
SHADER_VARIANT_PRIMITIVE_POINTS_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_POINTS_LIGHT },
};
RID shader_variant = canvas_singleton->shader.canvas_shader.version_get_shader(version, shader_variants[i][j]);
pipeline_variants.variants[i][j].setup(shader_variant, primitive[j], RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), blend_state, 0);
}
}
valid = true;
}
void RasterizerCanvasRD::ShaderData::set_default_texture_param(const StringName &p_name, RID p_texture) {
if (!p_texture.is_valid()) {
default_texture_params.erase(p_name);
} else {
default_texture_params[p_name] = p_texture;
}
}
void RasterizerCanvasRD::ShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
Map<int, StringName> order;
for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_LOCAL) {
continue;
}
if (E->get().texture_order >= 0) {
order[E->get().texture_order + 100000] = E->key();
} else {
order[E->get().order] = E->key();
}
}
for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E->get()]);
pi.name = E->get();
p_param_list->push_back(pi);
}
}
void RasterizerCanvasRD::ShaderData::get_instance_param_list(List<RasterizerStorage::InstanceShaderParam> *p_param_list) const {
for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
continue;
}
RasterizerStorage::InstanceShaderParam p;
p.info = ShaderLanguage::uniform_to_property_info(E->get());
p.info.name = E->key(); //supply name
p.index = E->get().instance_index;
p.default_value = ShaderLanguage::constant_value_to_variant(E->get().default_value, E->get().type, E->get().hint);
p_param_list->push_back(p);
}
}
bool RasterizerCanvasRD::ShaderData::is_param_texture(const StringName &p_param) const {
if (!uniforms.has(p_param)) {
return false;
}
return uniforms[p_param].texture_order >= 0;
}
bool RasterizerCanvasRD::ShaderData::is_animated() const {
return false;
}
bool RasterizerCanvasRD::ShaderData::casts_shadows() const {
return false;
}
Variant RasterizerCanvasRD::ShaderData::get_default_parameter(const StringName &p_parameter) const {
if (uniforms.has(p_parameter)) {
ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
}
return Variant();
}
RasterizerCanvasRD::ShaderData::ShaderData() {
valid = false;
uses_screen_texture = false;
uses_material_samplers = false;
}
RasterizerCanvasRD::ShaderData::~ShaderData() {
RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
ERR_FAIL_COND(!canvas_singleton);
//pipeline variants will clear themselves if shader is gone
if (version.is_valid()) {
canvas_singleton->shader.canvas_shader.version_free(version);
}
}
RasterizerStorageRD::ShaderData *RasterizerCanvasRD::_create_shader_func() {
ShaderData *shader_data = memnew(ShaderData);
return shader_data;
}
void RasterizerCanvasRD::MaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
RasterizerCanvasRD *canvas_singleton = (RasterizerCanvasRD *)RasterizerCanvas::singleton;
if ((uint32_t)ubo_data.size() != shader_data->ubo_size) {
p_uniform_dirty = true;
if (uniform_buffer.is_valid()) {
RD::get_singleton()->free(uniform_buffer);
uniform_buffer = RID();
}
ubo_data.resize(shader_data->ubo_size);
if (ubo_data.size()) {
uniform_buffer = RD::get_singleton()->uniform_buffer_create(ubo_data.size());
memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
}
//clear previous uniform set
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
uniform_set = RID();
}
}
//check whether buffer changed
if (p_uniform_dirty && ubo_data.size()) {
update_uniform_buffer(shader_data->uniforms, shader_data->ubo_offsets.ptr(), p_parameters, ubo_data.ptrw(), ubo_data.size(), false);
RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw());
}
uint32_t tex_uniform_count = shader_data->texture_uniforms.size();
if ((uint32_t)texture_cache.size() != tex_uniform_count) {
texture_cache.resize(tex_uniform_count);
p_textures_dirty = true;
//clear previous uniform set
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
uniform_set = RID();
}
}
if (p_textures_dirty && tex_uniform_count) {
update_textures(p_parameters, shader_data->default_texture_params, shader_data->texture_uniforms, texture_cache.ptrw(), false);
}
if (shader_data->ubo_size == 0 && !shader_data->uses_material_samplers) {
// This material does not require an uniform set, so don't create it.
return;
}
if (!p_textures_dirty && uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
//no reason to update uniform set, only UBO (or nothing) was needed to update
return;
}
Vector<RD::Uniform> uniforms;
{
if (shader_data->uses_material_samplers) {
//needs samplers for the material (uses custom textures) create them
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_SAMPLER;
u.binding = 0;
u.ids.resize(12);
RID *ids_ptr = u.ids.ptrw();
ids_ptr[0] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[1] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[2] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[3] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[4] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[5] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
ids_ptr[6] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[7] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[8] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[9] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[10] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
ids_ptr[11] = canvas_singleton->storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
uniforms.push_back(u);
}
if (shader_data->ubo_size) {
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
u.binding = 1;
u.ids.push_back(uniform_buffer);
uniforms.push_back(u);
}
const RID *textures = texture_cache.ptrw();
for (uint32_t i = 0; i < tex_uniform_count; i++) {
RD::Uniform u;
u.type = RD::UNIFORM_TYPE_TEXTURE;
u.binding = 2 + i;
u.ids.push_back(textures[i]);
uniforms.push_back(u);
}
}
uniform_set = RD::get_singleton()->uniform_set_create(uniforms, canvas_singleton->shader.canvas_shader.version_get_shader(shader_data->version, 0), 1);
}
RasterizerCanvasRD::MaterialData::~MaterialData() {
if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
RD::get_singleton()->free(uniform_set);
}
if (uniform_buffer.is_valid()) {
RD::get_singleton()->free(uniform_buffer);
}
}
RasterizerStorageRD::MaterialData *RasterizerCanvasRD::_create_material_func(ShaderData *p_shader) {
MaterialData *material_data = memnew(MaterialData);
material_data->shader_data = p_shader;
material_data->last_frame = false;
//update will happen later anyway so do nothing.
return material_data;
}
void RasterizerCanvasRD::set_time(double p_time) {
state.time = p_time;
}
void RasterizerCanvasRD::update() {
_dispose_bindings();
}
RasterizerCanvasRD::RasterizerCanvasRD(RasterizerStorageRD *p_storage) {
storage = p_storage;
{ //create default samplers
default_samplers.default_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;
default_samplers.default_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;
}
{ //shader variants
uint32_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
String global_defines;
if (textures_per_stage <= 16) {
//ARM pretty much, and very old Intel GPUs under Linux
state.max_lights_per_item = 4; //sad
global_defines += "#define MAX_LIGHT_TEXTURES 4\n";
} else if (textures_per_stage <= 32) {
//Apple (Metal)
state.max_lights_per_item = 8; //sad
global_defines += "#define MAX_LIGHT_TEXTURES 8\n";
} else {
//Anything else (16 lights per item)
state.max_lights_per_item = DEFAULT_MAX_LIGHTS_PER_ITEM;
global_defines += "#define MAX_LIGHT_TEXTURES " + itos(DEFAULT_MAX_LIGHTS_PER_ITEM) + "\n";
}
uint32_t uniform_max_size = RD::get_singleton()->limit_get(RD::LIMIT_MAX_UNIFORM_BUFFER_SIZE);
if (uniform_max_size < 65536) {
//Yes, you guessed right, ARM again
state.max_lights_per_render = 64;
global_defines += "#define MAX_LIGHTS 64\n";
} else {
state.max_lights_per_render = DEFAULT_MAX_LIGHTS_PER_RENDER;
global_defines += "#define MAX_LIGHTS " + itos(DEFAULT_MAX_LIGHTS_PER_RENDER) + "\n";
}
state.light_uniforms = memnew_arr(LightUniform, state.max_lights_per_render);
Vector<String> variants;
//non light variants
variants.push_back(""); //none by default is first variant
variants.push_back("#define USE_NINEPATCH\n"); //ninepatch is the second variant
variants.push_back("#define USE_PRIMITIVE\n"); //primitive is the third
variants.push_back("#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); //points need point size
variants.push_back("#define USE_ATTRIBUTES\n"); // attributes for vertex arrays
variants.push_back("#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); //attributes with point size
//light variants
variants.push_back("#define USE_LIGHTING\n"); //none by default is first variant
variants.push_back("#define USE_LIGHTING\n#define USE_NINEPATCH\n"); //ninepatch is the second variant
variants.push_back("#define USE_LIGHTING\n#define USE_PRIMITIVE\n"); //primitive is the third
variants.push_back("#define USE_LIGHTING\n#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); //points need point size
variants.push_back("#define USE_LIGHTING\n#define USE_ATTRIBUTES\n"); // attributes for vertex arrays
variants.push_back("#define USE_LIGHTING\n#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); //attributes with point size
shader.canvas_shader.initialize(variants, global_defines);
shader.default_version = shader.canvas_shader.version_create();
shader.default_version_rd_shader = shader.canvas_shader.version_get_shader(shader.default_version, SHADER_VARIANT_QUAD);
shader.default_version_rd_shader_light = shader.canvas_shader.version_get_shader(shader.default_version, SHADER_VARIANT_QUAD_LIGHT);
for (int i = 0; i < PIPELINE_LIGHT_MODE_MAX; i++) {
for (int j = 0; j < PIPELINE_VARIANT_MAX; j++) {
RD::RenderPrimitive primitive[PIPELINE_VARIANT_MAX] = {
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_LINES,
RD::RENDER_PRIMITIVE_POINTS,
RD::RENDER_PRIMITIVE_TRIANGLES,
RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS,
RD::RENDER_PRIMITIVE_LINES,
RD::RENDER_PRIMITIVE_LINESTRIPS,
RD::RENDER_PRIMITIVE_POINTS,
};
ShaderVariant shader_variants[PIPELINE_LIGHT_MODE_MAX][PIPELINE_VARIANT_MAX] = {
{ //non lit
SHADER_VARIANT_QUAD,
SHADER_VARIANT_NINEPATCH,
SHADER_VARIANT_PRIMITIVE,
SHADER_VARIANT_PRIMITIVE,
SHADER_VARIANT_PRIMITIVE_POINTS,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES,
SHADER_VARIANT_ATTRIBUTES_POINTS },
{ //lit
SHADER_VARIANT_QUAD_LIGHT,
SHADER_VARIANT_NINEPATCH_LIGHT,
SHADER_VARIANT_PRIMITIVE_LIGHT,
SHADER_VARIANT_PRIMITIVE_LIGHT,
SHADER_VARIANT_PRIMITIVE_POINTS_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_LIGHT,
SHADER_VARIANT_ATTRIBUTES_POINTS_LIGHT },
};
RID shader_variant = shader.canvas_shader.version_get_shader(shader.default_version, shader_variants[i][j]);
shader.pipeline_variants.variants[i][j].setup(shader_variant, primitive[j], RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_blend(), 0);
}
}
}
{
//shader compiler
ShaderCompilerRD::DefaultIdentifierActions actions;
actions.renames["VERTEX"] = "vertex";
actions.renames["LIGHT_VERTEX"] = "light_vertex";
actions.renames["SHADOW_VERTEX"] = "shadow_vertex";
actions.renames["UV"] = "uv";
actions.renames["POINT_SIZE"] = "gl_PointSize";
actions.renames["WORLD_MATRIX"] = "world_matrix";
actions.renames["CANVAS_MATRIX"] = "canvas_data.canvas_transform";
actions.renames["SCREEN_MATRIX"] = "canvas_data.screen_transform";
actions.renames["TIME"] = "canvas_data.time";
actions.renames["AT_LIGHT_PASS"] = "false";
actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
actions.renames["COLOR"] = "color";
actions.renames["NORMAL"] = "normal";
actions.renames["NORMALMAP"] = "normal_map";
actions.renames["NORMALMAP_DEPTH"] = "normal_depth";
actions.renames["TEXTURE"] = "color_texture";
actions.renames["TEXTURE_PIXEL_SIZE"] = "draw_data.color_texture_pixel_size";
actions.renames["NORMAL_TEXTURE"] = "normal_texture";
actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";
actions.renames["SPECULAR_SHININESS"] = "specular_shininess";
actions.renames["SCREEN_UV"] = "screen_uv";
actions.renames["SCREEN_TEXTURE"] = "screen_texture";
actions.renames["SCREEN_PIXEL_SIZE"] = "canvas_data.screen_pixel_size";
actions.renames["FRAGCOORD"] = "gl_FragCoord";
actions.renames["POINT_COORD"] = "gl_PointCoord";
actions.renames["LIGHT_POSITION"] = "light_pos";
actions.renames["LIGHT_COLOR"] = "light_color";
actions.renames["LIGHT_ENERGY"] = "light_energy";
actions.renames["LIGHT"] = "light";
actions.renames["SHADOW_MODULATE"] = "shadow_modulate";
actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
actions.usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";
actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
actions.usage_defines["NORMALMAP"] = "#define NORMALMAP_USED\n";
actions.usage_defines["LIGHT"] = "#define LIGHT_SHADER_CODE_USED\n";
actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
actions.custom_samplers["TEXTURE"] = "texture_sampler";
actions.custom_samplers["NORMAL_TEXTURE"] = "texture_sampler";
actions.custom_samplers["SPECULAR_SHININESS_TEXTURE"] = "texture_sampler";
actions.custom_samplers["SCREEN_TEXTURE"] = "material_samplers[3]"; //mipmap and filter for screen texture
actions.sampler_array_name = "material_samplers";
actions.base_texture_binding_index = 2;
actions.texture_layout_set = 1;
actions.base_uniform_string = "material.";
actions.default_filter = ShaderLanguage::FILTER_LINEAR;
actions.default_repeat = ShaderLanguage::REPEAT_DISABLE;
actions.base_varying_index = 4;
actions.global_buffer_array_variable = "global_variables.data";
shader.compiler.initialize(actions);
}
{ //shadow rendering
Vector<String> versions;
versions.push_back(String()); //no versions
shadow_render.shader.initialize(versions);
{
Vector<RD::AttachmentFormat> attachments;
RD::AttachmentFormat af_color;
af_color.format = RD::DATA_FORMAT_R32_SFLOAT;
af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
attachments.push_back(af_color);
RD::AttachmentFormat af_depth;
af_depth.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
af_depth.usage_flags = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
attachments.push_back(af_depth);
shadow_render.framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);
}
//pipelines
Vector<RD::VertexAttribute> vf;
RD::VertexAttribute vd;
vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT;
vd.location = 0;
vd.offset = 0;
vd.stride = sizeof(float) * 3;
vf.push_back(vd);
shadow_render.vertex_format = RD::get_singleton()->vertex_format_create(vf);
shadow_render.shader_version = shadow_render.shader.version_create();
for (int i = 0; i < 3; i++) {
RD::PipelineRasterizationState rs;
rs.cull_mode = i == 0 ? RD::POLYGON_CULL_DISABLED : (i == 1 ? RD::POLYGON_CULL_FRONT : RD::POLYGON_CULL_BACK);
RD::PipelineDepthStencilState ds;
ds.enable_depth_write = true;
ds.enable_depth_test = true;
ds.depth_compare_operator = RD::COMPARE_OP_LESS;
shadow_render.render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, 0), shadow_render.framebuffer_format, shadow_render.vertex_format, RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
}
}
{ //bindings
bindings.id_generator = 0;
//generate for 0
bindings.default_empty = request_texture_binding(RID(), RID(), RID(), RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT, RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT, RID());
{ //state allocate
state.canvas_state_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(State::Buffer));
state.lights_uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(LightUniform) * state.max_lights_per_render);
RD::SamplerState shadow_sampler_state;
shadow_sampler_state.mag_filter = RD::SAMPLER_FILTER_LINEAR;
shadow_sampler_state.min_filter = RD::SAMPLER_FILTER_LINEAR;
shadow_sampler_state.repeat_u = RD::SAMPLER_REPEAT_MODE_REPEAT; //shadow wrap around
shadow_sampler_state.compare_op = RD::COMPARE_OP_GREATER;
state.shadow_sampler = RD::get_singleton()->sampler_create(shadow_sampler_state);
}
}
{
//polygon buffers
polygon_buffers.last_id = 1;
}
{ // default index buffer
Vector<uint8_t> pv;
pv.resize(6 * 4);
{
uint8_t *w = pv.ptrw();
int *p32 = (int *)w;
p32[0] = 0;
p32[1] = 1;
p32[2] = 2;
p32[3] = 0;
p32[4] = 2;
p32[5] = 3;
}
shader.quad_index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT32, pv);
shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
}
{ //primitive
primitive_arrays.index_array[0] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 1);
primitive_arrays.index_array[1] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 2);
primitive_arrays.index_array[2] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 3);
primitive_arrays.index_array[3] = shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
}
{ //default skeleton buffer
shader.default_skeleton_uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkeletonUniform));
SkeletonUniform su;
_update_transform_2d_to_mat4(Transform2D(), su.skeleton_inverse);
_update_transform_2d_to_mat4(Transform2D(), su.skeleton_transform);
RD::get_singleton()->buffer_update(shader.default_skeleton_uniform_buffer, 0, sizeof(SkeletonUniform), &su);
shader.default_skeleton_texture_buffer = RD::get_singleton()->texture_buffer_create(32, RD::DATA_FORMAT_R32G32B32A32_SFLOAT);
}
//create functions for shader and material
storage->shader_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_2D, _create_shader_funcs);
storage->material_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_2D, _create_material_funcs);
state.time = 0;
static_assert(sizeof(PushConstant) == 128);
}
bool RasterizerCanvasRD::free(RID p_rid) {
if (canvas_light_owner.owns(p_rid)) {
CanvasLight *cl = canvas_light_owner.getornull(p_rid);
ERR_FAIL_COND_V(!cl, false);
light_set_use_shadow(p_rid, false, 64);
canvas_light_owner.free(p_rid);
} else if (occluder_polygon_owner.owns(p_rid)) {
occluder_polygon_set_shape_as_lines(p_rid, Vector<Vector2>());
occluder_polygon_owner.free(p_rid);
} else {
return false;
}
return true;
}
RasterizerCanvasRD::~RasterizerCanvasRD() {
//canvas state
{
if (state.canvas_state_buffer.is_valid()) {
RD::get_singleton()->free(state.canvas_state_buffer);
}
memdelete_arr(state.light_uniforms);
RD::get_singleton()->free(state.lights_uniform_buffer);
RD::get_singleton()->free(shader.default_skeleton_uniform_buffer);
RD::get_singleton()->free(shader.default_skeleton_texture_buffer);
}
//shadow rendering
{
shadow_render.shader.version_free(shadow_render.shader_version);
//this will also automatically clear all pipelines
RD::get_singleton()->free(state.shadow_sampler);
}
//bindings
{
free_texture_binding(bindings.default_empty);
//dispose pending
_dispose_bindings();
//anything remains?
if (bindings.texture_bindings.size()) {
ERR_PRINT("Some texture bindings were not properly freed (leaked CanvasItems?)");
const TextureBindingID *key = nullptr;
while ((key = bindings.texture_bindings.next(key))) {
TextureBinding *tb = bindings.texture_bindings[*key];
tb->reference_count = 1;
free_texture_binding(*key);
}
//dispose pending
_dispose_bindings();
}
}
//shaders
shader.canvas_shader.version_free(shader.default_version);
//buffers
{
RD::get_singleton()->free(shader.quad_index_array);
RD::get_singleton()->free(shader.quad_index_buffer);
//primitives are erase by dependency
}
//pipelines don't need freeing, they are all gone after shaders are gone
}
| {
"content_hash": "78bf5cd155ab660f3fe46bb641b9a128",
"timestamp": "",
"source": "github",
"line_count": 2524,
"max_line_length": 343,
"avg_line_length": 37.80110935023772,
"alnum_prop": 0.674635782412745,
"repo_name": "Paulloz/godot",
"id": "aad2be45c685c7613aa9675a1593a2abc39db5d7",
"size": "95410",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "servers/rendering/rasterizer_rd/rasterizer_canvas_rd.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "50004"
},
{
"name": "C#",
"bytes": "176259"
},
{
"name": "C++",
"bytes": "18569070"
},
{
"name": "GLSL",
"bytes": "1271"
},
{
"name": "Java",
"bytes": "495377"
},
{
"name": "JavaScript",
"bytes": "14680"
},
{
"name": "Makefile",
"bytes": "451"
},
{
"name": "Objective-C",
"bytes": "2645"
},
{
"name": "Objective-C++",
"bytes": "173262"
},
{
"name": "Python",
"bytes": "336142"
},
{
"name": "Shell",
"bytes": "19610"
}
],
"symlink_target": ""
} |
<HTML>
<HEAD>
<TITLE>3rd Party ROBOTC Drivers</TITLE>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</HEAD>
<BODY bgcolor="#ffffff" link="#000000" vlink="#000000">
<table width="100%" bgcolor="navy" cellspacing=0 cellpadding=1 border=0>
<tr><td><table width="100%" bgcolor="#EEEEDD" cellspacing=0 cellpadding=3 border=0>
<tr>
<td width="33%" align="left"> <img src="images/LOGO_NXT.gif" width=266 height=44 border="0" alt="Mindstorms"></td>
<td><b><font size="+3" color="navy">3rd Party ROBOTC Drivers</font></b></td>
<td align="right"> <img src="images/logo.png" width=44 height=44 border="0" alt="RobotC"></td>
</tr>
<tr bgcolor="#cccc99" align="right">
<td colspan=3> <font face="arial" size="-1"> [<a href=main.html>Home</a>] [<a target=_top href="https://sourceforge.net/projects/rdpartyrobotcdr/">Download</a>] [<a target=_top href="http://apps.sourceforge.net/mantisbt/rdpartyrobotcdr/my_view_page.php">Submit a bug/suggestion</a>] [<a target=_top href="http://www.robotc.net/forums/">ROBOTC Forums</a>] [<a target=_top href="http://botbench.com">Blog</a>] [<a target=_top href="http://sourceforge.net/donate/index.php?group_id=257238">Support this project</a>]</font> </td>
</tr>
</table></td></tr>
</table>
<!-- Generated by Doxygen 1.7.2 -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<h1>lego-touch.h File Reference</h1> </div>
</div>
<div class="contents">
<p>Lego Touch Sensor driver.
<a href="#_details">More...</a></p>
<code>#include "<a class="el" href="common_8h_source.html">common.h</a>"</code><br/>
<p><a href="lego-touch_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="func-members"></a>
Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="group__legots.html#gaae0bd904b0c84005903f271d24df84d9">TSreadState</a> (tSensors link)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="group__legots.html#ga387ef588aff2948ef40ea551322f6e53">TSreadState</a> (<a class="el" href="group__htsmux.html#gab5bad1759ac110c43e66c3ec54047f42">tMUXSensor</a> muxsensor)</td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<p>Lego Touch Sensor driver. </p>
<p><a class="el" href="lego-touch_8h.html" title="Lego Touch Sensor driver.">lego-touch.h</a> provides an API for the Lego Touch Sensor.</p>
<p>Changelog:</p>
<ul>
<li>0.1: Initial release</li>
</ul>
<p>License: You may use this code as you wish, provided you give credit where its due.</p>
<p>THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 3.59 AND HIGHER.</p>
<dl class="author"><dt><b>Author:</b></dt><dd>Xander Soldaat (xander_at_botbench.com) </dd></dl>
<dl class="date"><dt><b>Date:</b></dt><dd>08 December 2009 </dd></dl>
<dl class="version"><dt><b>Version:</b></dt><dd>0.1 </dd></dl>
<p>Definition in file <a class="el" href="lego-touch_8h_source.html">lego-touch.h</a>.</p>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Wed Mar 13 2013 19:56:43 for ROBOTC Drivers by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| {
"content_hash": "031c79353839d2ef7ab3bab9c0914b88",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 537,
"avg_line_length": 58.55,
"alnum_prop": 0.672929120409906,
"repo_name": "OlsonElliott/Easy-as-Pi",
"id": "2d006b498722763a9f705505f0ef1b6fb01aba73",
"size": "3513",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "rdpartyrobotcdr-3.3.1/html/lego-touch_8h.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "732203"
},
{
"name": "C++",
"bytes": "405197"
},
{
"name": "CSS",
"bytes": "11651"
},
{
"name": "Objective-C",
"bytes": "5909"
}
],
"symlink_target": ""
} |
MAGVAF05 ;WOIFO/NST - Utilities for RPC calls ; 14 Sep 2011 1:55 PM
;;3.0;IMAGING;**118**;Mar 19, 2002;Build 4525;May 01, 2013
;; Per VHA Directive 2004-038, this routine should not be modified.
;; +---------------------------------------------------------------+
;; | Property of the US Government. |
;; | No permission to copy or redistribute this software is given. |
;; | Use of unreleased versions of this software requires the user |
;; | to execute a written test agreement with the VistA Imaging |
;; | Development Office of the Department of Veterans Affairs, |
;; | telephone (301) 734-0100. |
;; | The Food and Drug Administration classifies this software as |
;; | a medical device. As such, it may not be changed in any way. |
;; | Modifications to this software may result in an adulterated |
;; | medical device under 21CFR820, the use of which is considered |
;; | to be a violation of US Federal Statutes. |
;; +---------------------------------------------------------------+
;;
Q
; +++++ Return IEN of the record with .01 field equals VALUE
; If record is not found a new record will be added if a add flag is set to true
;
; Input parameters
; ================
; FILE = FileMan file number (e.g. 2006.9193)
; VALUE = External or internal value of .01 field
; ADD = Add a new record if the VALUE is not found (e.g. 0/1)
GETIEN(FILE,VALUE,ADD) ; Return IEN of the record with .01 field equals VALUE
N MAGNFDA,MAGNIEN,MAGNXE,IEN,MAGRY
I (VALUE=0)!(VALUE<0) Q $$FAILED^MAGVAF02()_$$RESDEL^MAGVAF02()_"Unexpected value of #"_FILE_".01 :"_VALUE ; Error
; Do we have IEN?
I +VALUE=VALUE D SETOKVAL^MAGVAF02(.MAGRY,VALUE) Q MAGRY
; Find the IEN by VALUE
S IEN=$$FIND1^DIC(FILE,"","BX",VALUE,"","","MAGNXE") ; Find the IEN for VALUE
I $D(MAGNXE("DIERR")) Q $$FAILED^MAGVAF02()_$$RESDEL^MAGVAF02()_$G(MAGNXE("DIERR",1,"TEXT",1))
I IEN>0 D SETOKVAL^MAGVAF02(.MAGRY,IEN) Q MAGRY
; Return error if we don't need to add a new record
I 'ADD Q $$FAILED^MAGVAF02()_$$RESDEL^MAGVAF02()_"Record "_VALUE_" is not found in file #"_FILE
; Add a new record to FILE and return IEN of the new record
S MAGNFDA(FILE,"+1,",.01)=VALUE
D UPDATE^DIE("S","MAGNFDA","MAGNIEN","MAGNXE")
I $D(MAGNXE("DIERR","E")) Q $$FAILED^MAGVAF02()_$$RESDEL^MAGVAF02()_$G(MAGNXE("DIERR",1,"TEXT",1))
D SETOKVAL^MAGVAF02(.MAGRY,MAGNIEN(1))
Q MAGRY
;
; Input parameters
; ================
; FILE = FileMan file number (e.g. 2006.916)
; FIELD = Field number or name (e.g. "CREATING APPLICATION" or 6)
;
GETFILEP(FILE,FIELD) ; Returns the file that a FIELD in file FILE points to
Q $P($$GET1^DID(FILE,FIELD,"","SPECIFIER"),"P",2)
| {
"content_hash": "a9fa31d56b4803ddfa87a80d501de741",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 115,
"avg_line_length": 54.294117647058826,
"alnum_prop": 0.612856626941134,
"repo_name": "apexdatasolutions/VistA-M",
"id": "e335c16c9acd56ded0f3747923f2d0e0480f570d",
"size": "2769",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Packages/Imaging/Routines/MAGVAF05.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "M",
"bytes": "142217686"
},
{
"name": "Matlab",
"bytes": "379"
}
],
"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"/>
<title>src/plottables/plottable-financial.h File Reference</title>
<link href="qt.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class=header>
<a class=headerLink href="index.html">Main Page</a> ·
<a class=headerLink href="classoverview.html">Class Overview</a> ·
<a class=headerLink href="hierarchy.html">Hierarchy</a> ·
<a class=headerLink href="annotated.html">All Classes</a>
</div>
<!-- Generated by Doxygen 1.8.6 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_d1ab82e73f77cddd99808c625b504457.html">plottables</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Data Structures</a> |
<a href="#typedef-members">Typedefs</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">plottable-financial.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include "<a class="el" href="global_8h_source.html">../global.h</a>"</code><br/>
<code>#include "../range.h"</code><br/>
<code>#include "../plottable.h"</code><br/>
<code>#include "../painter.h"</code><br/>
</div>
<p><a href="plottable-financial_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Data Structures</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classQCPFinancialData.html">QCPFinancialData</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Holds the data of one single data point for <a class="el" href="classQCPFinancial.html" title="A plottable representing a financial stock chart. ">QCPFinancial</a>. <a href="classQCPFinancialData.html#details">More...</a><br/></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classQCPFinancial.html">QCPFinancial</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">A plottable representing a financial stock chart. <a href="classQCPFinancial.html#details">More...</a><br/></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a>
Typedefs</h2></td></tr>
<tr class="memitem:a745c09823fae0974b50beca9bc3b3d7d"><td class="memItemLeft" align="right" valign="top">typedef QMap< double, <br class="typebreak"/>
<a class="el" href="classQCPFinancialData.html">QCPFinancialData</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="plottable-financial_8h.html#a745c09823fae0974b50beca9bc3b3d7d">QCPFinancialDataMap</a></td></tr>
<tr class="separator:a745c09823fae0974b50beca9bc3b3d7d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad72fc549e490f52e8cbb03d7891f30c1"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad72fc549e490f52e8cbb03d7891f30c1"></a>
typedef QMapIterator< double, <br class="typebreak"/>
<a class="el" href="classQCPFinancialData.html">QCPFinancialData</a> > </td><td class="memItemRight" valign="bottom"><b>QCPFinancialDataMapIterator</b></td></tr>
<tr class="separator:ad72fc549e490f52e8cbb03d7891f30c1"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abfbd4d77d8bc14aa8ada56abcafe6711"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abfbd4d77d8bc14aa8ada56abcafe6711"></a>
typedef QMutableMapIterator<br class="typebreak"/>
< double, <a class="el" href="classQCPFinancialData.html">QCPFinancialData</a> > </td><td class="memItemRight" valign="bottom"><b>QCPFinancialDataMutableMapIterator</b></td></tr>
<tr class="separator:abfbd4d77d8bc14aa8ada56abcafe6711"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a36893db8c9fcdf5f9fcd8545f686d3ad"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a36893db8c9fcdf5f9fcd8545f686d3ad"></a>
 </td><td class="memItemRight" valign="bottom"><b>Q_DECLARE_TYPEINFO</b> (<a class="el" href="classQCPFinancialData.html">QCPFinancialData</a>, Q_MOVABLE_TYPE)</td></tr>
<tr class="separator:a36893db8c9fcdf5f9fcd8545f686d3ad"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Typedef Documentation</h2>
<a class="anchor" id="a745c09823fae0974b50beca9bc3b3d7d"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="plottable-financial_8h.html#a745c09823fae0974b50beca9bc3b3d7d">QCPFinancialDataMap</a></td>
</tr>
</table>
</div><div class="memdoc">
<p>Container for storing <a class="el" href="classQCPFinancialData.html">QCPFinancialData</a> items in a sorted fashion. The key of the map is the key member of the <a class="el" href="classQCPFinancialData.html" title="Holds the data of one single data point for QCPFinancial. ">QCPFinancialData</a> instance.</p>
<p>This is the container in which <a class="el" href="classQCPFinancial.html" title="A plottable representing a financial stock chart. ">QCPFinancial</a> holds its data. </p>
<dl class="section see"><dt>See Also</dt><dd><a class="el" href="classQCPFinancial.html" title="A plottable representing a financial stock chart. ">QCPFinancial</a>, <a class="el" href="classQCPFinancial.html#adf12a86082f1e488df6a4e8603f8fd6d">QCPFinancial::setData</a> </dd></dl>
</div>
</div>
</div><!-- contents -->
<div class="footer" />Generated with <a href="http://www.doxygen.org/index.html">Doxygen</a> 1.8.6</div>
</body>
</html>
| {
"content_hash": "c36bdf4e809e0ad27c47bdc8988e0b68",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 314,
"avg_line_length": 76.8,
"alnum_prop": 0.7173713235294118,
"repo_name": "jormunmor/doctorado",
"id": "a12a5037a53dabb6ed04ffc086f3c7f401aa90f8",
"size": "6528",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "cpp-projects/qcustomplot/documentation/html/plottable-financial_8h.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2671"
},
{
"name": "C",
"bytes": "14433"
},
{
"name": "C#",
"bytes": "18659"
},
{
"name": "C++",
"bytes": "2923396"
},
{
"name": "CMake",
"bytes": "38809"
},
{
"name": "CSS",
"bytes": "949322"
},
{
"name": "GAP",
"bytes": "24568"
},
{
"name": "HTML",
"bytes": "62229389"
},
{
"name": "Java",
"bytes": "2437530"
},
{
"name": "JavaScript",
"bytes": "8047306"
},
{
"name": "Makefile",
"bytes": "293709"
},
{
"name": "Objective-C++",
"bytes": "7535732"
},
{
"name": "PostScript",
"bytes": "13039"
},
{
"name": "Python",
"bytes": "4330"
},
{
"name": "QMake",
"bytes": "5527"
},
{
"name": "Shell",
"bytes": "2037"
},
{
"name": "TeX",
"bytes": "2066789"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="index_price/css/netstyle.css">
<link rel="stylesheet" href="index_price/css/animate.css">
<link rel="stylesheet" href="index_price/css/bootstrap.min.css">
<title>NetGet</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55875281-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body >
<?php
if(isset($_GET["alert"]))
{
$msg = $_GET['alert'];
echo "alert(\"$msg\");";
}
?>
<div class="container">
<div class="row">
<div class="col-lg-12 loginset">
<div class="menu">
<a href="web/tour/index.html"><p>Tour</p></a>
<span>|</span>
<a href="pricing.html"><p>Sign Up</p></a>
<span>|</span>
<a href="web/terms/contact.html" target="blank"><p>Contact</p></a>
</div>
<div class="col-lg-12 col-md-12"><h1 style="text-align: center;"><font color="white">NetGet One</h1></div>
<form class="formlog" method="post" action="cod/php/inlog.php">
<p class="input-field"><input type="text" name="usrUserName" id="usrUserName" placeholder="Username" /></p>
<p class="input-field" ><input type="password" id="usrPass" name="usrPass" placeholder="Password" /></p>
<input type="submit" class="buttonsblog center-block " name="submit" value="Log In" />
</form>
<div class="terms center-block"><a href="web/terms/terms.html" target="blank">Terms and conditions</a>|<a onclick="forgotAccount()"> Forgot Account Information?</a></br>
</div>
</div>
</div>
</div>
<script>
function forgotAccount() {
window.open("forgot.html", "_blank", "toolbar=no, scrollbars=yes, resizable=yes, top=200, left=500, width=400, height=300");
}
</script>
</body>
<script src="index_price/js/jquery-2.0.0.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.2/TweenMax.min.js"></script>
<script src="index_price/js/bootstrap.min.js" type="text/javascript"></script>
<script src="index_price/js/main.js"></script>
<script src="index_price/js/jquery.easing.1.3.js"></script>
</html> | {
"content_hash": "38508530a63ad1a2c37ee35777ec7204",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 185,
"avg_line_length": 33.577777777777776,
"alnum_prop": 0.5562541363335539,
"repo_name": "suiGn/orgboat",
"id": "243ce3ff60d0f10c9f4755f7b240aea1fe7a3f15",
"size": "3022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "netget.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "471655"
},
{
"name": "JavaScript",
"bytes": "291989"
},
{
"name": "PHP",
"bytes": "919636"
},
{
"name": "Shell",
"bytes": "214"
}
],
"symlink_target": ""
} |
#include "tensorflow/compiler/xla/client/computation_builder.h"
#include <stddef.h>
#include <array>
#include <numeric>
#include <set>
#include <vector>
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
namespace xla {
ComputationDataHandle ComputationBuilder::ParseOpResponse(
const Status& status, OpResponse* response) {
VLOG(2) << "done with op request";
if (!status.ok()) {
NoteError(status);
return ComputationDataHandle();
}
if (response->output().handle() == 0) {
NoteError(InternalError("No output handle"));
return ComputationDataHandle();
}
return response->output();
}
ComputationBuilder::ComputationBuilder(Client* client,
const string& computation_name)
: name_(computation_name), first_error_(Status::OK()), client_(client) {}
ComputationBuilder::~ComputationBuilder() {}
void ComputationBuilder::NoteError(const Status& error) {
if (die_immediately_on_error_) {
LOG(FATAL) << "error building computation: " << error;
}
if (first_error_.ok()) {
first_error_ = error;
first_error_backtrace_.CreateCurrent(/*skip_count=*/1);
}
}
std::unique_ptr<ComputationBuilder> ComputationBuilder::CreateSubBuilder(
const string& computation_name) {
auto sub_builder = MakeUnique<ComputationBuilder>(client_, computation_name);
sub_builder->parent_builder_ = this;
sub_builder->die_immediately_on_error_ = die_immediately_on_error_;
return sub_builder;
}
Status ComputationBuilder::PrepareComputation() {
if (!first_error_.ok()) {
return first_error_;
}
if (!computation_.IsNull()) {
return Status::OK();
}
ComputationRequest request;
request.set_name(name_);
ComputationResponse response;
VLOG(2) << "making computation request";
Status s = client_->stub()->Computation(&request, &response);
VLOG(2) << "done with computation request";
if (!s.ok()) {
NoteError(s);
return first_error_;
}
computation_ = Computation(client_->stub(), response.computation());
return Status::OK();
}
bool ComputationBuilder::MakeWindow(
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation, Window* window) {
const auto verify_size = [&](const size_t x, const char* x_name) {
if (x == 0 || x == window_dimensions.size()) {
return true;
} else {
NoteError(InvalidArgument(
"%s",
tensorflow::strings::StrCat(
"Window has different number of window dimensions than of ",
x_name, "\nNumber of window dimensions: ",
window_dimensions.size(), "\nNumber of ", x_name, ": ", x,
"\n")
.c_str())); //
return false;
}
};
if (!verify_size(window_strides.size(), "window strides") ||
!verify_size(padding.size(), "padding entries") ||
!verify_size(lhs_dilation.size(), "lhs dilation factors") ||
!verify_size(rhs_dilation.size(), "rhs dilation factors")) {
return false;
}
window->Clear();
for (size_t i = 0; i < window_dimensions.size(); i++) {
auto dim = window->add_dimensions();
dim->set_size(window_dimensions[i]);
if (!window_strides.empty()) {
dim->set_stride(window_strides[i]);
} else {
dim->set_stride(1);
}
if (!padding.empty()) {
dim->set_padding_low(padding[i].first);
dim->set_padding_high(padding[i].second);
} else {
dim->set_padding_low(0);
dim->set_padding_high(0);
}
if (!lhs_dilation.empty()) {
dim->set_base_dilation(lhs_dilation[i]);
} else {
dim->set_base_dilation(1);
}
if (!rhs_dilation.empty()) {
dim->set_window_dilation(rhs_dilation[i]);
} else {
dim->set_window_dilation(1);
}
}
return true;
}
ComputationDataHandle ComputationBuilder::ConstantOp(
const PopulateLiteral& populate) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ConstantRequest request;
Literal literal;
populate(&literal);
*request.mutable_literal() = literal.ToProto();
VLOG(3) << "created constant: " << request.literal().ShortDebugString();
OpRequest op_request;
*op_request.mutable_constant_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making constant request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::ConstantLiteral(
const Literal& literal) {
return ConstantOp(
[literal](Literal* mutable_literal) { *mutable_literal = literal; });
}
ComputationDataHandle ComputationBuilder::Parameter(int64 parameter_number,
const Shape& shape,
const string& name) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ParameterRequest request;
*request.mutable_shape() = shape;
request.set_parameter(parameter_number);
request.set_name(name);
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_parameter_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making parameter request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
StatusOr<std::unique_ptr<Shape>> ComputationBuilder::GetShape(
const ComputationDataHandle& operand) {
if (!first_error_.ok()) {
return first_error_;
}
GetLocalShapeRequest request;
*request.mutable_computation() = computation_.handle();
*request.mutable_operand() = operand;
GetLocalShapeResponse response;
VLOG(2) << "making get-shape request";
Status s = client_->stub()->GetLocalShape(&request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
NoteError(s);
return first_error_;
}
TF_RET_CHECK(response.has_shape());
std::unique_ptr<Shape> shape = WrapUnique(response.release_shape());
TF_RET_CHECK(shape != nullptr);
return std::move(shape);
}
ComputationDataHandle ComputationBuilder::CheckShape(
const ComputationDataHandle& operand, const Shape& expected_shape) {
std::unique_ptr<Shape> actual_shape = GetShape(operand).ConsumeValueOrDie();
CHECK(ShapeUtil::Equal(expected_shape, *actual_shape))
<< "want " << ShapeUtil::HumanString(expected_shape) << " got "
<< ShapeUtil::HumanString(*actual_shape);
return operand;
}
void ComputationBuilder::CheckSameShape(const ComputationDataHandle& lhs,
const ComputationDataHandle& rhs) {
std::unique_ptr<Shape> lhs_shape = GetShape(lhs).ConsumeValueOrDie();
std::unique_ptr<Shape> rhs_shape = GetShape(rhs).ConsumeValueOrDie();
VLOG(2) << "checking " << ShapeUtil::HumanString(*lhs_shape) << " equals "
<< ShapeUtil::HumanString(*rhs_shape);
CHECK(ShapeUtil::Equal(*lhs_shape, *rhs_shape))
<< "lhs " << ShapeUtil::HumanString(*lhs_shape) << " rhs "
<< ShapeUtil::HumanString(*rhs_shape);
}
ComputationDataHandle ComputationBuilder::Slice(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> start_indices,
tensorflow::gtl::ArraySlice<int64> limit_indices,
tensorflow::gtl::ArraySlice<int64> strides) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
SliceRequest request;
*request.mutable_operand() = operand;
for (int64 index : start_indices) {
request.add_start_indices(index);
}
for (int64 index : limit_indices) {
request.add_limit_indices(index);
}
for (int64 index : strides) {
request.add_strides(index);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_slice_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making slice request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::SliceInDim(
const ComputationDataHandle& operand, int64 start_index, int64 limit_index,
int64 stride, int64 dimno) {
StatusOr<std::unique_ptr<Shape>> shape_status = GetShape(operand);
if (!shape_status.ok()) {
NoteError(shape_status.status());
return ComputationDataHandle{};
}
const Shape& shape = *shape_status.ValueOrDie();
std::vector<int64> starts(ShapeUtil::Rank(shape), 0);
std::vector<int64> limits(shape.dimensions().begin(),
shape.dimensions().end());
std::vector<int64> strides(ShapeUtil::Rank(shape), 1);
starts[dimno] = start_index;
limits[dimno] = limit_index;
strides[dimno] = stride;
return Slice(operand, starts, limits, strides);
}
ComputationDataHandle ComputationBuilder::DynamicSlice(
const ComputationDataHandle& operand,
const ComputationDataHandle& start_indices,
tensorflow::gtl::ArraySlice<int64> slice_sizes) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
DynamicSliceRequest request;
*request.mutable_operand() = operand;
*request.mutable_start_indices() = start_indices;
for (int64 index : slice_sizes) {
request.add_slice_sizes(index);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_dynamic_slice_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making dynamic slice request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::DynamicUpdateSlice(
const ComputationDataHandle& operand, const ComputationDataHandle& update,
const ComputationDataHandle& start_indices) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
DynamicUpdateSliceRequest request;
*request.mutable_operand() = operand;
*request.mutable_update() = update;
*request.mutable_start_indices() = start_indices;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_dynamic_update_slice_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making dynamic update slice request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::ConcatInDim(
tensorflow::gtl::ArraySlice<ComputationDataHandle> operands,
int64 dimension) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ConcatenateRequest request;
for (const ComputationDataHandle& operand : operands) {
*request.add_operands() = operand;
}
request.set_dimension(dimension);
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_concatenate_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making concatenate request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Broadcast(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> broadcast_sizes) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
BroadcastRequest request;
*request.mutable_operand() = operand;
for (int64 size : broadcast_sizes) {
request.add_broadcast_sizes(size);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_broadcast_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making broadcast request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Pad(
const ComputationDataHandle& operand,
const ComputationDataHandle& padding_value,
const PaddingConfig& padding_config) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
PadRequest request;
*request.mutable_operand() = operand;
*request.mutable_padding_value() = padding_value;
*request.mutable_padding_config() = padding_config;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_pad_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making pad request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Reshape(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> dimensions,
tensorflow::gtl::ArraySlice<int64> new_sizes) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ReshapeRequest request;
*request.mutable_operand() = operand;
for (int64 dimension : dimensions) {
request.add_dimensions(dimension);
}
for (int64 new_size : new_sizes) {
request.add_new_sizes(new_size);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_reshape_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making reshape request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Reshape(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> new_sizes) {
if (!first_error_.ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> shape = GetShape(operand);
if (!shape.ok()) {
// Just early return with the existing error status.
first_error_ = shape.status();
return ComputationDataHandle();
}
std::vector<int64> dimensions(shape.ValueOrDie()->dimensions().size());
std::iota(dimensions.begin(), dimensions.end(), 0);
return Reshape(operand, dimensions, new_sizes);
}
ComputationDataHandle ComputationBuilder::Collapse(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> dims_to_collapse) {
if (!first_error_.ok()) {
return ComputationDataHandle();
}
// Don't support out-of-order collapse here.
// Checks that the collapsed dimensions are in order and consecutive.
for (tensorflow::gtl::ArraySlice<int64>::size_type i = 1;
i < dims_to_collapse.size(); ++i) {
if (dims_to_collapse[i] - 1 != dims_to_collapse[i - 1]) {
NoteError(InvalidArgument(
"Collapsed dimensions are not in order and consecutive."));
return ComputationDataHandle();
}
}
// Create a new sizes vector from the old shape, replacing the collapsed
// dimensions by the product of their sizes.
StatusOr<std::unique_ptr<Shape>> shape_or_status = GetShape(operand);
if (!shape_or_status.ok()) {
// Just early return with the existing error status.
first_error_ = shape_or_status.status();
return ComputationDataHandle();
}
std::unique_ptr<Shape> original_shape = shape_or_status.ConsumeValueOrDie();
std::vector<int64> new_sizes;
for (int i = 0; i < ShapeUtil::Rank(*original_shape); ++i) {
if (i <= dims_to_collapse.front() || i > dims_to_collapse.back()) {
new_sizes.push_back(original_shape->dimensions(i));
} else {
new_sizes.back() *= original_shape->dimensions(i);
}
}
return Reshape(operand, new_sizes);
}
void ComputationBuilder::Trace(const string& tag,
const ComputationDataHandle& operand) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return;
}
TraceRequest request;
request.set_tag(tag);
*request.mutable_operand() = operand;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_trace_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making trace request";
Status s = client_->stub()->Op(&op_request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
NoteError(s);
}
}
ComputationDataHandle ComputationBuilder::Select(
const ComputationDataHandle& pred, const ComputationDataHandle& on_true,
const ComputationDataHandle& on_false) {
return TernaryOp(TRIOP_SELECT, pred, on_true, on_false);
}
ComputationDataHandle ComputationBuilder::Tuple(
tensorflow::gtl::ArraySlice<ComputationDataHandle> elements) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
VariadicOpRequest request;
request.set_varop(VAROP_TUPLE);
for (const ComputationDataHandle& operand : elements) {
*request.add_operands() = operand;
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_variadic_op_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making variadic op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::GetTupleElement(
const ComputationDataHandle& tuple_data, int64 index) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
GetTupleElementRequest request;
*request.mutable_operand() = tuple_data;
request.set_index(index);
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_get_tuple_element_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making get tuple element op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Eq(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_EQ, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Ne(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_NE, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Ge(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_GE, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Gt(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_GT, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Le(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_LE, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Lt(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_LT, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Dot(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs) {
return BinaryOp(BINOP_DOT, lhs, rhs, /*broadcast_dimensions=*/{});
}
ComputationDataHandle ComputationBuilder::Conv(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
return ConvWithGeneralDimensions(
lhs, rhs, window_strides, padding,
CreateDefaultConvDimensionNumbers(window_strides.size()));
}
ComputationDataHandle ComputationBuilder::ConvWithGeneralPadding(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
return ConvGeneral(lhs, rhs, window_strides, padding,
CreateDefaultConvDimensionNumbers(window_strides.size()));
}
bool ComputationBuilder::VerifyConvolution(
const Shape& lhs_shape, const Shape& rhs_shape,
const ConvolutionDimensionNumbers& dimension_numbers) {
if (ShapeUtil::Rank(lhs_shape) != ShapeUtil::Rank(rhs_shape)) {
NoteError(
InvalidArgument("Convolution arguments must have same number of "
"dimensions. Got: %s and %s",
ShapeUtil::HumanString(lhs_shape).c_str(),
ShapeUtil::HumanString(rhs_shape).c_str()));
return false;
}
int num_dims = ShapeUtil::Rank(lhs_shape);
if (num_dims < 3) {
NoteError(InvalidArgument(
"Convolution expects argument arrays with >= 3 dimensions. "
"Got: %s and %s",
ShapeUtil::HumanString(lhs_shape).c_str(),
ShapeUtil::HumanString(rhs_shape).c_str()));
return false;
}
int num_spatial_dims = num_dims - 2;
const auto check_spatial_dimensions = [&](
const char* const field_name,
const tensorflow::protobuf::RepeatedField<tensorflow::protobuf_int64>&
numbers) {
if (numbers.size() != num_spatial_dims) {
NoteError(InvalidArgument("Expected %d elements for %s, but got %d.",
num_spatial_dims, field_name, numbers.size()));
return false;
}
for (int i = 0; i < numbers.size(); ++i) {
if (numbers.Get(i) < 0 || numbers.Get(i) >= num_dims) {
NoteError(InvalidArgument("Convolution %s[%d] is out of bounds: %lld",
field_name, i, numbers.Get(i)));
return false;
}
}
return true;
};
return check_spatial_dimensions("spatial_dimensions",
dimension_numbers.spatial_dimensions()) &&
check_spatial_dimensions(
"kernel_spatial_dimensions",
dimension_numbers.kernel_spatial_dimensions());
}
ComputationDataHandle ComputationBuilder::ConvWithGeneralDimensions(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
const ConvolutionDimensionNumbers& dimension_numbers) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> lhs_shape_or_status = GetShape(lhs);
if (!lhs_shape_or_status.ok()) {
first_error_ = lhs_shape_or_status.status();
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> rhs_shape_or_status = GetShape(rhs);
if (!rhs_shape_or_status.ok()) {
first_error_ = rhs_shape_or_status.status();
return ComputationDataHandle();
}
std::unique_ptr<Shape> lhs_shape = lhs_shape_or_status.ConsumeValueOrDie();
std::unique_ptr<Shape> rhs_shape = rhs_shape_or_status.ConsumeValueOrDie();
if (!VerifyConvolution(*lhs_shape, *rhs_shape, dimension_numbers)) {
NoteError(InternalError("failed to verify convolution"));
return ComputationDataHandle();
}
std::vector<int64> base_area_dimensions(
dimension_numbers.spatial_dimensions_size());
for (std::vector<int64>::size_type i = 0; i < base_area_dimensions.size();
++i) {
base_area_dimensions[i] =
lhs_shape->dimensions(dimension_numbers.spatial_dimensions(i));
}
std::vector<int64> window_dimensions(
dimension_numbers.kernel_spatial_dimensions_size());
for (std::vector<int64>::size_type i = 0; i < window_dimensions.size(); ++i) {
window_dimensions[i] =
rhs_shape->dimensions(dimension_numbers.kernel_spatial_dimensions(i));
}
return ConvGeneral(lhs, rhs, window_strides,
MakePadding(base_area_dimensions, window_dimensions,
window_strides, padding),
dimension_numbers);
}
ComputationDataHandle ComputationBuilder::ConvGeneral(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
const ConvolutionDimensionNumbers& dimension_numbers) {
return ConvGeneralDilated(lhs, rhs, window_strides, padding, {}, {},
dimension_numbers);
}
ComputationDataHandle ComputationBuilder::ConvGeneralDilated(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
tensorflow::gtl::ArraySlice<int64> lhs_dilation,
tensorflow::gtl::ArraySlice<int64> rhs_dilation,
const ConvolutionDimensionNumbers& dimension_numbers) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> lhs_shape_or_status = GetShape(lhs);
if (!lhs_shape_or_status.ok()) {
first_error_ = lhs_shape_or_status.status();
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> rhs_shape_or_status = GetShape(rhs);
if (!rhs_shape_or_status.ok()) {
first_error_ = rhs_shape_or_status.status();
return ComputationDataHandle();
}
std::unique_ptr<Shape> lhs_shape = lhs_shape_or_status.ConsumeValueOrDie();
std::unique_ptr<Shape> rhs_shape = rhs_shape_or_status.ConsumeValueOrDie();
if (!VerifyConvolution(*lhs_shape, *rhs_shape, dimension_numbers)) {
// Error is recorded in VerifyConvolution.
return ComputationDataHandle();
}
std::vector<int64> window_dimensions(
dimension_numbers.kernel_spatial_dimensions_size());
for (std::vector<int64>::size_type i = 0; i < window_dimensions.size(); ++i) {
window_dimensions[i] =
rhs_shape->dimensions(dimension_numbers.kernel_spatial_dimensions(i));
}
ConvolveRequest request;
*request.mutable_lhs() = lhs;
*request.mutable_rhs() = rhs;
*request.mutable_dimension_numbers() = dimension_numbers;
if (!MakeWindow(window_dimensions, window_strides, padding, lhs_dilation,
rhs_dilation, request.mutable_window())) {
// Error is recorded in MakeWindow.
return ComputationDataHandle();
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_convolve_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making convolve request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Infeed(const Shape& shape,
const string& config) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
InfeedRequest request;
*request.mutable_shape() = shape;
*request.mutable_config() = config;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_infeed_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making infeed op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
void ComputationBuilder::Outfeed(const ComputationDataHandle& operand,
const Shape& shape,
const string& outfeed_config) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return;
}
OutfeedRequest request;
request.set_outfeed_config(outfeed_config);
*request.mutable_operand() = operand;
*request.mutable_shape() = shape;
OpRequest op_request;
*op_request.mutable_outfeed_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making outfeed op request";
tensorflow::Status s = client_->stub()->Op(&op_request, &response);
if (!s.ok()) {
NoteError(s);
return;
}
}
ComputationDataHandle ComputationBuilder::Call(
const Computation& computation,
tensorflow::gtl::ArraySlice<ComputationDataHandle> operands) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
CallRequest request;
*request.mutable_to_apply() = computation.handle();
for (const ComputationDataHandle& operand : operands) {
*request.add_operands() = operand;
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_call_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making call op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::CustomCall(
const string& call_target_name,
tensorflow::gtl::ArraySlice<ComputationDataHandle> operands,
const Shape& shape) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
CustomCallRequest request;
request.set_call_target_name(call_target_name);
for (const ComputationDataHandle& operand : operands) {
*request.add_operands() = operand;
}
*request.mutable_shape() = shape;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_custom_call_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making custom call op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Add(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_ADD, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Sub(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_SUB, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Mul(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_MUL, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Div(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_DIV, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Rem(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_REM, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Max(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_MAX, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::Min(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_MIN, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::LogicalAnd(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_LOGICAL_AND, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::LogicalOr(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_LOGICAL_OR, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::LogicalNot(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_LOGICAL_NOT, operand);
}
ComputationDataHandle ComputationBuilder::Abs(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_ABS, operand);
}
ComputationDataHandle ComputationBuilder::Exp(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_EXP, operand);
}
ComputationDataHandle ComputationBuilder::Floor(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_FLOOR, operand);
}
ComputationDataHandle ComputationBuilder::Ceil(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_CEIL, operand);
}
ComputationDataHandle ComputationBuilder::Log(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_LOG, operand);
}
ComputationDataHandle ComputationBuilder::Sign(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_SIGN, operand);
}
ComputationDataHandle ComputationBuilder::Cos(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_COS, operand);
}
ComputationDataHandle ComputationBuilder::Sin(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_SIN, operand);
}
ComputationDataHandle ComputationBuilder::Tanh(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_TANH, operand);
}
ComputationDataHandle ComputationBuilder::IsFinite(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_IS_FINITE, operand);
}
ComputationDataHandle ComputationBuilder::Transpose(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> permutation) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
TransposeRequest* request = op_request.mutable_transpose_request();
*request->mutable_operand() = operand;
for (int64 dimension : permutation) {
request->add_dimensions(dimension);
}
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making transpose request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Rev(
const ComputationDataHandle& operand,
tensorflow::gtl::ArraySlice<int64> dimensions) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ReverseRequest request;
*request.mutable_operand() = operand;
for (int64 dimension : dimensions) {
request.add_dimensions(dimension);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_reverse_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making reverse op request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Sort(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_SORT, operand);
}
ComputationDataHandle ComputationBuilder::SqrtF32(
const ComputationDataHandle& operand) {
return BinaryOp(BINOP_POW, operand, ConstantR0<float>(0.5),
/*broadcast_dimensions=*/{});
}
ComputationDataHandle ComputationBuilder::Pow(
const ComputationDataHandle& lhs, const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
return BinaryOp(BINOP_POW, lhs, rhs, broadcast_dimensions);
}
ComputationDataHandle ComputationBuilder::ConvertElementType(
const ComputationDataHandle& operand, PrimitiveType new_element_type) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> shape_status = GetShape(operand);
if (!shape_status.ok()) {
// Just early return with the existing error status.
first_error_ = shape_status.status();
return ComputationDataHandle();
}
std::unique_ptr<Shape> original = shape_status.ConsumeValueOrDie();
ConvertRequest request;
*request.mutable_operand() = operand;
request.set_new_element_type(new_element_type);
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_convert_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making convert request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::SquareF32(
const ComputationDataHandle& operand) {
return BinaryOp(BINOP_POW, operand, ConstantR0<float>(2.0),
/*broadcast_dimensions=*/{});
}
ComputationDataHandle ComputationBuilder::ReciprocalF32(
const ComputationDataHandle& operand) {
return BinaryOp(BINOP_POW, operand, ConstantR0<float>(-1.0),
/*broadcast_dimensions=*/{});
}
ComputationDataHandle ComputationBuilder::Neg(
const ComputationDataHandle& operand) {
return UnaryOp(UNOP_NEGATE, operand);
}
ComputationDataHandle ComputationBuilder::Clamp(
const ComputationDataHandle& min, const ComputationDataHandle& operand,
const ComputationDataHandle& max) {
return TernaryOp(TRIOP_CLAMP, min, operand, max);
}
ComputationDataHandle ComputationBuilder::UnaryOp(
UnaryOperation unop, const ComputationDataHandle& operand) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
UnaryOpRequest request;
request.set_unop(unop);
*request.mutable_operand() = operand;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_unary_op_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making unop request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::BinaryOp(
BinaryOperation binop, const ComputationDataHandle& lhs,
const ComputationDataHandle& rhs,
tensorflow::gtl::ArraySlice<int64> broadcast_dimensions) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
BinaryOpRequest request;
request.set_binop(binop);
*request.mutable_lhs() = lhs;
*request.mutable_rhs() = rhs;
for (int64 dimension : broadcast_dimensions) {
request.add_broadcast_dimensions(dimension);
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_binary_op_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making binop request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::RngOp(
RandomDistribution distribution,
tensorflow::gtl::ArraySlice<ComputationDataHandle> parameters,
const Shape& shape) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
RngRequest request;
request.set_distribution(distribution);
for (const ComputationDataHandle& param : parameters) {
*request.add_parameter() = param;
}
*request.mutable_shape() = shape;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_rng_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making rngop request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::TernaryOp(
TernaryOperation triop, const ComputationDataHandle& lhs,
const ComputationDataHandle& rhs, const ComputationDataHandle& ehs) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
TernaryOpRequest request;
request.set_triop(triop);
*request.mutable_lhs() = lhs;
*request.mutable_rhs() = rhs;
*request.mutable_ehs() = ehs;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_ternary_op_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making triop request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
Status ComputationBuilder::SetReturnValue(
const ComputationDataHandle& operand) {
if (!first_error_.ok()) {
return first_error_;
}
SetReturnValueRequest request;
*request.mutable_computation() = computation_.handle();
*request.mutable_operand() = operand;
SetReturnValueResponse response;
VLOG(2) << "making set-handle-to-execute request";
Status s = client_->stub()->SetReturnValue(&request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
NoteError(s);
return first_error_;
}
return Status::OK();
}
StatusOr<bool> ComputationBuilder::IsConstant(
const ComputationDataHandle& operand) {
if (!first_error_.ok()) {
return first_error_;
}
IsConstantRequest request;
*request.mutable_computation() = computation_.handle();
*request.mutable_operand() = operand;
IsConstantResponse response;
VLOG(2) << "making IsConstant request";
Status s = client_->stub()->IsConstant(&request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
return s;
}
return response.is_constant();
}
StatusOr<std::unique_ptr<GlobalData>> ComputationBuilder::ComputeConstant(
const ComputationDataHandle& operand, const Layout* output_layout) {
if (!first_error_.ok()) {
return first_error_;
}
ComputeConstantRequest request;
*request.mutable_computation() = computation_.handle();
*request.mutable_operand() = operand;
if (output_layout != nullptr) {
*request.mutable_output_layout() = *output_layout;
}
ComputeConstantResponse response;
VLOG(2) << "making compute-constant request";
Status s = client_->stub()->ComputeConstant(&request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
return s;
}
TF_RET_CHECK(response.output().handle() != 0);
return MakeUnique<GlobalData>(client_->stub(), response.output());
}
ComputationDataHandle ComputationBuilder::Map(
tensorflow::gtl::ArraySlice<ComputationDataHandle> operands,
const Computation& computation,
tensorflow::gtl::ArraySlice<ComputationDataHandle> static_operands) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
MapRequest request;
for (const ComputationDataHandle& operand : operands) {
*request.add_operands() = operand;
}
*request.mutable_to_apply() = computation.handle();
for (const ComputationDataHandle& sop : static_operands) {
*request.add_static_operands() = sop;
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_map_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making Map request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::RngNormal(
const ComputationDataHandle& mu, const ComputationDataHandle& sigma,
const Shape& shape) {
return RngOp(RandomDistribution::RNG_NORMAL, {mu, sigma}, shape);
}
ComputationDataHandle ComputationBuilder::RngUniform(
const ComputationDataHandle& a, const ComputationDataHandle& b,
const Shape& shape) {
return RngOp(RandomDistribution::RNG_UNIFORM, {a, b}, shape);
}
ComputationDataHandle ComputationBuilder::RngBernoulli(
const ComputationDataHandle& mean, const Shape& shape) {
return RngOp(RandomDistribution::RNG_BERNOULLI, {mean}, shape);
}
ComputationDataHandle ComputationBuilder::While(
const Computation& condition, const Computation& body,
const ComputationDataHandle& init) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
WhileRequest request;
*request.mutable_condition() = condition.handle();
*request.mutable_body() = body.handle();
*request.mutable_init() = init;
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_while_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making while request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::Reduce(
const ComputationDataHandle& operand,
const ComputationDataHandle& init_value, const Computation& computation,
tensorflow::gtl::ArraySlice<int64> dimensions_to_reduce) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ReduceRequest request;
*request.mutable_operand() = operand;
*request.mutable_init_value() = init_value;
for (int64 dimension : dimensions_to_reduce) {
request.add_dimensions(dimension);
}
*request.mutable_to_apply() = computation.handle();
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_reduce_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making reduce request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::ReduceWindow(
const ComputationDataHandle& operand,
const ComputationDataHandle& init_value, const Computation& computation,
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding) {
if (!first_error_.ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> shape = GetShape(operand);
if (!shape.ok()) {
// Just early return with the existing error status.
first_error_ = shape.status();
return ComputationDataHandle();
}
return ReduceWindowWithGeneralPadding(
operand, init_value, computation, window_dimensions, window_strides,
MakePadding(AsInt64Slice(shape.ValueOrDie()->dimensions()),
window_dimensions, window_strides, padding));
}
ComputationDataHandle ComputationBuilder::ReduceWindowWithGeneralPadding(
const ComputationDataHandle& operand,
const ComputationDataHandle& init_value, const Computation& computation,
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ReduceWindowRequest request;
*request.mutable_operand() = operand;
*request.mutable_to_apply() = computation.handle();
*request.mutable_init_value() = init_value;
if (!MakeWindow(window_dimensions, window_strides, padding, {}, {},
request.mutable_window())) {
NoteError(InternalError("failed to make window"));
return ComputationDataHandle();
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_reduce_window_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making reduce-window request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::BatchNormTraining(
const ComputationDataHandle& operand, const ComputationDataHandle& scale,
const ComputationDataHandle& offset, float epsilon, int64 feature_index) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
BatchNormTrainingRequest request;
*request.mutable_operand() = operand;
*request.mutable_scale() = scale;
*request.mutable_offset() = offset;
request.set_epsilon(epsilon);
request.set_feature_index(feature_index);
OpRequest op_request;
*op_request.mutable_batch_norm_training_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making BatchNormTraining request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::BatchNormInference(
const ComputationDataHandle& operand, const ComputationDataHandle& scale,
const ComputationDataHandle& offset, const ComputationDataHandle& mean,
const ComputationDataHandle& variance, float epsilon, int64 feature_index) {
// TODO(b/62843645): Implement BatchNormInference.
NoteError(Unimplemented("BatchNormInference is not implemented yet."));
return ComputationDataHandle();
}
ComputationDataHandle ComputationBuilder::BatchNormGrad(
const ComputationDataHandle& operand, const ComputationDataHandle& scale,
const ComputationDataHandle& mean, const ComputationDataHandle& var,
const ComputationDataHandle& grad_output, float epsilon,
int64 feature_index) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
BatchNormGradRequest request;
*request.mutable_operand() = operand;
*request.mutable_scale() = scale;
*request.mutable_mean() = mean;
*request.mutable_variance() = var;
*request.mutable_grad_output() = grad_output;
request.set_epsilon(epsilon);
request.set_feature_index(feature_index);
OpRequest op_request;
*op_request.mutable_batch_norm_grad_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making BatchNormGrad request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::CrossReplicaSum(
const ComputationDataHandle& operand) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
CrossReplicaSumRequest request;
*request.mutable_operand() = operand;
OpRequest op_request;
*op_request.mutable_cross_replica_sum_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making cross-replica-sum request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::SelectAndScatter(
const ComputationDataHandle& operand, const Computation& select,
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides, Padding padding,
const ComputationDataHandle& source,
const ComputationDataHandle& init_value, const Computation& scatter) {
if (!first_error_.ok()) {
return ComputationDataHandle();
}
StatusOr<std::unique_ptr<Shape>> shape = GetShape(operand);
if (!shape.ok()) {
// Just early return with the existing error status.
first_error_ = shape.status();
return ComputationDataHandle();
}
return SelectAndScatterWithGeneralPadding(
operand, select, window_dimensions, window_strides,
MakePadding(AsInt64Slice(shape.ValueOrDie()->dimensions()),
window_dimensions, window_strides, padding),
source, init_value, scatter);
}
ComputationDataHandle ComputationBuilder::SelectAndScatterWithGeneralPadding(
const ComputationDataHandle& operand, const Computation& select,
tensorflow::gtl::ArraySlice<int64> window_dimensions,
tensorflow::gtl::ArraySlice<int64> window_strides,
tensorflow::gtl::ArraySlice<std::pair<int64, int64>> padding,
const ComputationDataHandle& source,
const ComputationDataHandle& init_value, const Computation& scatter) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
SelectAndScatterRequest request;
*request.mutable_operand() = operand;
*request.mutable_select() = select.handle();
*request.mutable_source() = source;
*request.mutable_init_value() = init_value;
*request.mutable_scatter() = scatter.handle();
if (!MakeWindow(window_dimensions, window_strides, padding, {}, {},
request.mutable_window())) {
NoteError(InternalError("failed to make window"));
return ComputationDataHandle();
}
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_select_and_scatter_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making select-and-scatter request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
ComputationDataHandle ComputationBuilder::ReducePrecision(
const ComputationDataHandle& operand, const int exponent_bits,
const int mantissa_bits) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
ReducePrecisionRequest request;
*request.mutable_operand() = operand;
request.set_exponent_bits(exponent_bits);
request.set_mantissa_bits(mantissa_bits);
OpRequest op_request;
*op_request.mutable_computation() = computation_.handle();
*op_request.mutable_reduce_precision_request() = request;
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making reduce-precision request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
void ComputationBuilder::Send(const ComputationDataHandle& operand,
const ChannelHandle& handle) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return;
}
SendRequest request;
*request.mutable_operand() = operand;
*request.mutable_channel_handle() = handle;
OpRequest op_request;
*op_request.mutable_send_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making send request";
Status s = client_->stub()->Op(&op_request, &response);
VLOG(2) << "done with op request";
if (!s.ok()) {
NoteError(s);
return;
}
}
ComputationDataHandle ComputationBuilder::Recv(const Shape& shape,
const ChannelHandle& handle) {
if (!first_error_.ok() || !PrepareComputation().ok()) {
return ComputationDataHandle();
}
RecvRequest request;
*request.mutable_shape() = shape;
*request.mutable_channel_handle() = handle;
OpRequest op_request;
*op_request.mutable_recv_request() = request;
*op_request.mutable_computation() = computation_.handle();
AddOpMetadata(&op_request);
OpResponse response;
VLOG(2) << "making recv request";
Status s = client_->stub()->Op(&op_request, &response);
return ParseOpResponse(s, &response);
}
Computation ComputationBuilder::BuildAndNoteError() {
DCHECK(parent_builder_ != nullptr);
auto build_status = Build();
if (!build_status.ok()) {
parent_builder_->NoteError(
AddStatus(build_status.status(),
tensorflow::strings::StrCat("error from: ", name_)));
return Computation();
}
return build_status.ConsumeValueOrDie();
}
StatusOr<Computation> ComputationBuilder::Build() {
if (!first_error_.ok()) {
string backtrace;
first_error_backtrace_.Dump(tensorflow::DebugWriteToString, &backtrace);
return AppendStatus(first_error_, backtrace);
}
if (computation_.IsNull()) {
return FailedPrecondition("no computation was built");
}
return {std::move(computation_)};
}
void ComputationBuilder::AddOpMetadata(OpRequest* request) const {
tensorflow::mutex_lock lock(mutex_);
*request->mutable_metadata() = metadata_;
}
/* static */ ConvolutionDimensionNumbers
ComputationBuilder::CreateDefaultConvDimensionNumbers(int num_spatial_dims) {
ConvolutionDimensionNumbers dimension_numbers;
dimension_numbers.set_batch_dimension(kConvBatchDimension);
dimension_numbers.set_feature_dimension(kConvFeatureDimension);
dimension_numbers.set_kernel_output_feature_dimension(
kConvKernelOutputDimension);
dimension_numbers.set_kernel_input_feature_dimension(
kConvKernelInputDimension);
for (int i = 0; i < num_spatial_dims; ++i) {
dimension_numbers.add_spatial_dimensions(i + 2);
dimension_numbers.add_kernel_spatial_dimensions(i + 2);
}
return dimension_numbers;
}
/* static */ StatusOr<ConvolutionDimensionNumbers>
ComputationBuilder::CreateConvDimensionNumbers(
int64 batch, int64 feature, int64 first_spatial, int64 second_spatial,
int64 kernel_output_feature, int64 kernel_input_feature,
int64 kernel_first_spatial, int64 kernel_second_spatial) {
if (std::set<int64>({batch, feature, first_spatial, second_spatial}).size() !=
4) {
return FailedPrecondition(
"dimension numbers for the input are not unique: (%lld, %lld, %lld, "
"%lld)",
batch, feature, first_spatial, second_spatial);
}
if (std::set<int64>({kernel_output_feature, kernel_input_feature,
kernel_first_spatial, kernel_second_spatial})
.size() != 4) {
return FailedPrecondition(
"dimension numbers for the weight are not unique: (%lld, %lld, %lld, "
"%lld)",
kernel_output_feature, kernel_input_feature, kernel_first_spatial,
kernel_second_spatial);
}
ConvolutionDimensionNumbers dimension_numbers;
dimension_numbers.set_batch_dimension(batch);
dimension_numbers.set_feature_dimension(feature);
dimension_numbers.add_spatial_dimensions(first_spatial);
dimension_numbers.add_spatial_dimensions(second_spatial);
dimension_numbers.set_kernel_output_feature_dimension(kernel_output_feature);
dimension_numbers.set_kernel_input_feature_dimension(kernel_input_feature);
dimension_numbers.add_kernel_spatial_dimensions(kernel_first_spatial);
dimension_numbers.add_kernel_spatial_dimensions(kernel_second_spatial);
return dimension_numbers;
}
} // namespace xla
| {
"content_hash": "323fce6150b15e9cb20615d2a07519f6",
"timestamp": "",
"source": "github",
"line_count": 1719,
"max_line_length": 80,
"avg_line_length": 34.29842931937173,
"alnum_prop": 0.7040655370681321,
"repo_name": "raymondxyang/tensorflow",
"id": "cbecab5037a5c0531930102328bfebc0184aef62",
"size": "59627",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/xla/client/computation_builder.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7666"
},
{
"name": "C",
"bytes": "193181"
},
{
"name": "C++",
"bytes": "28154892"
},
{
"name": "CMake",
"bytes": "624041"
},
{
"name": "Go",
"bytes": "940282"
},
{
"name": "Java",
"bytes": "380704"
},
{
"name": "Jupyter Notebook",
"bytes": "1833674"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "37232"
},
{
"name": "Objective-C",
"bytes": "7056"
},
{
"name": "Objective-C++",
"bytes": "63210"
},
{
"name": "Perl",
"bytes": "6715"
},
{
"name": "Protocol Buffer",
"bytes": "260324"
},
{
"name": "PureBasic",
"bytes": "24932"
},
{
"name": "Python",
"bytes": "24820337"
},
{
"name": "Ruby",
"bytes": "327"
},
{
"name": "Shell",
"bytes": "353443"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3ebd8967207373f13534f19ffeacffae",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "80b5a00db79c327084562c363948c717a7fbaf35",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Penstemon/Penstemon roseus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!--
~ Copyright 2014-present Open Networking Laboratory
~
~ 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.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.onosproject.cli.MarkCommand"/>
</command>
<command>
<action class="org.onosproject.cli.PrettyJson"/>
</command>
<command>
<action class="org.onosproject.cli.SummaryCommand"/>
</command>
<command>
<action class="org.onosproject.cli.security.ReviewCommand"/>
<completers>
<ref component-id="reviewAppNameCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.FlowObjectiveNextListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.FlowObjectivePendingNextCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.FlowObjectiveCompositionCommand"/>
</command>
<command>
<action class="org.onosproject.cli.app.ApplicationsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.app.ApplicationCommand"/>
<completers>
<ref component-id="appCommandCompleter"/>
<ref component-id="appNameCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.cfg.ComponentConfigCommand"/>
<completers>
<ref component-id="cfgCommandCompleter"/>
<ref component-id="componentNameCompleter"/>
<ref component-id="componentPropertyNameCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.cfg.NetworkConfigRegistryCommand"/>
</command>
<command>
<action class="org.onosproject.cli.cfg.NetworkConfigCommand"/>
<completers>
<ref component-id="subjectClassKeyCompleter"/>
<ref component-id="subjectKeyCompleter"/>
<ref component-id="configKeyCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.MetricsListCommand"/>
<completers>
<ref component-id="metricNameCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.NodesListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.UiViewListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.RolesCommand"/>
</command>
<command>
<action class="org.onosproject.cli.MastersListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.BalanceMastersCommand"/>
</command>
<command>
<action class="org.onosproject.cli.app.ApplicationIdListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.McastShowCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.McastJoinCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.McastDeleteCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.DriversListCommand"/>
<completers>
<ref component-id="driverNameCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DevicesListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.DevicePortsListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DevicePortStateCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<ref component-id="portStateCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceControllersCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceSetControllersCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceConfigGetterCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceConfigSetterCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DevicePortGetterCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceRemoveCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceInterfaceAddCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceInterfaceRemoveCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceInterfacesListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.MeterAddCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.MeterRemoveCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.MetersListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceRoleCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="nodeIdCompleter"/>
<ref component-id="roleCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AnnotateDeviceCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="annotationKeysCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AnnotatePortCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="annotationKeysCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AnnotateLinkCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="peerConnectPointCompleter"/>
<ref component-id="annotationKeysCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.LinksListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.EdgePortsListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.TopologyCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.PathListCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="deviceIdCompleter"/>
<null/> <!-- no more arguments -->
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.IntentsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.IntentListCompilers"/>
</command>
<command>
<action class="org.onosproject.cli.net.IntentListInstallers"/>
</command>
<command>
<action class="org.onosproject.cli.net.IntentRemoveCommand"/>
<completers>
<ref component-id="appIdWithIntentNameCompleter"/>
<ref component-id="intentKeyCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.IntentPurgeCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.AddHostToHostIntentCommand"/>
<completers>
<ref component-id="hostIdCompleter"/>
<ref component-id="hostIdCompleter"/>
</completers>
<optional-completers>
<entry key="-t" value-ref="ethTypeCompleter"/>
<entry key="--ipProto" value-ref="ipProtocolCompleter"/>
<entry key="--icmp6Type" value-ref="Icmp6TypeCompleter"/>
<entry key="--icmp6Code" value-ref="Icmp6CodeCompleter"/>
<entry key="--extHdr" value-ref="ExtHeaderCompleter"/>
<entry key="-a" value-ref="allAppNameCompleter"/>
<entry key="-e" value-ref="encapTypeCompleter"/>
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.AddPointToPointIntentCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="connectPointCompleter"/>
<null/> <!-- no more argument -->
</completers>
<optional-completers>
<entry key="-t" value-ref="ethTypeCompleter"/>
<entry key="--ipProto" value-ref="ipProtocolCompleter"/>
<entry key="--icmp6Type" value-ref="Icmp6TypeCompleter"/>
<entry key="--icmp6Code" value-ref="Icmp6CodeCompleter"/>
<entry key="--extHdr" value-ref="ExtHeaderCompleter"/>
<entry key="-a" value-ref="allAppNameCompleter"/>
<entry key="-e" value-ref="encapTypeCompleter"/>
<entry key="-r" value-ref="nullCompleter"/> <!-- option has no argument -->
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.GetStatisticsCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.GetFlowStatisticsCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AddMultiPointToSinglePointIntentCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
</completers>
<optional-completers>
<entry key="-t" value-ref="ethTypeCompleter"/>
<entry key="--ipProto" value-ref="ipProtocolCompleter"/>
<entry key="--icmp6Type" value-ref="Icmp6TypeCompleter"/>
<entry key="--icmp6Code" value-ref="Icmp6CodeCompleter"/>
<entry key="--extHdr" value-ref="ExtHeaderCompleter"/>
<entry key="-a" value-ref="allAppNameCompleter"/>
<entry key="-e" value-ref="encapTypeCompleter"/>
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.AddSinglePointToMultiPointIntentCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
</completers>
<optional-completers>
<entry key="-t" value-ref="ethTypeCompleter"/>
<entry key="--ipProto" value-ref="ipProtocolCompleter"/>
<entry key="--icmp6Type" value-ref="Icmp6TypeCompleter"/>
<entry key="--icmp6Code" value-ref="Icmp6CodeCompleter"/>
<entry key="--extHdr" value-ref="ExtHeaderCompleter"/>
<entry key="-a" value-ref="allAppNameCompleter"/>
<entry key="-e" value-ref="encapTypeCompleter"/>
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.IntentPushTestCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="connectPointCompleter"/>
<ref component-id="nullCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.IntentCycleCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="connectPointCompleter"/>
<ref component-id="nullCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RandomIntentCommand"/>
<completers>
<ref component-id="nullCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.ResourcesCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AllocationsCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.TestAllocateResource"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.TestProtectionEndpointIntentCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.AddProtectedTransportIntentCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.ClustersListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.PartitionsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.MapsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.CountersListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.QueuesListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TransactionsCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.CounterCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.ClusterDevicesCommand"/>
<completers>
<ref component-id="clusterIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.ClusterLinksCommand"/>
<completers>
<ref component-id="clusterIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.HostsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.HostRemoveCommand"/>
<completers>
<ref component-id="hostIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.InterfacesListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.InterfaceAddCommand"/>
<completers>
<ref component-id="connectPointCompleter" />
<ref component-id="placeholderCompleter" />
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.InterfaceRemoveCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="interfaceNameCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.GroupsListCommand"/>
<completers>
<ref component-id="groupStatusCompleter"/>
<ref component-id="deviceIdCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DevicePortStatsCommand"/>
<completers>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.PortQueryVlansCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.TableStatisticsCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.FlowsListCommand"/>
<completers>
<ref component-id="flowRuleStatusCompleter"/>
<ref component-id="deviceIdCompleter"/>
<ref component-id="placeholderCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.PacketRequestsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.PacketProcessorsListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.NeighbourHandlersListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.AddTestFlowsCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LeaderCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.WipeOutCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.RoutesListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.RouteAddCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.RouteRemoveCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.RouteStoreCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.GlobalLabelCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LabelResourceCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.GlobalLabelPoolCreateCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LabelPoolCreateCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.GlobalLabelPoolDestoryCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LabelPoolDestroyCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.GlobalLabelReleaseCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LabelReleaseCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.GlobalLabelApplyCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LabelApplyCommand"/>
</command>
<!-- tunnel commands -->
<command>
<action class="org.onosproject.cli.net.TunnelBorrowCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelReturnCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelQueryCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelQuerySubscriptionCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelCreateCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelRemoveCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.TunnelUpdateCommand"/>
</command>
<!-- device key commands -->
<command>
<action class="org.onosproject.cli.net.DeviceKeyListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceKeyAddCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.DeviceKeyRemoveCommand"/>
</command>
<!--region commands -->
<command>
<action class="org.onosproject.cli.net.RegionListCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionAddCommand"/>
<completers>
<null/>
<null/>
<ref component-id="regionTypeCompleter"/>
<ref component-id="nodeIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionUpdateCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
<null/>
<ref component-id="regionTypeCompleter"/>
<ref component-id="nodeIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionRemoveCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionAddDevicesCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionRemoveDevicesCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
<ref component-id="deviceIdCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.RegionAddPeerLocCommand"/>
<completers>
<ref component-id="regionIdCompleter"/>
</completers>
</command>
<!-- UI Layout commands -->
<command>
<action class="org.onosproject.cli.net.LayoutListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.LayoutAddCommand"/>
</command>
<!--TODO: add this + completers
<command>
<action class="org.onosproject.cli.net.LayoutRemoveCommand"/>
</command>
-->
<!--virtual network commands -->
<command>
<action class="org.onosproject.cli.net.vnet.TenantListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.TenantAddCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.TenantRemoveCommand"/>
<completers>
<ref component-id="tenantCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkCreateCommand"/>
<completers>
<ref component-id="tenantCompleter"/>
<ref component-id="nullCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualDeviceListCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualDeviceCreateCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualDeviceRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="nullCompleter"/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualLinkListCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualLinkCreateCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualLinkRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualPortListCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualPortCreateCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="nullCompleter"/>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualPortBindCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<ref component-id="deviceIdCompleter"/>
<ref component-id="portNumberCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualPortRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="virtualPortCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualHostListCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualHostCreateCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualHostRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="virtualHostCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkIntentCreateCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkIntentRemoveCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualFlowsListCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<ref component-id="flowRuleStatusCompleter"/>
<ref component-id="virtualDeviceCompleter"/>
<ref component-id="placeholderCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkPacketRequestCommand"/>
<optional-completers>
<entry key="-t" value-ref="ethTypeCompleter"/>
<entry key="--ipProto" value-ref="ipProtocolCompleter"/>
<entry key="--icmp6Type" value-ref="Icmp6TypeCompleter"/>
<entry key="--icmp6Code" value-ref="Icmp6CodeCompleter"/>
<entry key="--extHdr" value-ref="ExtHeaderCompleter"/>
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.vnet.VirtualNetworkBalanceMastersCommand"/>
<completers>
<ref component-id="virtualNetworkCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.cli.net.DpisListCommand"/>
</command>
<command>
<action class="org.onosproject.cli.net.IntentDetailsCommand"/>
<optional-completers>
<entry key="--id" value-ref="intentIdCompleter"/>
</optional-completers>
</command>
<command>
<action class="org.onosproject.cli.net.ConfigureLinkCommand"/>
<completers>
<ref component-id="connectPointCompleter"/>
<ref component-id="peerConnectPointCompleter"/>
<null/>
</completers>
<optional-completers>
<entry key="--type" value-ref="linkTypeCompleter"/>
</optional-completers>
</command>
<!--Domain command-->
<command>
<action class="org.onosproject.cli.net.GetDomainsCommand"/>
</command>
</command-bundle>
<bean id="reviewAppNameCompleter" class="org.onosproject.cli.security.ReviewApplicationNameCompleter"/>
<bean id="appCommandCompleter" class="org.onosproject.cli.app.ApplicationCommandCompleter"/>
<bean id="appNameCompleter" class="org.onosproject.cli.app.ApplicationNameCompleter"/>
<bean id="allAppNameCompleter" class="org.onosproject.cli.app.AllApplicationNamesCompleter"/>
<bean id="appIdWithIntentNameCompleter" class="org.onosproject.cli.app.ApplicationIdWithIntentNameCompleter"/>
<bean id="cfgCommandCompleter" class="org.onosproject.cli.cfg.ComponentConfigCommandCompleter"/>
<bean id="componentNameCompleter" class="org.onosproject.cli.cfg.ComponentNameCompleter"/>
<bean id="componentPropertyNameCompleter" class="org.onosproject.cli.cfg.ComponentPropertyNameCompleter"/>
<bean id="nodeIdCompleter" class="org.onosproject.cli.NodeIdCompleter"/>
<bean id="deviceIdCompleter" class="org.onosproject.cli.net.DeviceIdCompleter"/>
<bean id="portNumberCompleter" class="org.onosproject.cli.net.PortNumberCompleter"/>
<bean id="portStateCompleter" class="org.onosproject.cli.net.PortStateCompleter"/>
<bean id="clusterIdCompleter" class="org.onosproject.cli.net.ClusterIdCompleter"/>
<bean id="roleCompleter" class="org.onosproject.cli.net.RoleCompleter"/>
<bean id="hostIdCompleter" class="org.onosproject.cli.net.HostIdCompleter"/>
<bean id="intentKeyCompleter" class="org.onosproject.cli.net.IntentKeyCompleter"/>
<bean id="intentIdCompleter" class="org.onosproject.cli.net.completer.IntentIdCompleter"/>
<bean id="flowRuleStatusCompleter" class="org.onosproject.cli.net.FlowRuleStatusCompleter"/>
<bean id="groupStatusCompleter" class="org.onosproject.cli.net.GroupStatusCompleter" />
<bean id="connectPointCompleter" class="org.onosproject.cli.net.ConnectPointCompleter"/>
<bean id="nullCompleter" class="org.apache.karaf.shell.console.completer.NullCompleter"/>
<bean id="ethTypeCompleter" class="org.onosproject.cli.net.EthTypeCompleter"/>
<bean id="ipProtocolCompleter" class="org.onosproject.cli.net.IpProtocolCompleter"/>
<bean id="driverNameCompleter" class="org.onosproject.cli.net.DriverNameCompleter"/>
<bean id="Icmp6TypeCompleter" class="org.onosproject.cli.net.Icmp6TypeCompleter"/>
<bean id="Icmp6CodeCompleter" class="org.onosproject.cli.net.Icmp6CodeCompleter"/>
<bean id="ExtHeaderCompleter" class="org.onosproject.cli.net.ExtHeaderCompleter"/>
<bean id="startStopCompleter" class="org.onosproject.cli.StartStopCompleter"/>
<bean id="metricNameCompleter" class="org.onosproject.cli.MetricNameCompleter"/>
<bean id="upDownCompleter" class="org.onosproject.cli.UpDownCompleter"/>
<bean id="encapTypeCompleter" class="org.onosproject.cli.net.EncapTypeCompleter"/>
<bean id="placeholderCompleter" class="org.onosproject.cli.PlaceholderCompleter"/>
<bean id="subjectClassKeyCompleter" class="org.onosproject.cli.cfg.SubjectClassKeyCompleter"/>
<bean id="subjectKeyCompleter" class="org.onosproject.cli.cfg.SubjectKeyCompleter"/>
<bean id="configKeyCompleter" class="org.onosproject.cli.cfg.ConfigKeyCompleter"/>
<bean id="regionIdCompleter" class="org.onosproject.cli.net.RegionIdCompleter"/>
<bean id="regionTypeCompleter" class="org.onosproject.cli.net.RegionTypeCompleter"/>
<bean id="annotationKeysCompleter" class="org.onosproject.cli.net.completer.AnnotationKeysCompleter"/>
<bean id="peerConnectPointCompleter" class="org.onosproject.cli.net.completer.PeerConnectPointCompleter"/>
<bean id="interfaceNameCompleter" class="org.onosproject.cli.net.completer.InterfaceNameCompleter"/>
<bean id="linkTypeCompleter" class="org.onosproject.cli.net.completer.LinkTypeCompleter"/>
<bean id="tenantCompleter" class="org.onosproject.cli.net.vnet.TenantCompleter"/>
<bean id="virtualNetworkCompleter" class="org.onosproject.cli.net.vnet.VirtualNetworkCompleter"/>
<bean id="virtualDeviceCompleter" class="org.onosproject.cli.net.vnet.VirtualDeviceCompleter"/>
<bean id="virtualPortCompleter" class="org.onosproject.cli.net.vnet.VirtualPortCompleter"/>
<bean id="virtualHostCompleter" class="org.onosproject.cli.net.vnet.VirtualHostCompleter"/>
<bean id="domainIdCompleter" class="org.onosproject.cli.net.DomainIdCompleter" />
</blueprint>
| {
"content_hash": "997f562e525569277a2cea4abeae91d5",
"timestamp": "",
"source": "github",
"line_count": 980,
"max_line_length": 114,
"avg_line_length": 39.95510204081633,
"alnum_prop": 0.5721473082030851,
"repo_name": "LorenzReinhart/ONOSnew",
"id": "15d2a6464e89ce9ade20d1ff4d6543fb3f11f396",
"size": "39156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cli/src/main/resources/OSGI-INF/blueprint/shell-config.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "224030"
},
{
"name": "HTML",
"bytes": "108368"
},
{
"name": "Java",
"bytes": "34148438"
},
{
"name": "JavaScript",
"bytes": "3833411"
},
{
"name": "Protocol Buffer",
"bytes": "13730"
},
{
"name": "Python",
"bytes": "185205"
},
{
"name": "Shell",
"bytes": "2594"
}
],
"symlink_target": ""
} |
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
describe("B suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
describe("C suite", function() {
it("contains spec with an expectation", function() {
expect(1).toBe(true);
});
});
| {
"content_hash": "f9996827cac900af67aa43281231432e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 56,
"avg_line_length": 23.764705882352942,
"alnum_prop": 0.5792079207920792,
"repo_name": "jackzing/automation",
"id": "7c328f77ea60cf5cc6c5e6bd0b53e4bd318a5285",
"size": "404",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/js/test/jasmine/first.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3100"
}
],
"symlink_target": ""
} |
@interface DeviceAudioOutput : NSObject
- (id)initWithProducer:(id<QuietAudioProducer>)p
withNumBuffers:(unsigned int)numBuffers
withBufferLength:(unsigned int)bufferLength;
@end
| {
"content_hash": "32faf220dfb12248c2a6093e493a08a6",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 50,
"avg_line_length": 38.6,
"alnum_prop": 0.7772020725388601,
"repo_name": "quiet/QuietModemKit",
"id": "493e0aef22d993db61a880b900804c196727a4e4",
"size": "257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "QuietModemKit/DeviceAudioOutput.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CMake",
"bytes": "11386"
},
{
"name": "Objective-C",
"bytes": "69694"
},
{
"name": "Shell",
"bytes": "4009"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<citations>
<bibl><title level="j">AAPS PharmSciTech</title> <date>2002</date>; <biblScope type="vol">3</biblScope> (<biblScope type="issue">2</biblScope>) <idno>article 7</idno></bibl>
</citations>
| {
"content_hash": "5f52ac91b14718d2405ae8d7aba46dfb",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 174,
"avg_line_length": 59.75,
"alnum_prop": 0.6861924686192469,
"repo_name": "Aazhar/grobid",
"id": "a9be3e777fdbc67a29c72133b7a970a941356782",
"size": "239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grobid-trainer/resources/dataset/citation/corpus/55010894.header-reference.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* (C) 2015 NPException
*/
package de.npe.gameanalytics.events;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import de.npe.gameanalytics.Analytics;
import de.npe.gameanalytics.Analytics.KeyPair;
/**
* Base event class. Contains values that are mandatory for all event types.
*
* @author NPException
*
*/
public abstract class GAEvent {
private static Gson GSON; // only initialized if necessary
public final transient KeyPair keyPair;
@SerializedName("user_id")
private final String userID;
@SerializedName("session_id")
private final String sessionID;
@SerializedName("build")
private final String build;
private transient String toString;
GAEvent(Analytics an) {
keyPair = an.keyPair();
userID = an.getUserID();
sessionID = an.getSessionID();
build = an.build();
}
public abstract String category();
@Override
public String toString() {
if (toString == null) {
String tmp;
try {
if (GSON == null) {
GSON = new Gson();
}
tmp = GSON.toJson(this);
} catch (Exception ex) {
tmp = super.toString();
}
tmp = tmp + " + " + String.valueOf(keyPair);
toString = tmp;
}
return toString;
}
}
| {
"content_hash": "f857dce7bed81281f0770a3611a89fa4",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 76,
"avg_line_length": 20.423728813559322,
"alnum_prop": 0.6854771784232365,
"repo_name": "pixlepix/CompositeReactors",
"id": "1cebc8dacfe3db90d2b3415f56257bc18d6825b5",
"size": "1205",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/gameanalytics/de/npe/gameanalytics/events/GAEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "264572"
}
],
"symlink_target": ""
} |
.. document::
.. title:: Demo document
.. stylesheet:: style.css
.. meta::
:description: A demo Gregwar/RST document
.. .. this is a comment!
Gregwar/RST Sandbox
===================
Reference to :doc:`HoHo <some/doc>`
.. note::
**Note**:
This is a testing sandbox, if you want to understand how it works, have a
look to the rst original file
#=) Titles
----------
#-) Using titles
~~~~~~~~~~~~~~~~
Titles can be wrote using the underlining, the default order is:
1. ``=======``
2. ``-------``
3. ``~~~~~~~``
4. ``*******``
#-) Using auto-numbering
~~~~~~~~~~~~~~~~~~~~~~~~
This is not a standard of RST but is really useful, you can use the special syntax
``#`` followed by the letter of the title you are in (it resets the counter when used).
You can for instance use ``Question #*`` if you are under an ``*******``, the number
displayed will be auto-incremented:
** Question #* **
The first question
** Question #* **
The second question
This can of course also be used to number parts, chapter etc.
#-) Separator
~~~~~~~~~~~~~
A separator is like a title underline but without any text above::
-----
This will result in a text separation:
----
#=) Inline style
----------------
* ``*italic*`` renders as *italic*
* ``**strong**`` renders as **strong**
You can force a line break by adding an extra space at the end of a line
#=) Tables
----------
Tables can be created using the line separator ``====``::
================ ================
**First column** **Other column**
================ ================
Second row with Second row, of the
some contents text other column
============ ================
Will result in:
================ ================
**First column** **Other column**
================ ================
Second row with Second row, of the
some contents text other column
============ ================
Another example:
=== === ===
Col A Col B Col C
=== === ===
Col X Col Y Col Z
=== === ===
Col U Col J Col K
=== === ===
#=) Lists
---------
Lists can be ordered or unordered, and nested, for instance this::
* Element A
* Sub A, this a
multiline sentence in the source
1. Sub ordered as "1"
2. Sub ordered as "2"
* Sub hello two
* Element B
While result in:
* Element A
* Sub A, this a
multiline sentence in the source
1. Sub ordered as "1"
2. Sub ordered as "2"
* Sub hello two
* Element B
#=) Blocks
----------
#-) Quoting
~~~~~~~~~~~
You can quote a block by indenting it::
This is a normal pagagraph
This is a quote
Will result in:
This is a normal paragraph
This is a quote
#-) Code
~~~~~~~~
You can quote code the same way as quote, but using the ``::`` at the end
of the previous paragraph::
Here is a piece of code:
.. code-block:: php
<?php
echo "I love RST";
Will result in:
Here is a piece of code:
.. code-block:: php
<?php
echo "I love RST";
#=) Links
---------
#-) Standard links
~~~~~~~~~~~~~~~~~~
Links can be defined once for all using the trailing ``_``, like this::
PHP_ is a great language
.. _PHP: http://php.net/
Will result in:
PHP_ is a great language
.. _PHP: http://php.net/
#-) Anonymous links
~~~~~~~~~~~~~~~~~~~
Anonymous links can also be used to avoid copying the name just after the
block that uses it, for instance::
I love GitHub__
.. __: http://www.github.com/
Will result in:
I love GitHub__
.. __: http://www.github.com/
You can use the following shortcut::
I love GitHub__
__ http://www.github.com/
#-) Inline links
~~~~~~~~~~~~~~~~
You can also define the link target inside the link::
Do you know `Google <http://www.google.com>`_ ?
Will result in:
Do you know `Google <http://www.google.com>`_ ?
#-) Anchor links
~~~~~~~~~~~~~~~~
An anchor can be used like this::
.. _anchor:
Some anchor section, you can link to it like `this <#anchor>`_
Will result in:
.. _anchor:
Some anchor section, you can link to it like `this <#anchor>`_
#=) Directives
--------------
#-) Include
~~~~~~~~~~~
.. include:: include.rst
#-) Replace
~~~~~~~~~~~
You can use the replace directive like this::
.. |name| replace:: bob
Hello |name| !
Will result in:
.. |name| replace:: bob
Hello |name| !
#-) Image
~~~~~~~~~
The ``image`` directive can be used to display images, this way::
.. image:: rst.png
:width: 250px
:title: RST logo
Will result in:
.. image:: rst.png
:width: 250px
:title: RST logo
| {
"content_hash": "c1b619c2c644c64aca88d39f3552e74a",
"timestamp": "",
"source": "github",
"line_count": 269,
"max_line_length": 87,
"avg_line_length": 17.434944237918216,
"alnum_prop": 0.5439232409381664,
"repo_name": "Gregwar/RST",
"id": "7d2649cb724ab7ad714155926ea880b85be3b99e",
"size": "4690",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/document/document.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "999"
},
{
"name": "HTML",
"bytes": "6076"
},
{
"name": "PHP",
"bytes": "147642"
}
],
"symlink_target": ""
} |
import falcor from 'falcor';
import _ from 'lodash';
import * as db from 'lib/db';
const $ref = falcor.Model.ref;
export default [
{
// Search for staff member by name
route: "search['staff'][{keys:queries}][{integers:indices}]",
get: pathSet =>
new Promise(resolve => {
let minIndex = pathSet.indices[0];
let maxIndex = pathSet.indices[0];
pathSet.indices.forEach(index => {
if (index < minIndex) {
minIndex = index;
}
if (index > maxIndex) {
maxIndex = index;
}
});
db.searchStaffQuery(pathSet.queries, minIndex, maxIndex).then(data => {
// Map all the indices down to fit the indices returned by the db call
const processedPathSet = {
...pathSet,
indices: pathSet.indices.map(index => index - minIndex),
};
const results = [];
_.forEach(data, (queryResults, query) => {
processedPathSet.indices.forEach(index => {
if (index < queryResults.length) {
results.push({
path: ['search', 'staff', query, index],
value: $ref(['staff', 'bySlug', queryResults[index]]),
});
}
});
});
resolve(results);
});
}),
},
];
| {
"content_hash": "8080d549cc715b8761d6f0166daacef6",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 80,
"avg_line_length": 30.355555555555554,
"alnum_prop": 0.5029282576866764,
"repo_name": "thegazelle-ad/gazelle-server",
"id": "88e91e4f25f09b68fa64fa828f08fc56080aff36",
"size": "1366",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/lib/falcor/routes/search/staff.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1167"
},
{
"name": "Dockerfile",
"bytes": "278"
},
{
"name": "HTML",
"bytes": "6724"
},
{
"name": "JavaScript",
"bytes": "580728"
},
{
"name": "Python",
"bytes": "815"
},
{
"name": "SCSS",
"bytes": "41454"
},
{
"name": "Shell",
"bytes": "9946"
},
{
"name": "TypeScript",
"bytes": "10723"
}
],
"symlink_target": ""
} |
package alluxio.proxy.s3.signature;
import static alluxio.proxy.s3.S3Constants.AUTHORIZATION_CHARSET;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.SigningAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.apache.kerby.util.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* AWS v4 authentication payload validator. For more details refer to AWS
* documentation https://docs.aws.amazon.com/general/latest/gr/
* sigv4-create-canonical-request.html.
**/
public class AuthorizationV4Validator {
private static final Logger LOG =
LoggerFactory.getLogger(AuthorizationV4Validator.class);
private static final char LINE_SEPARATOR = '\n';
private static final char SIGN_SEPARATOR = '/';
private static final String AWS4_TERMINATOR = "aws4_request";
private static final SigningAlgorithm HMAC_SHA256 = SigningAlgorithm.HmacSHA256;
private AuthorizationV4Validator() {
}
/**
* Validate request by comparing Signature from request. Returns true if
* aws request is legit else returns false.
* Signature = HEX(HMAC_SHA256(key, String to Sign))
*
* For more details refer to AWS documentation: https://docs.aws.amazon.com
* /AmazonS3/latest/API/sigv4-streaming.html
*
* @param strToSign string to sign
* @param signature signature string
* @param userKey secretKey
* @return ture, if validate success
*/
public static boolean validateRequest(String strToSign, String signature,
String userKey) {
String expectedSignature = Hex.encode(sign(getSignedKey(userKey,
strToSign), strToSign));
return expectedSignature.equals(signature);
}
/**
* function to compute sign.
* @param key key info
* @param msg msg info
* @return sign bytes
*/
private static byte[] sign(byte[] key, String msg) {
return sign(msg.getBytes(AUTHORIZATION_CHARSET), key, HMAC_SHA256);
}
private static byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm)
throws SdkClientException {
try {
Mac mac = algorithm.getMac();
mac.init(new SecretKeySpec(key, algorithm.name()));
return mac.doFinal(data);
} catch (GeneralSecurityException gse) {
throw new RuntimeException(gse);
}
}
/**
* Returns signed key.
*
* @param key
* @param strToSign
*
* SignatureKey = HMAC-SHA256(HMAC-SHA256(HMAC-SHA256(HMAC-SHA256("AWS4" +
* "<YourSecretAccessKey/>","20130524"),"us-east-1"),"s3"),"aws4_request")
*
* For more details refer to AWS documentation: https://docs.aws.amazon
* .com/AmazonS3/latest/API/sig-v4-header-based-auth.html
*
* */
private static byte[] getSignedKey(String key, String strToSign) {
LOG.debug("strToSign: {}", strToSign);
String[] signData = StringUtils.split(StringUtils.split(strToSign,
LINE_SEPARATOR)[2],
SIGN_SEPARATOR);
String dateStamp = signData[0];
String regionName = signData[1];
String serviceName = signData[2];
byte[] kDate = sign(("AWS4" + key).getBytes(AUTHORIZATION_CHARSET), dateStamp);
byte[] kRegion = sign(kDate, regionName);
byte[] kService = sign(kRegion, serviceName);
byte[] kSigning = sign(kService, AWS4_TERMINATOR);
LOG.info(Hex.encode(kSigning));
return kSigning;
}
}
| {
"content_hash": "bfae0703963c0bdf46d1581a4b7e0911",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 83,
"avg_line_length": 33.32692307692308,
"alnum_prop": 0.6959030582804385,
"repo_name": "Alluxio/alluxio",
"id": "f054e9350e15a4a4a34cd9d9150fbface1df7a15",
"size": "3978",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/server/proxy/src/main/java/alluxio/proxy/s3/signature/AuthorizationV4Validator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7326"
},
{
"name": "C++",
"bytes": "47930"
},
{
"name": "Dockerfile",
"bytes": "12060"
},
{
"name": "Go",
"bytes": "290492"
},
{
"name": "HTML",
"bytes": "3412"
},
{
"name": "Handlebars",
"bytes": "3633"
},
{
"name": "Java",
"bytes": "15503816"
},
{
"name": "JavaScript",
"bytes": "9992"
},
{
"name": "Makefile",
"bytes": "6312"
},
{
"name": "Mustache",
"bytes": "22163"
},
{
"name": "Python",
"bytes": "18085"
},
{
"name": "Roff",
"bytes": "5919"
},
{
"name": "Ruby",
"bytes": "15044"
},
{
"name": "SCSS",
"bytes": "12027"
},
{
"name": "Shell",
"bytes": "278582"
},
{
"name": "TypeScript",
"bytes": "324466"
}
],
"symlink_target": ""
} |
namespace content {
class WebKitTestRunnerBindings : public v8::Extension {
public:
WebKitTestRunnerBindings();
virtual ~WebKitTestRunnerBindings();
// v8::Extension implementation.
virtual v8::Handle<v8::FunctionTemplate>
GetNativeFunction(v8::Handle<v8::String> name) OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(WebKitTestRunnerBindings);
};
} // namespace content
#endif // CONTENT_SHELL_WEBKIT_TEST_RUNNER_BINDINGS_H_
| {
"content_hash": "7b5df1dfe4edb83ff3840d4d3261334d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 62,
"avg_line_length": 24.833333333333332,
"alnum_prop": 0.7516778523489933,
"repo_name": "leighpauls/k2cro4",
"id": "d9eac862542d2c3fbd65d6aea34c457b19fd415e",
"size": "817",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "content/shell/webkit_test_runner_bindings.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "3062"
},
{
"name": "AppleScript",
"bytes": "25392"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "68131038"
},
{
"name": "C",
"bytes": "242794338"
},
{
"name": "C#",
"bytes": "11024"
},
{
"name": "C++",
"bytes": "353525184"
},
{
"name": "Common Lisp",
"bytes": "3721"
},
{
"name": "D",
"bytes": "1931"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "F#",
"bytes": "4992"
},
{
"name": "FORTRAN",
"bytes": "10404"
},
{
"name": "Java",
"bytes": "3845159"
},
{
"name": "JavaScript",
"bytes": "39146656"
},
{
"name": "Lua",
"bytes": "13768"
},
{
"name": "Matlab",
"bytes": "22373"
},
{
"name": "Objective-C",
"bytes": "21887598"
},
{
"name": "PHP",
"bytes": "2344144"
},
{
"name": "Perl",
"bytes": "49033099"
},
{
"name": "Prolog",
"bytes": "2926122"
},
{
"name": "Python",
"bytes": "39863959"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Racket",
"bytes": "359"
},
{
"name": "Ruby",
"bytes": "304063"
},
{
"name": "Scheme",
"bytes": "14853"
},
{
"name": "Shell",
"bytes": "9195117"
},
{
"name": "Tcl",
"bytes": "1919771"
},
{
"name": "Verilog",
"bytes": "3092"
},
{
"name": "Visual Basic",
"bytes": "1430"
},
{
"name": "eC",
"bytes": "5079"
}
],
"symlink_target": ""
} |
package de.frosner.datagenerator.distributions;
import javax.annotation.Nonnull;
import net.sf.qualitycheck.Check;
import de.frosner.datagenerator.features.ContinuousFeatureValue;
import de.frosner.datagenerator.features.FeatureDefinition;
import de.frosner.datagenerator.features.FeatureValue;
public class ContinuousVariableParameter extends VariableParameter<Double> {
/**
* Constructs a new {@linkplain ContinuousVariableParameter} conditioned on the specified
* {@linkplain FeatureDefinition}.
*
* @param featureDefinition
* this parameter is conditioned on
*/
public ContinuousVariableParameter(@Nonnull FeatureDefinition featureDefinition) {
super(featureDefinition);
}
@Override
public void updateParameter(FeatureValue value) {
Check.instanceOf(ContinuousFeatureValue.class, value, "value");
_parameter = ((ContinuousFeatureValue) value).getDoubleValue();
}
}
| {
"content_hash": "7283be66f6369b6d84c4c8e426f08994",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 90,
"avg_line_length": 31.413793103448278,
"alnum_prop": 0.7947310647639956,
"repo_name": "FRosner/DataGenerator",
"id": "83adb0c8021357f19fe1ddf61dd4dc79f0bca4be",
"size": "911",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/frosner/datagenerator/distributions/ContinuousVariableParameter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "305360"
},
{
"name": "Scala",
"bytes": "1222"
}
],
"symlink_target": ""
} |
title='
JUGEND RETTET
'
# Description of the whole page (e.g. to be seen on link preview cards)
description='
Wir sind eine Organisation junger Menschen, die mithilfe von Spenden ehrenamtlich Seenotrettung betreiben. Mit unserem Schiff, der IUVENTA, retten wir Menschen aus Seenot im Mittelmeer.
Unterstรผtze uns jetzt und rette mit!
'
| {
"content_hash": "d2492c98dffe6a676781141954fc2a04",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 185,
"avg_line_length": 37.333333333333336,
"alnum_prop": 0.7946428571428571,
"repo_name": "JugendRettet/translations",
"id": "4277e179074e6db2c4323ca135376efe2800d71e",
"size": "402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "de/general.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "575"
}
],
"symlink_target": ""
} |
int main(int argc, char** argv)
{
using namespace NeedHug;
ReturnCode returnCode = ReturnCode::Stop_Restart;
while (returnCode == NeedHug::ReturnCode::Stop_Restart)
{
// When the code reaches here, nothing should be allocated any longer in order to avoid memoryleaks.
NeedHugGame needHugGame;
try
{
returnCode = needHugGame.Start();
}
catch (...)
{
std::cout << "Game crashed unexpectedly" << std::endl;
returnCode = ReturnCode::Unknown;
}
}
std::cout << "The game returned the following stopCode '" << ReturnCodeConverter().Convert(returnCode).info << "'." << std::endl;
int returnCodeValue = 1;
if (returnCode == ReturnCode::Stop_End)
{
returnCodeValue = 0;
}
#ifdef _WIN32
std::getchar();
#endif
return returnCodeValue;
}
| {
"content_hash": "581c84067293437ce67bd451fa332e39",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 130,
"avg_line_length": 23.96875,
"alnum_prop": 0.6857887874837028,
"repo_name": "Poelsa/need-hug",
"id": "1ba1dc618da50bb5e22e7d93d7cfe108f90657f2",
"size": "863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "need-hug/src/Main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "38766"
},
{
"name": "CMake",
"bytes": "28398"
},
{
"name": "Shell",
"bytes": "6716"
}
],
"symlink_target": ""
} |
package edu.emory.cci.aiw.i2b2etl.dest;
import edu.emory.cci.aiw.i2b2etl.AbstractDataAndMetadataTest;
import edu.emory.cci.aiw.i2b2etl.ProtempaFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Parent class to all test classes that creates a protempa instance.
*
* @author Andrew Post
*/
public abstract class AbstractI2b2DestDataAndMetadataTest extends AbstractDataAndMetadataTest {
private static ProtempaFactory protempaFactory;
@BeforeClass
public static void setUpClsCreateProtempaFactory() throws Exception {
protempaFactory = new ProtempaFactory(getConfigFactory());
}
@AfterClass
public static void tearDownClsCloseProtempaFactory() throws Exception {
if (protempaFactory != null) {
protempaFactory.close();
}
}
public static ProtempaFactory getProtempaFactory() {
return protempaFactory;
}
}
| {
"content_hash": "a76e4b6f93071632bc8668405024a89a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 95,
"avg_line_length": 26.941176470588236,
"alnum_prop": 0.740174672489083,
"repo_name": "arpost/aiw-i2b2-etl",
"id": "6cf9aa71de846c01e446559c419f7fad3cd4e5c7",
"size": "1568",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/edu/emory/cci/aiw/i2b2etl/dest/AbstractI2b2DestDataAndMetadataTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "279"
},
{
"name": "Java",
"bytes": "745490"
},
{
"name": "PLpgSQL",
"bytes": "2772"
}
],
"symlink_target": ""
} |
#ifndef __GAME_PROJECTILE_H__
#define __GAME_PROJECTILE_H__
/*
===============================================================================
idProjectile
===============================================================================
*/
extern const idEventDef EV_Explode;
class idProjectile : public idEntity {
public :
CLASS_PROTOTYPE( idProjectile );
idProjectile();
virtual ~idProjectile();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Create( idEntity *owner, const idVec3 &start, const idVec3 &dir );
virtual void Launch( const idVec3 &start, const idVec3 &dir, const idVec3 &pushVelocity, const float timeSinceFire = 0.0f, const float launchPower = 1.0f, const float dmgPower = 1.0f );
virtual void FreeLightDef( void );
idEntity * GetOwner( void ) const;
#ifdef _D3XP
void CatchProjectile( idEntity* o, const char* reflectName );
int GetProjectileState( void );
void Event_CreateProjectile( idEntity *owner, const idVec3 &start, const idVec3 &dir );
void Event_LaunchProjectile( const idVec3 &start, const idVec3 &dir, const idVec3 &pushVelocity );
void Event_SetGravity( float gravity );
#endif
virtual void Think( void );
virtual void Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location );
virtual bool Collide( const trace_t &collision, const idVec3 &velocity );
virtual void Explode( const trace_t &collision, idEntity *ignore );
void Fizzle( void );
static idVec3 GetVelocity( const idDict *projectile );
static idVec3 GetGravity( const idDict *projectile );
enum {
EVENT_DAMAGE_EFFECT = idEntity::EVENT_MAXEVENTS,
EVENT_MAXEVENTS
};
static void DefaultDamageEffect( idEntity *soundEnt, const idDict &projectileDef, const trace_t &collision, const idVec3 &velocity );
static bool ClientPredictionCollide( idEntity *soundEnt, const idDict &projectileDef, const trace_t &collision, const idVec3 &velocity, bool addDamageEffect );
virtual void ClientPredictionThink( void );
virtual void WriteToSnapshot( idBitMsgDelta &msg ) const;
virtual void ReadFromSnapshot( const idBitMsgDelta &msg );
virtual bool ClientReceiveEvent( int event, int time, const idBitMsg &msg );
protected:
idEntityPtr<idEntity> owner;
struct projectileFlags_s {
bool detonate_on_world : 1;
bool detonate_on_actor : 1;
bool randomShaderSpin : 1;
bool isTracer : 1;
bool noSplashDamage : 1;
} projectileFlags;
float thrust;
int thrust_end;
float damagePower;
renderLight_t renderLight;
qhandle_t lightDefHandle; // handle to renderer light def
idVec3 lightOffset;
int lightStartTime;
int lightEndTime;
idVec3 lightColor;
idForce_Constant thruster;
idPhysics_RigidBody physicsObj;
const idDeclParticle * smokeFly;
int smokeFlyTime;
#ifdef _D3XP
int originalTimeGroup;
#endif
typedef enum {
// must update these in script/doom_defs.script if changed
SPAWNED = 0,
CREATED = 1,
LAUNCHED = 2,
FIZZLED = 3,
EXPLODED = 4
} projectileState_t;
projectileState_t state;
private:
bool netSyncPhysics;
void AddDefaultDamageEffect( const trace_t &collision, const idVec3 &velocity );
void Event_Explode( void );
void Event_Fizzle( void );
void Event_RadiusDamage( idEntity *ignore );
void Event_Touch( idEntity *other, trace_t *trace );
void Event_GetProjectileState( void );
};
class idGuidedProjectile : public idProjectile {
public :
CLASS_PROTOTYPE( idGuidedProjectile );
idGuidedProjectile( void );
~idGuidedProjectile( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
virtual void Think( void );
virtual void Launch( const idVec3 &start, const idVec3 &dir, const idVec3 &pushVelocity, const float timeSinceFire = 0.0f, const float launchPower = 1.0f, const float dmgPower = 1.0f );
#ifdef _D3XP
void SetEnemy( idEntity *ent );
void Event_SetEnemy(idEntity *ent);
#endif
protected:
float speed;
idEntityPtr<idEntity> enemy;
virtual void GetSeekPos( idVec3 &out );
private:
idAngles rndScale;
idAngles rndAng;
idAngles angles;
int rndUpdateTime;
float turn_max;
float clamp_dist;
bool burstMode;
bool unGuided;
float burstDist;
float burstVelocity;
};
class idSoulCubeMissile : public idGuidedProjectile {
public:
CLASS_PROTOTYPE ( idSoulCubeMissile );
~idSoulCubeMissile();
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
virtual void Think( void );
virtual void Launch( const idVec3 &start, const idVec3 &dir, const idVec3 &pushVelocity, const float timeSinceFire = 0.0f, const float power = 1.0f, const float dmgPower = 1.0f );
protected:
virtual void GetSeekPos( idVec3 &out );
void ReturnToOwner( void );
void KillTarget( const idVec3 &dir );
private:
idVec3 startingVelocity;
idVec3 endingVelocity;
float accelTime;
int launchTime;
bool killPhase;
bool returnPhase;
idVec3 destOrg;
idVec3 orbitOrg;
int orbitTime;
int smokeKillTime;
const idDeclParticle * smokeKill;
};
struct beamTarget_t {
idEntityPtr<idEntity> target;
renderEntity_t renderEntity;
qhandle_t modelDefHandle;
};
class idBFGProjectile : public idProjectile {
public :
CLASS_PROTOTYPE( idBFGProjectile );
idBFGProjectile();
~idBFGProjectile();
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
virtual void Think( void );
virtual void Launch( const idVec3 &start, const idVec3 &dir, const idVec3 &pushVelocity, const float timeSinceFire = 0.0f, const float launchPower = 1.0f, const float dmgPower = 1.0f );
virtual void Explode( const trace_t &collision, idEntity *ignore );
private:
idList<beamTarget_t> beamTargets;
renderEntity_t secondModel;
qhandle_t secondModelDefHandle;
int nextDamageTime;
idStr damageFreq;
void FreeBeams();
void Event_RemoveBeams();
void ApplyDamage();
};
/*
===============================================================================
idDebris
===============================================================================
*/
class idDebris : public idEntity {
public :
CLASS_PROTOTYPE( idDebris );
idDebris();
~idDebris();
// save games
void Save( idSaveGame *savefile ) const; // archives object for save game file
void Restore( idRestoreGame *savefile ); // unarchives object from save game file
void Spawn( void );
void Create( idEntity *owner, const idVec3 &start, const idMat3 &axis );
void Launch( void );
void Think( void );
void Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location );
void Explode( void );
void Fizzle( void );
virtual bool Collide( const trace_t &collision, const idVec3 &velocity );
private:
idEntityPtr<idEntity> owner;
idPhysics_RigidBody physicsObj;
const idDeclParticle * smokeFly;
int smokeFlyTime;
const idSoundShader * sndBounce;
void Event_Explode( void );
void Event_Fizzle( void );
};
#endif /* !__GAME_PROJECTILE_H__ */
| {
"content_hash": "840e204a30566c006ffed3f28a7ceacf",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 188,
"avg_line_length": 28.899224806201552,
"alnum_prop": 0.6645654506437768,
"repo_name": "Grimace1975/bclcontrib-scriptsharp",
"id": "d328b0f9f245b2e75d6675fdbc6e9183de2fea19",
"size": "8948",
"binary": false,
"copies": "58",
"ref": "refs/heads/master",
"path": "ref.neo/d3xp/Projectile.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "538"
},
{
"name": "Awk",
"bytes": "757"
},
{
"name": "Bison",
"bytes": "28643"
},
{
"name": "C",
"bytes": "4699807"
},
{
"name": "C#",
"bytes": "1254546"
},
{
"name": "C++",
"bytes": "21199604"
},
{
"name": "CSS",
"bytes": "435"
},
{
"name": "Emacs Lisp",
"bytes": "3759"
},
{
"name": "Groff",
"bytes": "1815"
},
{
"name": "HTML",
"bytes": "43572"
},
{
"name": "JavaScript",
"bytes": "893948"
},
{
"name": "Makefile",
"bytes": "2945"
},
{
"name": "NSIS",
"bytes": "958"
},
{
"name": "Objective-C",
"bytes": "170817"
},
{
"name": "Objective-C++",
"bytes": "2733"
},
{
"name": "Perl",
"bytes": "9219"
},
{
"name": "Python",
"bytes": "73136"
},
{
"name": "Shell",
"bytes": "260754"
}
],
"symlink_target": ""
} |
<?php
namespace Backend\Modules\Banners\Domain\Banner\Command;
use Backend\Modules\Banners\Domain\Banner\Banner;
final class DeleteBanner
{
/** @var Banner */
private $banner;
public function __construct(Banner $banner)
{
$this->banner = $banner;
}
public function getBanner(): Banner
{
return $this->banner;
}
}
| {
"content_hash": "a90e28b94d082cce4a2ef2138e7c695f",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 56,
"avg_line_length": 17.428571428571427,
"alnum_prop": 0.639344262295082,
"repo_name": "wijs/fork-cms-module-banners",
"id": "ae4532fa5aaf511f7ac749f81b28f7c2b23f4c44",
"size": "366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Backend/Modules/Banners/Domain/Banner/Command/DeleteBanner.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5319"
},
{
"name": "PHP",
"bytes": "59826"
}
],
"symlink_target": ""
} |
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.engine.valueextraction;
import java.lang.reflect.AnnotatedArrayType;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.validation.valueextraction.ExtractedValue;
import javax.validation.valueextraction.UnwrapByDefault;
import javax.validation.valueextraction.ValueExtractor;
import org.hibernate.validator.internal.util.ReflectionHelper;
import org.hibernate.validator.internal.util.StringHelper;
import org.hibernate.validator.internal.util.TypeHelper;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
/**
* Describes a {@link ValueExtractor}.
*
* @author Gunnar Morling
* @author Guillaume Smet
*/
public class ValueExtractorDescriptor {
private static final Log LOG = LoggerFactory.make();
private final Key key;
private final ValueExtractor<?> valueExtractor;
private final boolean unwrapByDefault;
private final Optional<Class<?>> extractedType;
public ValueExtractorDescriptor(ValueExtractor<?> valueExtractor) {
AnnotatedParameterizedType valueExtractorDefinition = getValueExtractorDefinition( valueExtractor.getClass() );
this.key = new Key(
getContainerType( valueExtractorDefinition, valueExtractor.getClass() ),
getExtractedTypeParameter( valueExtractorDefinition, valueExtractor.getClass() )
);
this.valueExtractor = valueExtractor;
this.unwrapByDefault = hasUnwrapByDefaultAnnotation( valueExtractor.getClass() );
this.extractedType = getExtractedType( valueExtractorDefinition );
}
@SuppressWarnings("rawtypes")
private static TypeVariable<?> getExtractedTypeParameter(AnnotatedParameterizedType valueExtractorDefinition,
Class<? extends ValueExtractor> extractorImplementationType) {
AnnotatedType containerType = valueExtractorDefinition.getAnnotatedActualTypeArguments()[0];
Class<?> containerTypeRaw = (Class<?>) TypeHelper.getErasedType( containerType.getType() );
TypeVariable<?> extractedTypeParameter = null;
if ( containerType.isAnnotationPresent( ExtractedValue.class ) ) {
if ( containerType instanceof AnnotatedArrayType ) {
extractedTypeParameter = new ArrayElement( (AnnotatedArrayType) containerType );
}
else {
extractedTypeParameter = AnnotatedObject.INSTANCE;
}
}
if ( containerType instanceof AnnotatedParameterizedType ) {
AnnotatedParameterizedType parameterizedExtractedType = (AnnotatedParameterizedType) containerType;
int i = 0;
for ( AnnotatedType typeArgument : parameterizedExtractedType.getAnnotatedActualTypeArguments() ) {
if ( !isUnboundWildcard( typeArgument.getType() ) ) {
throw LOG.getOnlyUnboundWildcardTypeArgumentsSupportedForContainerTypeOfValueExtractorException( extractorImplementationType );
}
if ( typeArgument.isAnnotationPresent( ExtractedValue.class ) ) {
if ( extractedTypeParameter != null ) {
throw LOG.getValueExtractorDeclaresExtractedValueMultipleTimesException( extractorImplementationType );
}
if ( !void.class.equals( typeArgument.getAnnotation( ExtractedValue.class ).type() ) ) {
throw LOG.getExtractedValueOnTypeParameterOfContainerTypeMayNotDefineTypeAttributeException( extractorImplementationType );
}
extractedTypeParameter = containerTypeRaw.getTypeParameters()[i];
}
i++;
}
}
if ( extractedTypeParameter == null ) {
throw LOG.getValueExtractorFailsToDeclareExtractedValueException( extractorImplementationType );
}
return extractedTypeParameter;
}
private static boolean isUnboundWildcard(Type type) {
if ( !( type instanceof WildcardType ) ) {
return false;
}
WildcardType wildcardType = (WildcardType) type;
return isEmptyBounds( wildcardType.getUpperBounds() ) && isEmptyBounds( wildcardType.getLowerBounds() );
}
private static boolean isEmptyBounds(Type[] bounds) {
return bounds == null || bounds.length == 0 || ( bounds.length == 1 && Object.class.equals( bounds[0] ) );
}
private static Optional<Class<?>> getExtractedType(AnnotatedParameterizedType valueExtractorDefinition) {
AnnotatedType containerType = valueExtractorDefinition.getAnnotatedActualTypeArguments()[0];
if ( containerType.isAnnotationPresent( ExtractedValue.class ) ) {
Class<?> extractedType = containerType.getAnnotation( ExtractedValue.class ).type();
if ( !void.class.equals( extractedType ) ) {
return Optional.of( ReflectionHelper.boxedType( extractedType ) );
}
}
return Optional.empty();
}
@SuppressWarnings("rawtypes")
private static Class<?> getContainerType(AnnotatedParameterizedType valueExtractorDefinition, Class<? extends ValueExtractor> extractorImplementationType) {
AnnotatedType containerType = valueExtractorDefinition.getAnnotatedActualTypeArguments()[0];
return TypeHelper.getErasedReferenceType( containerType.getType() );
}
private static AnnotatedParameterizedType getValueExtractorDefinition(Class<?> extractorImplementationType) {
List<AnnotatedType> valueExtractorAnnotatedTypes = new ArrayList<>();
determineValueExtractorDefinitions( valueExtractorAnnotatedTypes, extractorImplementationType );
if ( valueExtractorAnnotatedTypes.size() == 1 ) {
return (AnnotatedParameterizedType) valueExtractorAnnotatedTypes.get( 0 );
}
else if ( valueExtractorAnnotatedTypes.size() > 1 ) {
throw LOG.getParallelDefinitionsOfValueExtractorException( extractorImplementationType );
}
else {
throw new AssertionError( extractorImplementationType.getName() + " should be a subclass of " + ValueExtractor.class.getSimpleName() );
}
}
private static void determineValueExtractorDefinitions(List<AnnotatedType> valueExtractorDefinitions, Class<?> extractorImplementationType) {
if ( !ValueExtractor.class.isAssignableFrom( extractorImplementationType ) ) {
return;
}
Class<?> superClass = extractorImplementationType.getSuperclass();
if ( superClass != null && !Object.class.equals( superClass ) ) {
determineValueExtractorDefinitions( valueExtractorDefinitions, superClass );
}
for ( Class<?> implementedInterface : extractorImplementationType.getInterfaces() ) {
if ( !ValueExtractor.class.equals( implementedInterface ) ) {
determineValueExtractorDefinitions( valueExtractorDefinitions, implementedInterface );
}
}
for ( AnnotatedType annotatedInterface : extractorImplementationType.getAnnotatedInterfaces() ) {
if ( ValueExtractor.class.equals( ReflectionHelper.getClassFromType( annotatedInterface.getType() ) ) ) {
valueExtractorDefinitions.add( annotatedInterface );
}
}
}
private static boolean hasUnwrapByDefaultAnnotation(Class<?> extractorImplementationType) {
return extractorImplementationType.isAnnotationPresent( UnwrapByDefault.class );
}
public Key getKey() {
return key;
}
public Class<?> getContainerType() {
return key.containerType;
}
public TypeVariable<?> getExtractedTypeParameter() {
return key.extractedTypeParameter;
}
public Optional<Class<?>> getExtractedType() {
return extractedType;
}
public ValueExtractor<?> getValueExtractor() {
return valueExtractor;
}
public boolean isUnwrapByDefault() {
return unwrapByDefault;
}
@Override
public String toString() {
return "ValueExtractorDescriptor [key=" + key + ", valueExtractor=" + valueExtractor + ", unwrapByDefault=" + unwrapByDefault + "]";
}
public static class Key {
private final Class<?> containerType;
private final TypeVariable<?> extractedTypeParameter;
private final int hashCode;
public Key(Class<?> containerType, TypeVariable<?> extractedTypeParameter) {
this.containerType = containerType;
this.extractedTypeParameter = extractedTypeParameter;
this.hashCode = buildHashCode( containerType, extractedTypeParameter );
}
private static int buildHashCode(Type containerType, TypeVariable<?> extractedTypeParameter) {
final int prime = 31;
int result = 1;
result = prime * result + containerType.hashCode();
result = prime * result + extractedTypeParameter.hashCode();
return result;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Key other = (Key) obj;
return containerType.equals( other.containerType ) &&
extractedTypeParameter.equals( other.extractedTypeParameter );
}
@Override
public String toString() {
return "Key [containerType=" + StringHelper.toShortString( containerType ) + ", extractedTypeParameter=" + extractedTypeParameter + "]";
}
}
}
| {
"content_hash": "5297c296cca47ee5dd95036977103ba5",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 157,
"avg_line_length": 36.6425702811245,
"alnum_prop": 0.7691801841297676,
"repo_name": "shahramgdz/hibernate-validator",
"id": "897de5ec34696cbbf11e05a8f00087b7102bab52",
"size": "9124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/src/main/java/org/hibernate/validator/internal/engine/valueextraction/ValueExtractorDescriptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "3627"
},
{
"name": "HTML",
"bytes": "1378"
},
{
"name": "Java",
"bytes": "3946066"
},
{
"name": "Ruby",
"bytes": "8672"
},
{
"name": "Shell",
"bytes": "476"
}
],
"symlink_target": ""
} |
package roaring
//
// Copyright (c) 2016 by the roaring authors.
// Licensed under the Apache License, Version 2.0.
//
// We derive a few lines of code from the sort.Search
// function in the golang standard library. That function
// is Copyright 2009 The Go Authors, and licensed
// under the following BSD-style license.
import (
"fmt"
"sort"
"unsafe"
)
// runContainer16 does run-length encoding of sets of
// uint16 integers.
type runContainer16 struct {
iv []interval16
}
// interval16 is the internal to runContainer16
// structure that maintains the individual [start, last]
// closed intervals.
type interval16 struct {
start uint16
length uint16 // length minus 1
}
func newInterval16Range(start, last uint16) interval16 {
if last < start {
panic(fmt.Sprintf("last (%d) cannot be smaller than start (%d)", last, start))
}
return interval16{
start,
last - start,
}
}
// runlen returns the count of integers in the interval.
func (iv interval16) runlen() int {
return int(iv.length) + 1
}
func (iv interval16) last() uint16 {
return iv.start + iv.length
}
// String produces a human viewable string of the contents.
func (iv interval16) String() string {
return fmt.Sprintf("[%d, %d]", iv.start, iv.length)
}
func ivalString16(iv []interval16) string {
var s string
var j int
var p interval16
for j, p = range iv {
s += fmt.Sprintf("%v:[%d, %d], ", j, p.start, p.last())
}
return s
}
// String produces a human viewable string of the contents.
func (rc *runContainer16) String() string {
if len(rc.iv) == 0 {
return "runContainer16{}"
}
is := ivalString16(rc.iv)
return `runContainer16{` + is + `}`
}
// uint16Slice is a sort.Sort convenience method
type uint16Slice []uint16
// Len returns the length of p.
func (p uint16Slice) Len() int { return len(p) }
// Less returns p[i] < p[j]
func (p uint16Slice) Less(i, j int) bool { return p[i] < p[j] }
// Swap swaps elements i and j.
func (p uint16Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// addHelper helps build a runContainer16.
type addHelper16 struct {
runstart uint16
runlen uint16
actuallyAdded uint16
m []interval16
rc *runContainer16
}
func (ah *addHelper16) storeIval(runstart, runlen uint16) {
mi := interval16{start: runstart, length: runlen}
ah.m = append(ah.m, mi)
}
func (ah *addHelper16) add(cur, prev uint16, i int) {
if cur == prev+1 {
ah.runlen++
ah.actuallyAdded++
} else {
if cur < prev {
panic(fmt.Sprintf("newRunContainer16FromVals sees "+
"unsorted vals; vals[%v]=cur=%v < prev=%v. Sort your vals"+
" before calling us with alreadySorted == true.", i, cur, prev))
}
if cur == prev {
// ignore duplicates
} else {
ah.actuallyAdded++
ah.storeIval(ah.runstart, ah.runlen)
ah.runstart = cur
ah.runlen = 0
}
}
}
// newRunContainerRange makes a new container made of just the specified closed interval [rangestart,rangelast]
func newRunContainer16Range(rangestart uint16, rangelast uint16) *runContainer16 {
rc := &runContainer16{}
rc.iv = append(rc.iv, newInterval16Range(rangestart, rangelast))
return rc
}
// newRunContainer16FromVals makes a new container from vals.
//
// For efficiency, vals should be sorted in ascending order.
// Ideally vals should not contain duplicates, but we detect and
// ignore them. If vals is already sorted in ascending order, then
// pass alreadySorted = true. Otherwise, for !alreadySorted,
// we will sort vals before creating a runContainer16 of them.
// We sort the original vals, so this will change what the
// caller sees in vals as a side effect.
func newRunContainer16FromVals(alreadySorted bool, vals ...uint16) *runContainer16 {
// keep this in sync with newRunContainer16FromArray below
rc := &runContainer16{}
ah := addHelper16{rc: rc}
if !alreadySorted {
sort.Sort(uint16Slice(vals))
}
n := len(vals)
var cur, prev uint16
switch {
case n == 0:
// nothing more
case n == 1:
ah.m = append(ah.m, newInterval16Range(vals[0], vals[0]))
ah.actuallyAdded++
default:
ah.runstart = vals[0]
ah.actuallyAdded++
for i := 1; i < n; i++ {
prev = vals[i-1]
cur = vals[i]
ah.add(cur, prev, i)
}
ah.storeIval(ah.runstart, ah.runlen)
}
rc.iv = ah.m
return rc
}
// newRunContainer16FromBitmapContainer makes a new run container from bc,
// somewhat efficiently. For reference, see the Java
// https://github.com/RoaringBitmap/RoaringBitmap/blob/master/src/main/java/org/roaringbitmap/RunContainer.java#L145-L192
func newRunContainer16FromBitmapContainer(bc *bitmapContainer) *runContainer16 {
rc := &runContainer16{}
nbrRuns := bc.numberOfRuns()
if nbrRuns == 0 {
return rc
}
rc.iv = make([]interval16, nbrRuns)
longCtr := 0 // index of current long in bitmap
curWord := bc.bitmap[0] // its value
runCount := 0
for {
// potentially multiword advance to first 1 bit
for curWord == 0 && longCtr < len(bc.bitmap)-1 {
longCtr++
curWord = bc.bitmap[longCtr]
}
if curWord == 0 {
// wrap up, no more runs
return rc
}
localRunStart := countTrailingZeros(curWord)
runStart := localRunStart + 64*longCtr
// stuff 1s into number's LSBs
curWordWith1s := curWord | (curWord - 1)
// find the next 0, potentially in a later word
runEnd := 0
for curWordWith1s == maxWord && longCtr < len(bc.bitmap)-1 {
longCtr++
curWordWith1s = bc.bitmap[longCtr]
}
if curWordWith1s == maxWord {
// a final unterminated run of 1s
runEnd = wordSizeInBits + longCtr*64
rc.iv[runCount].start = uint16(runStart)
rc.iv[runCount].length = uint16(runEnd) - uint16(runStart) - 1
return rc
}
localRunEnd := countTrailingZeros(^curWordWith1s)
runEnd = localRunEnd + longCtr*64
rc.iv[runCount].start = uint16(runStart)
rc.iv[runCount].length = uint16(runEnd) - 1 - uint16(runStart)
runCount++
// now, zero out everything right of runEnd.
curWord = curWordWith1s & (curWordWith1s + 1)
// We've lathered and rinsed, so repeat...
}
}
//
// newRunContainer16FromArray populates a new
// runContainer16 from the contents of arr.
//
func newRunContainer16FromArray(arr *arrayContainer) *runContainer16 {
// keep this in sync with newRunContainer16FromVals above
rc := &runContainer16{}
ah := addHelper16{rc: rc}
n := arr.getCardinality()
var cur, prev uint16
switch {
case n == 0:
// nothing more
case n == 1:
ah.m = append(ah.m, newInterval16Range(arr.content[0], arr.content[0]))
ah.actuallyAdded++
default:
ah.runstart = arr.content[0]
ah.actuallyAdded++
for i := 1; i < n; i++ {
prev = arr.content[i-1]
cur = arr.content[i]
ah.add(cur, prev, i)
}
ah.storeIval(ah.runstart, ah.runlen)
}
rc.iv = ah.m
return rc
}
// set adds the integers in vals to the set. Vals
// must be sorted in increasing order; if not, you should set
// alreadySorted to false, and we will sort them in place for you.
// (Be aware of this side effect -- it will affect the callers
// view of vals).
//
// If you have a small number of additions to an already
// big runContainer16, calling Add() may be faster.
func (rc *runContainer16) set(alreadySorted bool, vals ...uint16) {
rc2 := newRunContainer16FromVals(alreadySorted, vals...)
un := rc.union(rc2)
rc.iv = un.iv
}
// canMerge returns true iff the intervals
// a and b either overlap or they are
// contiguous and so can be merged into
// a single interval.
func canMerge16(a, b interval16) bool {
if int(a.last())+1 < int(b.start) {
return false
}
return int(b.last())+1 >= int(a.start)
}
// haveOverlap differs from canMerge in that
// it tells you if the intersection of a
// and b would contain an element (otherwise
// it would be the empty set, and we return
// false).
func haveOverlap16(a, b interval16) bool {
if int(a.last())+1 <= int(b.start) {
return false
}
return int(b.last())+1 > int(a.start)
}
// mergeInterval16s joins a and b into a
// new interval, and panics if it cannot.
func mergeInterval16s(a, b interval16) (res interval16) {
if !canMerge16(a, b) {
panic(fmt.Sprintf("cannot merge %#v and %#v", a, b))
}
if b.start < a.start {
res.start = b.start
} else {
res.start = a.start
}
if b.last() > a.last() {
res.length = b.last() - res.start
} else {
res.length = a.last() - res.start
}
return
}
// intersectInterval16s returns the intersection
// of a and b. The isEmpty flag will be true if
// a and b were disjoint.
func intersectInterval16s(a, b interval16) (res interval16, isEmpty bool) {
if !haveOverlap16(a, b) {
isEmpty = true
return
}
if b.start > a.start {
res.start = b.start
} else {
res.start = a.start
}
bEnd := b.last()
aEnd := a.last()
var resEnd uint16
if bEnd < aEnd {
resEnd = bEnd
} else {
resEnd = aEnd
}
res.length = resEnd - res.start
return
}
// union merges two runContainer16s, producing
// a new runContainer16 with the union of rc and b.
func (rc *runContainer16) union(b *runContainer16) *runContainer16 {
// rc is also known as 'a' here, but golint insisted we
// call it rc for consistency with the rest of the methods.
var m []interval16
alim := int(len(rc.iv))
blim := int(len(b.iv))
var na int // next from a
var nb int // next from b
// merged holds the current merge output, which might
// get additional merges before being appended to m.
var merged interval16
var mergedUsed bool // is merged being used at the moment?
var cura interval16 // currently considering this interval16 from a
var curb interval16 // currently considering this interval16 from b
pass := 0
for na < alim && nb < blim {
pass++
cura = rc.iv[na]
curb = b.iv[nb]
if mergedUsed {
mergedUpdated := false
if canMerge16(cura, merged) {
merged = mergeInterval16s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
mergedUpdated = true
}
if canMerge16(curb, merged) {
merged = mergeInterval16s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
mergedUpdated = true
}
if !mergedUpdated {
// we know that merged is disjoint from cura and curb
m = append(m, merged)
mergedUsed = false
}
continue
} else {
// !mergedUsed
if !canMerge16(cura, curb) {
if cura.start < curb.start {
m = append(m, cura)
na++
} else {
m = append(m, curb)
nb++
}
} else {
merged = mergeInterval16s(cura, curb)
mergedUsed = true
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
}
}
}
var aDone, bDone bool
if na >= alim {
aDone = true
}
if nb >= blim {
bDone = true
}
// finish by merging anything remaining into merged we can:
if mergedUsed {
if !aDone {
aAdds:
for na < alim {
cura = rc.iv[na]
if canMerge16(cura, merged) {
merged = mergeInterval16s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
} else {
break aAdds
}
}
}
if !bDone {
bAdds:
for nb < blim {
curb = b.iv[nb]
if canMerge16(curb, merged) {
merged = mergeInterval16s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
} else {
break bAdds
}
}
}
m = append(m, merged)
}
if na < alim {
m = append(m, rc.iv[na:]...)
}
if nb < blim {
m = append(m, b.iv[nb:]...)
}
res := &runContainer16{iv: m}
return res
}
// unionCardinality returns the cardinality of the merger of two runContainer16s, the union of rc and b.
func (rc *runContainer16) unionCardinality(b *runContainer16) uint {
// rc is also known as 'a' here, but golint insisted we
// call it rc for consistency with the rest of the methods.
answer := uint(0)
alim := int(len(rc.iv))
blim := int(len(b.iv))
var na int // next from a
var nb int // next from b
// merged holds the current merge output, which might
// get additional merges before being appended to m.
var merged interval16
var mergedUsed bool // is merged being used at the moment?
var cura interval16 // currently considering this interval16 from a
var curb interval16 // currently considering this interval16 from b
pass := 0
for na < alim && nb < blim {
pass++
cura = rc.iv[na]
curb = b.iv[nb]
if mergedUsed {
mergedUpdated := false
if canMerge16(cura, merged) {
merged = mergeInterval16s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
mergedUpdated = true
}
if canMerge16(curb, merged) {
merged = mergeInterval16s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
mergedUpdated = true
}
if !mergedUpdated {
// we know that merged is disjoint from cura and curb
//m = append(m, merged)
answer += uint(merged.last()) - uint(merged.start) + 1
mergedUsed = false
}
continue
} else {
// !mergedUsed
if !canMerge16(cura, curb) {
if cura.start < curb.start {
answer += uint(cura.last()) - uint(cura.start) + 1
//m = append(m, cura)
na++
} else {
answer += uint(curb.last()) - uint(curb.start) + 1
//m = append(m, curb)
nb++
}
} else {
merged = mergeInterval16s(cura, curb)
mergedUsed = true
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
}
}
}
var aDone, bDone bool
if na >= alim {
aDone = true
}
if nb >= blim {
bDone = true
}
// finish by merging anything remaining into merged we can:
if mergedUsed {
if !aDone {
aAdds:
for na < alim {
cura = rc.iv[na]
if canMerge16(cura, merged) {
merged = mergeInterval16s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int(merged.last())+1, na+1)
} else {
break aAdds
}
}
}
if !bDone {
bAdds:
for nb < blim {
curb = b.iv[nb]
if canMerge16(curb, merged) {
merged = mergeInterval16s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int(merged.last())+1, nb+1)
} else {
break bAdds
}
}
}
//m = append(m, merged)
answer += uint(merged.last()) - uint(merged.start) + 1
}
for _, r := range rc.iv[na:] {
answer += uint(r.last()) - uint(r.start) + 1
}
for _, r := range b.iv[nb:] {
answer += uint(r.last()) - uint(r.start) + 1
}
return answer
}
// indexOfIntervalAtOrAfter is a helper for union.
func (rc *runContainer16) indexOfIntervalAtOrAfter(key int, startIndex int) int {
w, already, _ := rc.searchRange(key, startIndex, 0)
if already {
return w
}
return w + 1
}
// intersect returns a new runContainer16 holding the
// intersection of rc (also known as 'a') and b.
func (rc *runContainer16) intersect(b *runContainer16) *runContainer16 {
a := rc
numa := int(len(a.iv))
numb := int(len(b.iv))
res := &runContainer16{}
if numa == 0 || numb == 0 {
return res
}
if numa == 1 && numb == 1 {
if !haveOverlap16(a.iv[0], b.iv[0]) {
return res
}
}
var output []interval16
var acuri int
var bcuri int
astart := int(a.iv[acuri].start)
bstart := int(b.iv[bcuri].start)
var intersection interval16
var leftoverstart int
var isOverlap, isLeftoverA, isLeftoverB bool
var done bool
toploop:
for acuri < numa && bcuri < numb {
isOverlap, isLeftoverA, isLeftoverB, leftoverstart, intersection =
intersectWithLeftover16(astart, int(a.iv[acuri].last()), bstart, int(b.iv[bcuri].last()))
if !isOverlap {
switch {
case astart < bstart:
acuri, done = a.findNextIntervalThatIntersectsStartingFrom(acuri+1, bstart)
if done {
break toploop
}
astart = int(a.iv[acuri].start)
case astart > bstart:
bcuri, done = b.findNextIntervalThatIntersectsStartingFrom(bcuri+1, astart)
if done {
break toploop
}
bstart = int(b.iv[bcuri].start)
}
} else {
// isOverlap
output = append(output, intersection)
switch {
case isLeftoverA:
// note that we change astart without advancing acuri,
// since we need to capture any 2ndary intersections with a.iv[acuri]
astart = leftoverstart
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int(b.iv[bcuri].start)
case isLeftoverB:
// note that we change bstart without advancing bcuri,
// since we need to capture any 2ndary intersections with b.iv[bcuri]
bstart = leftoverstart
acuri++
if acuri >= numa {
break toploop
}
astart = int(a.iv[acuri].start)
default:
// neither had leftover, both completely consumed
// advance to next a interval
acuri++
if acuri >= numa {
break toploop
}
astart = int(a.iv[acuri].start)
// advance to next b interval
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int(b.iv[bcuri].start)
}
}
} // end for toploop
if len(output) == 0 {
return res
}
res.iv = output
return res
}
// intersectCardinality returns the cardinality of the
// intersection of rc (also known as 'a') and b.
func (rc *runContainer16) intersectCardinality(b *runContainer16) int {
answer := int(0)
a := rc
numa := int(len(a.iv))
numb := int(len(b.iv))
if numa == 0 || numb == 0 {
return 0
}
if numa == 1 && numb == 1 {
if !haveOverlap16(a.iv[0], b.iv[0]) {
return 0
}
}
var acuri int
var bcuri int
astart := int(a.iv[acuri].start)
bstart := int(b.iv[bcuri].start)
var intersection interval16
var leftoverstart int
var isOverlap, isLeftoverA, isLeftoverB bool
var done bool
pass := 0
toploop:
for acuri < numa && bcuri < numb {
pass++
isOverlap, isLeftoverA, isLeftoverB, leftoverstart, intersection =
intersectWithLeftover16(astart, int(a.iv[acuri].last()), bstart, int(b.iv[bcuri].last()))
if !isOverlap {
switch {
case astart < bstart:
acuri, done = a.findNextIntervalThatIntersectsStartingFrom(acuri+1, bstart)
if done {
break toploop
}
astart = int(a.iv[acuri].start)
case astart > bstart:
bcuri, done = b.findNextIntervalThatIntersectsStartingFrom(bcuri+1, astart)
if done {
break toploop
}
bstart = int(b.iv[bcuri].start)
}
} else {
// isOverlap
answer += int(intersection.last()) - int(intersection.start) + 1
switch {
case isLeftoverA:
// note that we change astart without advancing acuri,
// since we need to capture any 2ndary intersections with a.iv[acuri]
astart = leftoverstart
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int(b.iv[bcuri].start)
case isLeftoverB:
// note that we change bstart without advancing bcuri,
// since we need to capture any 2ndary intersections with b.iv[bcuri]
bstart = leftoverstart
acuri++
if acuri >= numa {
break toploop
}
astart = int(a.iv[acuri].start)
default:
// neither had leftover, both completely consumed
// advance to next a interval
acuri++
if acuri >= numa {
break toploop
}
astart = int(a.iv[acuri].start)
// advance to next b interval
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int(b.iv[bcuri].start)
}
}
} // end for toploop
return answer
}
// get returns true iff key is in the container.
func (rc *runContainer16) contains(key uint16) bool {
_, in, _ := rc.search(int(key))
return in
}
// numIntervals returns the count of intervals in the container.
func (rc *runContainer16) numIntervals() int {
return len(rc.iv)
}
// searchRange returns alreadyPresent to indicate if the
// key is already in one of our interval16s.
//
// If key is alreadyPresent, then whichInterval16 tells
// you where.
//
// If key is not already present, then whichInterval16 is
// set as follows:
//
// a) whichInterval16 == len(rc.iv)-1 if key is beyond our
// last interval16 in rc.iv;
//
// b) whichInterval16 == -1 if key is before our first
// interval16 in rc.iv;
//
// c) whichInterval16 is set to the minimum index of rc.iv
// which comes strictly before the key;
// so rc.iv[whichInterval16].last < key,
// and if whichInterval16+1 exists, then key < rc.iv[whichInterval16+1].start
// (Note that whichInterval16+1 won't exist when
// whichInterval16 is the last interval.)
//
// runContainer16.search always returns whichInterval16 < len(rc.iv).
//
// The search space is from startIndex to endxIndex. If endxIndex is set to zero, then there
// no upper bound.
//
func (rc *runContainer16) searchRange(key int, startIndex int, endxIndex int) (whichInterval16 int, alreadyPresent bool, numCompares int) {
n := int(len(rc.iv))
if n == 0 {
return -1, false, 0
}
if endxIndex == 0 {
endxIndex = n
}
// sort.Search returns the smallest index i
// in [0, n) at which f(i) is true, assuming that on the range [0, n),
// f(i) == true implies f(i+1) == true.
// If there is no such index, Search returns n.
// For correctness, this began as verbatim snippet from
// sort.Search in the Go standard lib.
// We inline our comparison function for speed, and
// annotate with numCompares
// to observe and test that extra bounds are utilized.
i, j := startIndex, endxIndex
for i < j {
h := i + (j-i)/2 // avoid overflow when computing h as the bisector
// i <= h < j
numCompares++
if !(key < int(rc.iv[h].start)) {
i = h + 1
} else {
j = h
}
}
below := i
// end std lib snippet.
// The above is a simple in-lining and annotation of:
/* below := sort.Search(n,
func(i int) bool {
return key < rc.iv[i].start
})
*/
whichInterval16 = below - 1
if below == n {
// all falses => key is >= start of all interval16s
// ... so does it belong to the last interval16?
if key < int(rc.iv[n-1].last())+1 {
// yes, it belongs to the last interval16
alreadyPresent = true
return
}
// no, it is beyond the last interval16.
// leave alreadyPreset = false
return
}
// INVAR: key is below rc.iv[below]
if below == 0 {
// key is before the first first interval16.
// leave alreadyPresent = false
return
}
// INVAR: key is >= rc.iv[below-1].start and
// key is < rc.iv[below].start
// is key in below-1 interval16?
if key >= int(rc.iv[below-1].start) && key < int(rc.iv[below-1].last())+1 {
// yes, it is. key is in below-1 interval16.
alreadyPresent = true
return
}
// INVAR: key >= rc.iv[below-1].endx && key < rc.iv[below].start
// leave alreadyPresent = false
return
}
// search returns alreadyPresent to indicate if the
// key is already in one of our interval16s.
//
// If key is alreadyPresent, then whichInterval16 tells
// you where.
//
// If key is not already present, then whichInterval16 is
// set as follows:
//
// a) whichInterval16 == len(rc.iv)-1 if key is beyond our
// last interval16 in rc.iv;
//
// b) whichInterval16 == -1 if key is before our first
// interval16 in rc.iv;
//
// c) whichInterval16 is set to the minimum index of rc.iv
// which comes strictly before the key;
// so rc.iv[whichInterval16].last < key,
// and if whichInterval16+1 exists, then key < rc.iv[whichInterval16+1].start
// (Note that whichInterval16+1 won't exist when
// whichInterval16 is the last interval.)
//
// runContainer16.search always returns whichInterval16 < len(rc.iv).
//
func (rc *runContainer16) search(key int) (whichInterval16 int, alreadyPresent bool, numCompares int) {
return rc.searchRange(key, 0, 0)
}
// getCardinality returns the count of the integers stored in the
// runContainer16. The running complexity depends on the size
// of the container.
func (rc *runContainer16) getCardinality() int {
// have to compute it
n := 0
for _, p := range rc.iv {
n += p.runlen()
}
return n
}
// isEmpty returns true if the container is empty.
// It runs in constant time.
func (rc *runContainer16) isEmpty() bool {
return len(rc.iv) == 0
}
// AsSlice decompresses the contents into a []uint16 slice.
func (rc *runContainer16) AsSlice() []uint16 {
s := make([]uint16, rc.getCardinality())
j := 0
for _, p := range rc.iv {
for i := p.start; i <= p.last(); i++ {
s[j] = i
j++
}
}
return s
}
// newRunContainer16 creates an empty run container.
func newRunContainer16() *runContainer16 {
return &runContainer16{}
}
// newRunContainer16CopyIv creates a run container, initializing
// with a copy of the supplied iv slice.
//
func newRunContainer16CopyIv(iv []interval16) *runContainer16 {
rc := &runContainer16{
iv: make([]interval16, len(iv)),
}
copy(rc.iv, iv)
return rc
}
func (rc *runContainer16) Clone() *runContainer16 {
rc2 := newRunContainer16CopyIv(rc.iv)
return rc2
}
// newRunContainer16TakeOwnership returns a new runContainer16
// backed by the provided iv slice, which we will
// assume exclusive control over from now on.
//
func newRunContainer16TakeOwnership(iv []interval16) *runContainer16 {
rc := &runContainer16{
iv: iv,
}
return rc
}
const baseRc16Size = int(unsafe.Sizeof(runContainer16{}))
const perIntervalRc16Size = int(unsafe.Sizeof(interval16{}))
const baseDiskRc16Size = int(unsafe.Sizeof(uint16(0)))
// see also runContainer16SerializedSizeInBytes(numRuns int) int
// getSizeInBytes returns the number of bytes of memory
// required by this runContainer16.
func (rc *runContainer16) getSizeInBytes() int {
return perIntervalRc16Size*len(rc.iv) + baseRc16Size
}
// runContainer16SerializedSizeInBytes returns the number of bytes of disk
// required to hold numRuns in a runContainer16.
func runContainer16SerializedSizeInBytes(numRuns int) int {
return perIntervalRc16Size*numRuns + baseDiskRc16Size
}
// Add adds a single value k to the set.
func (rc *runContainer16) Add(k uint16) (wasNew bool) {
// TODO comment from runContainer16.java:
// it might be better and simpler to do return
// toBitmapOrArrayContainer(getCardinality()).add(k)
// but note that some unit tests use this method to build up test
// runcontainers without calling runOptimize
k64 := int(k)
index, present, _ := rc.search(k64)
if present {
return // already there
}
wasNew = true
n := int(len(rc.iv))
if index == -1 {
// we may need to extend the first run
if n > 0 {
if rc.iv[0].start == k+1 {
rc.iv[0].start = k
rc.iv[0].length++
return
}
}
// nope, k stands alone, starting the new first interval16.
rc.iv = append([]interval16{newInterval16Range(k, k)}, rc.iv...)
return
}
// are we off the end? handle both index == n and index == n-1:
if index >= n-1 {
if int(rc.iv[n-1].last())+1 == k64 {
rc.iv[n-1].length++
return
}
rc.iv = append(rc.iv, newInterval16Range(k, k))
return
}
// INVAR: index and index+1 both exist, and k goes between them.
//
// Now: add k into the middle,
// possibly fusing with index or index+1 interval16
// and possibly resulting in fusing of two interval16s
// that had a one integer gap.
left := index
right := index + 1
// are we fusing left and right by adding k?
if int(rc.iv[left].last())+1 == k64 && int(rc.iv[right].start) == k64+1 {
// fuse into left
rc.iv[left].length = rc.iv[right].last() - rc.iv[left].start
// remove redundant right
rc.iv = append(rc.iv[:left+1], rc.iv[right+1:]...)
return
}
// are we an addition to left?
if int(rc.iv[left].last())+1 == k64 {
// yes
rc.iv[left].length++
return
}
// are we an addition to right?
if int(rc.iv[right].start) == k64+1 {
// yes
rc.iv[right].start = k
rc.iv[right].length++
return
}
// k makes a standalone new interval16, inserted in the middle
tail := append([]interval16{newInterval16Range(k, k)}, rc.iv[right:]...)
rc.iv = append(rc.iv[:left+1], tail...)
return
}
// runIterator16 advice: you must call hasNext()
// before calling next()/peekNext() to insure there are contents.
type runIterator16 struct {
rc *runContainer16
curIndex int
curPosInIndex uint16
}
// newRunIterator16 returns a new empty run container.
func (rc *runContainer16) newRunIterator16() *runIterator16 {
return &runIterator16{rc: rc, curIndex: 0, curPosInIndex: 0}
}
func (rc *runContainer16) iterate(cb func(x uint16) bool) bool {
iterator := runIterator16{rc, 0, 0}
for iterator.hasNext() {
if !cb(iterator.next()) {
return false
}
}
return true
}
// hasNext returns false if calling next will panic. It
// returns true when there is at least one more value
// available in the iteration sequence.
func (ri *runIterator16) hasNext() bool {
return int(len(ri.rc.iv)) > ri.curIndex+1 ||
(int(len(ri.rc.iv)) == ri.curIndex+1 && ri.rc.iv[ri.curIndex].length >= ri.curPosInIndex)
}
// next returns the next value in the iteration sequence.
func (ri *runIterator16) next() uint16 {
next := ri.rc.iv[ri.curIndex].start + ri.curPosInIndex
if ri.curPosInIndex == ri.rc.iv[ri.curIndex].length {
ri.curPosInIndex = 0
ri.curIndex++
} else {
ri.curPosInIndex++
}
return next
}
// peekNext returns the next value in the iteration sequence without advancing the iterator
func (ri *runIterator16) peekNext() uint16 {
return ri.rc.iv[ri.curIndex].start + ri.curPosInIndex
}
// advanceIfNeeded advances as long as the next value is smaller than minval
func (ri *runIterator16) advanceIfNeeded(minval uint16) {
if !ri.hasNext() || ri.peekNext() >= minval {
return
}
// interval cannot be -1 because of minval > peekNext
interval, isPresent, _ := ri.rc.searchRange(int(minval), ri.curIndex, int(len(ri.rc.iv)))
// if the minval is present, set the curPosIndex at the right position
if isPresent {
ri.curIndex = interval
ri.curPosInIndex = minval - ri.rc.iv[ri.curIndex].start
} else {
// otherwise interval is set to to the minimum index of rc.iv
// which comes strictly before the key, that's why we set the next interval
ri.curIndex = interval + 1
ri.curPosInIndex = 0
}
}
// runReverseIterator16 advice: you must call hasNext()
// before calling next() to insure there are contents.
type runReverseIterator16 struct {
rc *runContainer16
curIndex int // index into rc.iv
curPosInIndex uint16 // offset in rc.iv[curIndex]
}
// newRunReverseIterator16 returns a new empty run iterator.
func (rc *runContainer16) newRunReverseIterator16() *runReverseIterator16 {
index := int(len(rc.iv)) - 1
pos := uint16(0)
if index >= 0 {
pos = rc.iv[index].length
}
return &runReverseIterator16{
rc: rc,
curIndex: index,
curPosInIndex: pos,
}
}
// hasNext returns false if calling next will panic. It
// returns true when there is at least one more value
// available in the iteration sequence.
func (ri *runReverseIterator16) hasNext() bool {
return ri.curIndex > 0 || ri.curIndex == 0 && ri.curPosInIndex >= 0
}
// next returns the next value in the iteration sequence.
func (ri *runReverseIterator16) next() uint16 {
next := ri.rc.iv[ri.curIndex].start + ri.curPosInIndex
if ri.curPosInIndex > 0 {
ri.curPosInIndex--
} else {
ri.curIndex--
if ri.curIndex >= 0 {
ri.curPosInIndex = ri.rc.iv[ri.curIndex].length
}
}
return next
}
func (rc *runContainer16) newManyRunIterator16() *runIterator16 {
return rc.newRunIterator16()
}
// hs are the high bits to include to avoid needing to reiterate over the buffer in NextMany
func (ri *runIterator16) nextMany(hs uint32, buf []uint32) int {
n := 0
if !ri.hasNext() {
return n
}
// start and end are inclusive
for n < len(buf) {
moreVals := 0
if ri.rc.iv[ri.curIndex].length >= ri.curPosInIndex {
// add as many as you can from this seq
moreVals = minOfInt(int(ri.rc.iv[ri.curIndex].length-ri.curPosInIndex)+1, len(buf)-n)
base := uint32(ri.rc.iv[ri.curIndex].start+ri.curPosInIndex) | hs
// allows BCE
buf2 := buf[n : n+moreVals]
for i := range buf2 {
buf2[i] = base + uint32(i)
}
// update values
n += moreVals
}
if moreVals+int(ri.curPosInIndex) > int(ri.rc.iv[ri.curIndex].length) {
ri.curPosInIndex = 0
ri.curIndex++
if ri.curIndex == int(len(ri.rc.iv)) {
break
}
} else {
ri.curPosInIndex += uint16(moreVals) //moreVals always fits in uint16
}
}
return n
}
func (ri *runIterator16) nextMany64(hs uint64, buf []uint64) int {
n := 0
if !ri.hasNext() {
return n
}
// start and end are inclusive
for n < len(buf) {
moreVals := 0
if ri.rc.iv[ri.curIndex].length >= ri.curPosInIndex {
// add as many as you can from this seq
moreVals = minOfInt(int(ri.rc.iv[ri.curIndex].length-ri.curPosInIndex)+1, len(buf)-n)
base := uint64(ri.rc.iv[ri.curIndex].start+ri.curPosInIndex) | hs
// allows BCE
buf2 := buf[n : n+moreVals]
for i := range buf2 {
buf2[i] = base + uint64(i)
}
// update values
n += moreVals
}
if moreVals+int(ri.curPosInIndex) > int(ri.rc.iv[ri.curIndex].length) {
ri.curPosInIndex = 0
ri.curIndex++
if ri.curIndex == int(len(ri.rc.iv)) {
break
}
} else {
ri.curPosInIndex += uint16(moreVals) //moreVals always fits in uint16
}
}
return n
}
// remove removes key from the container.
func (rc *runContainer16) removeKey(key uint16) (wasPresent bool) {
var index int
index, wasPresent, _ = rc.search(int(key))
if !wasPresent {
return // already removed, nothing to do.
}
pos := key - rc.iv[index].start
rc.deleteAt(&index, &pos)
return
}
// internal helper functions
func (rc *runContainer16) deleteAt(curIndex *int, curPosInIndex *uint16) {
ci := *curIndex
pos := *curPosInIndex
// are we first, last, or in the middle of our interval16?
switch {
case pos == 0:
if int(rc.iv[ci].length) == 0 {
// our interval disappears
rc.iv = append(rc.iv[:ci], rc.iv[ci+1:]...)
// curIndex stays the same, since the delete did
// the advance for us.
*curPosInIndex = 0
} else {
rc.iv[ci].start++ // no longer overflowable
rc.iv[ci].length--
}
case pos == rc.iv[ci].length:
// length
rc.iv[ci].length--
// our interval16 cannot disappear, else we would have been pos == 0, case first above.
*curPosInIndex--
// if we leave *curIndex alone, then Next() will work properly even after the delete.
default:
//middle
// split into two, adding an interval16
new0 := newInterval16Range(rc.iv[ci].start, rc.iv[ci].start+*curPosInIndex-1)
new1start := int(rc.iv[ci].start+*curPosInIndex) + 1
if new1start > int(MaxUint16) {
panic("overflow?!?!")
}
new1 := newInterval16Range(uint16(new1start), rc.iv[ci].last())
tail := append([]interval16{new0, new1}, rc.iv[ci+1:]...)
rc.iv = append(rc.iv[:ci], tail...)
// update curIndex and curPosInIndex
*curIndex++
*curPosInIndex = 0
}
}
func have4Overlap16(astart, alast, bstart, blast int) bool {
if alast+1 <= bstart {
return false
}
return blast+1 > astart
}
func intersectWithLeftover16(astart, alast, bstart, blast int) (isOverlap, isLeftoverA, isLeftoverB bool, leftoverstart int, intersection interval16) {
if !have4Overlap16(astart, alast, bstart, blast) {
return
}
isOverlap = true
// do the intersection:
if bstart > astart {
intersection.start = uint16(bstart)
} else {
intersection.start = uint16(astart)
}
switch {
case blast < alast:
isLeftoverA = true
leftoverstart = blast + 1
intersection.length = uint16(blast) - intersection.start
case alast < blast:
isLeftoverB = true
leftoverstart = alast + 1
intersection.length = uint16(alast) - intersection.start
default:
// alast == blast
intersection.length = uint16(alast) - intersection.start
}
return
}
func (rc *runContainer16) findNextIntervalThatIntersectsStartingFrom(startIndex int, key int) (index int, done bool) {
w, _, _ := rc.searchRange(key, startIndex, 0)
// rc.search always returns w < len(rc.iv)
if w < startIndex {
// not found and comes before lower bound startIndex,
// so just use the lower bound.
if startIndex == int(len(rc.iv)) {
// also this bump up means that we are done
return startIndex, true
}
return startIndex, false
}
return w, false
}
func sliceToString16(m []interval16) string {
s := ""
for i := range m {
s += fmt.Sprintf("%v: %s, ", i, m[i])
}
return s
}
// helper for invert
func (rc *runContainer16) invertlastInterval(origin uint16, lastIdx int) []interval16 {
cur := rc.iv[lastIdx]
if cur.last() == MaxUint16 {
if cur.start == origin {
return nil // empty container
}
return []interval16{newInterval16Range(origin, cur.start-1)}
}
if cur.start == origin {
return []interval16{newInterval16Range(cur.last()+1, MaxUint16)}
}
// invert splits
return []interval16{
newInterval16Range(origin, cur.start-1),
newInterval16Range(cur.last()+1, MaxUint16),
}
}
// invert returns a new container (not inplace), that is
// the inversion of rc. For each bit b in rc, the
// returned value has !b
func (rc *runContainer16) invert() *runContainer16 {
ni := len(rc.iv)
var m []interval16
switch ni {
case 0:
return &runContainer16{iv: []interval16{newInterval16Range(0, MaxUint16)}}
case 1:
return &runContainer16{iv: rc.invertlastInterval(0, 0)}
}
var invstart int
ult := ni - 1
for i, cur := range rc.iv {
if i == ult {
// invertlastInteval will add both intervals (b) and (c) in
// diagram below.
m = append(m, rc.invertlastInterval(uint16(invstart), i)...)
break
}
// INVAR: i and cur are not the last interval, there is a next at i+1
//
// ........[cur.start, cur.last] ...... [next.start, next.last]....
// ^ ^ ^
// (a) (b) (c)
//
// Now: we add interval (a); but if (a) is empty, for cur.start==0, we skip it.
if cur.start > 0 {
m = append(m, newInterval16Range(uint16(invstart), cur.start-1))
}
invstart = int(cur.last() + 1)
}
return &runContainer16{iv: m}
}
func (iv interval16) equal(b interval16) bool {
return iv.start == b.start && iv.length == b.length
}
func (iv interval16) isSuperSetOf(b interval16) bool {
return iv.start <= b.start && b.last() <= iv.last()
}
func (iv interval16) subtractInterval(del interval16) (left []interval16, delcount int) {
isect, isEmpty := intersectInterval16s(iv, del)
if isEmpty {
return nil, 0
}
if del.isSuperSetOf(iv) {
return nil, iv.runlen()
}
switch {
case isect.start > iv.start && isect.last() < iv.last():
new0 := newInterval16Range(iv.start, isect.start-1)
new1 := newInterval16Range(isect.last()+1, iv.last())
return []interval16{new0, new1}, isect.runlen()
case isect.start == iv.start:
return []interval16{newInterval16Range(isect.last()+1, iv.last())}, isect.runlen()
default:
return []interval16{newInterval16Range(iv.start, isect.start-1)}, isect.runlen()
}
}
func (rc *runContainer16) isubtract(del interval16) {
origiv := make([]interval16, len(rc.iv))
copy(origiv, rc.iv)
n := int(len(rc.iv))
if n == 0 {
return // already done.
}
_, isEmpty := intersectInterval16s(newInterval16Range(rc.iv[0].start, rc.iv[n-1].last()), del)
if isEmpty {
return // done
}
// INVAR there is some intersection between rc and del
istart, startAlready, _ := rc.search(int(del.start))
ilast, lastAlready, _ := rc.search(int(del.last()))
if istart == -1 {
if ilast == n-1 && !lastAlready {
rc.iv = nil
return
}
}
// some intervals will remain
switch {
case startAlready && lastAlready:
res0, _ := rc.iv[istart].subtractInterval(del)
// would overwrite values in iv b/c res0 can have len 2. so
// write to origiv instead.
lost := 1 + ilast - istart
changeSize := int(len(res0)) - lost
newSize := int(len(rc.iv)) + changeSize
// rc.iv = append(pre, caboose...)
// return
if ilast != istart {
res1, _ := rc.iv[ilast].subtractInterval(del)
res0 = append(res0, res1...)
changeSize = int(len(res0)) - lost
newSize = int(len(rc.iv)) + changeSize
}
switch {
case changeSize < 0:
// shrink
copy(rc.iv[istart+int(len(res0)):], rc.iv[ilast+1:])
copy(rc.iv[istart:istart+int(len(res0))], res0)
rc.iv = rc.iv[:newSize]
return
case changeSize == 0:
// stay the same
copy(rc.iv[istart:istart+int(len(res0))], res0)
return
default:
// changeSize > 0 is only possible when ilast == istart.
// Hence we now know: changeSize == 1 and len(res0) == 2
rc.iv = append(rc.iv, interval16{})
// len(rc.iv) is correct now, no need to rc.iv = rc.iv[:newSize]
// copy the tail into place
copy(rc.iv[ilast+2:], rc.iv[ilast+1:])
// copy the new item(s) into place
copy(rc.iv[istart:istart+2], res0)
return
}
case !startAlready && !lastAlready:
// we get to discard whole intervals
// from the search() definition:
// if del.start is not present, then istart is
// set as follows:
//
// a) istart == n-1 if del.start is beyond our
// last interval16 in rc.iv;
//
// b) istart == -1 if del.start is before our first
// interval16 in rc.iv;
//
// c) istart is set to the minimum index of rc.iv
// which comes strictly before the del.start;
// so del.start > rc.iv[istart].last,
// and if istart+1 exists, then del.start < rc.iv[istart+1].startx
// if del.last is not present, then ilast is
// set as follows:
//
// a) ilast == n-1 if del.last is beyond our
// last interval16 in rc.iv;
//
// b) ilast == -1 if del.last is before our first
// interval16 in rc.iv;
//
// c) ilast is set to the minimum index of rc.iv
// which comes strictly before the del.last;
// so del.last > rc.iv[ilast].last,
// and if ilast+1 exists, then del.last < rc.iv[ilast+1].start
// INVAR: istart >= 0
pre := rc.iv[:istart+1]
if ilast == n-1 {
rc.iv = pre
return
}
// INVAR: ilast < n-1
lost := ilast - istart
changeSize := -lost
newSize := int(len(rc.iv)) + changeSize
if changeSize != 0 {
copy(rc.iv[ilast+1+changeSize:], rc.iv[ilast+1:])
}
rc.iv = rc.iv[:newSize]
return
case startAlready && !lastAlready:
// we can only shrink or stay the same size
// i.e. we either eliminate the whole interval,
// or just cut off the right side.
res0, _ := rc.iv[istart].subtractInterval(del)
if len(res0) > 0 {
// len(res) must be 1
rc.iv[istart] = res0[0]
}
lost := 1 + (ilast - istart)
changeSize := int(len(res0)) - lost
newSize := int(len(rc.iv)) + changeSize
if changeSize != 0 {
copy(rc.iv[ilast+1+changeSize:], rc.iv[ilast+1:])
}
rc.iv = rc.iv[:newSize]
return
case !startAlready && lastAlready:
// we can only shrink or stay the same size
res1, _ := rc.iv[ilast].subtractInterval(del)
lost := ilast - istart
changeSize := int(len(res1)) - lost
newSize := int(len(rc.iv)) + changeSize
if changeSize != 0 {
// move the tail first to make room for res1
copy(rc.iv[ilast+1+changeSize:], rc.iv[ilast+1:])
}
copy(rc.iv[istart+1:], res1)
rc.iv = rc.iv[:newSize]
return
}
}
// compute rc minus b, and return the result as a new value (not inplace).
// port of run_container_andnot from CRoaring...
// https://github.com/RoaringBitmap/CRoaring/blob/master/src/containers/run.c#L435-L496
func (rc *runContainer16) AndNotRunContainer16(b *runContainer16) *runContainer16 {
if len(b.iv) == 0 || len(rc.iv) == 0 {
return rc
}
dst := newRunContainer16()
apos := 0
bpos := 0
a := rc
astart := a.iv[apos].start
alast := a.iv[apos].last()
bstart := b.iv[bpos].start
blast := b.iv[bpos].last()
alen := len(a.iv)
blen := len(b.iv)
for apos < alen && bpos < blen {
switch {
case alast < bstart:
// output the first run
dst.iv = append(dst.iv, newInterval16Range(astart, alast))
apos++
if apos < alen {
astart = a.iv[apos].start
alast = a.iv[apos].last()
}
case blast < astart:
// exit the second run
bpos++
if bpos < blen {
bstart = b.iv[bpos].start
blast = b.iv[bpos].last()
}
default:
// a: [ ]
// b: [ ]
// alast >= bstart
// blast >= astart
if astart < bstart {
dst.iv = append(dst.iv, newInterval16Range(astart, bstart-1))
}
if alast > blast {
astart = blast + 1
} else {
apos++
if apos < alen {
astart = a.iv[apos].start
alast = a.iv[apos].last()
}
}
}
}
if apos < alen {
dst.iv = append(dst.iv, newInterval16Range(astart, alast))
apos++
if apos < alen {
dst.iv = append(dst.iv, a.iv[apos:]...)
}
}
return dst
}
func (rc *runContainer16) numberOfRuns() (nr int) {
return len(rc.iv)
}
func (rc *runContainer16) containerType() contype {
return run16Contype
}
func (rc *runContainer16) equals16(srb *runContainer16) bool {
// Check if the containers are the same object.
if rc == srb {
return true
}
if len(srb.iv) != len(rc.iv) {
return false
}
for i, v := range rc.iv {
if v != srb.iv[i] {
return false
}
}
return true
}
// compile time verify we meet interface requirements
var _ container = &runContainer16{}
func (rc *runContainer16) clone() container {
return newRunContainer16CopyIv(rc.iv)
}
func (rc *runContainer16) minimum() uint16 {
return rc.iv[0].start // assume not empty
}
func (rc *runContainer16) maximum() uint16 {
return rc.iv[len(rc.iv)-1].last() // assume not empty
}
func (rc *runContainer16) isFull() bool {
return (len(rc.iv) == 1) && ((rc.iv[0].start == 0) && (rc.iv[0].last() == MaxUint16))
}
func (rc *runContainer16) and(a container) container {
if rc.isFull() {
return a.clone()
}
switch c := a.(type) {
case *runContainer16:
return rc.intersect(c)
case *arrayContainer:
return rc.andArray(c)
case *bitmapContainer:
return rc.andBitmapContainer(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) andCardinality(a container) int {
switch c := a.(type) {
case *runContainer16:
return int(rc.intersectCardinality(c))
case *arrayContainer:
return rc.andArrayCardinality(c)
case *bitmapContainer:
return rc.andBitmapContainerCardinality(c)
}
panic("unsupported container type")
}
// andBitmapContainer finds the intersection of rc and b.
func (rc *runContainer16) andBitmapContainer(bc *bitmapContainer) container {
bc2 := newBitmapContainerFromRun(rc)
return bc2.andBitmap(bc)
}
func (rc *runContainer16) andArrayCardinality(ac *arrayContainer) int {
pos := 0
answer := 0
maxpos := ac.getCardinality()
if maxpos == 0 {
return 0 // won't happen in actual code
}
v := ac.content[pos]
mainloop:
for _, p := range rc.iv {
for v < p.start {
pos++
if pos == maxpos {
break mainloop
}
v = ac.content[pos]
}
for v <= p.last() {
answer++
pos++
if pos == maxpos {
break mainloop
}
v = ac.content[pos]
}
}
return answer
}
func (rc *runContainer16) iand(a container) container {
if rc.isFull() {
return a.clone()
}
switch c := a.(type) {
case *runContainer16:
return rc.inplaceIntersect(c)
case *arrayContainer:
return rc.andArray(c)
case *bitmapContainer:
return rc.iandBitmapContainer(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) inplaceIntersect(rc2 *runContainer16) container {
sect := rc.intersect(rc2)
*rc = *sect
return rc
}
func (rc *runContainer16) iandBitmapContainer(bc *bitmapContainer) container {
isect := rc.andBitmapContainer(bc)
*rc = *newRunContainer16FromContainer(isect)
return rc
}
func (rc *runContainer16) andArray(ac *arrayContainer) container {
if len(rc.iv) == 0 {
return newArrayContainer()
}
acCardinality := ac.getCardinality()
c := newArrayContainerCapacity(acCardinality)
for rlePos, arrayPos := 0, 0; arrayPos < acCardinality; {
iv := rc.iv[rlePos]
arrayVal := ac.content[arrayPos]
for iv.last() < arrayVal {
rlePos++
if rlePos == len(rc.iv) {
return c
}
iv = rc.iv[rlePos]
}
if iv.start > arrayVal {
arrayPos = advanceUntil(ac.content, arrayPos, len(ac.content), iv.start)
} else {
c.content = append(c.content, arrayVal)
arrayPos++
}
}
return c
}
func (rc *runContainer16) andNot(a container) container {
switch c := a.(type) {
case *arrayContainer:
return rc.andNotArray(c)
case *bitmapContainer:
return rc.andNotBitmap(c)
case *runContainer16:
return rc.andNotRunContainer16(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) fillLeastSignificant16bits(x []uint32, i int, mask uint32) int {
k := i
var val int
for _, p := range rc.iv {
n := p.runlen()
for j := int(0); j < n; j++ {
val = int(p.start) + j
x[k] = uint32(val) | mask
k++
}
}
return k
}
func (rc *runContainer16) getShortIterator() shortPeekable {
return rc.newRunIterator16()
}
func (rc *runContainer16) getReverseIterator() shortIterable {
return rc.newRunReverseIterator16()
}
func (rc *runContainer16) getManyIterator() manyIterable {
return rc.newManyRunIterator16()
}
// add the values in the range [firstOfRange, endx). endx
// is still abe to express 2^16 because it is an int not an uint16.
func (rc *runContainer16) iaddRange(firstOfRange, endx int) container {
if firstOfRange > endx {
panic(fmt.Sprintf("invalid %v = endx > firstOfRange", endx))
}
if firstOfRange == endx {
return rc
}
addme := newRunContainer16TakeOwnership([]interval16{
{
start: uint16(firstOfRange),
length: uint16(endx - 1 - firstOfRange),
},
})
*rc = *rc.union(addme)
return rc
}
// remove the values in the range [firstOfRange,endx)
func (rc *runContainer16) iremoveRange(firstOfRange, endx int) container {
if firstOfRange > endx {
panic(fmt.Sprintf("request to iremove empty set [%v, %v),"+
" nothing to do.", firstOfRange, endx))
}
// empty removal
if firstOfRange == endx {
return rc
}
x := newInterval16Range(uint16(firstOfRange), uint16(endx-1))
rc.isubtract(x)
return rc
}
// not flip the values in the range [firstOfRange,endx)
func (rc *runContainer16) not(firstOfRange, endx int) container {
if firstOfRange > endx {
panic(fmt.Sprintf("invalid %v = endx > firstOfRange = %v", endx, firstOfRange))
}
return rc.Not(firstOfRange, endx)
}
// Not flips the values in the range [firstOfRange,endx).
// This is not inplace. Only the returned value has the flipped bits.
//
// Currently implemented as (!A intersect B) union (A minus B),
// where A is rc, and B is the supplied [firstOfRange, endx) interval.
//
// TODO(time optimization): convert this to a single pass
// algorithm by copying AndNotRunContainer16() and modifying it.
// Current routine is correct but
// makes 2 more passes through the arrays than should be
// strictly necessary. Measure both ways though--this may not matter.
//
func (rc *runContainer16) Not(firstOfRange, endx int) *runContainer16 {
if firstOfRange > endx {
panic(fmt.Sprintf("invalid %v = endx > firstOfRange == %v", endx, firstOfRange))
}
if firstOfRange >= endx {
return rc.Clone()
}
a := rc
// algo:
// (!A intersect B) union (A minus B)
nota := a.invert()
bs := []interval16{newInterval16Range(uint16(firstOfRange), uint16(endx-1))}
b := newRunContainer16TakeOwnership(bs)
notAintersectB := nota.intersect(b)
aMinusB := a.AndNotRunContainer16(b)
rc2 := notAintersectB.union(aMinusB)
return rc2
}
// equals is now logical equals; it does not require the
// same underlying container type.
func (rc *runContainer16) equals(o container) bool {
srb, ok := o.(*runContainer16)
if !ok {
// maybe value instead of pointer
val, valok := o.(*runContainer16)
if valok {
srb = val
ok = true
}
}
if ok {
// Check if the containers are the same object.
if rc == srb {
return true
}
if len(srb.iv) != len(rc.iv) {
return false
}
for i, v := range rc.iv {
if v != srb.iv[i] {
return false
}
}
return true
}
// use generic comparison
if o.getCardinality() != rc.getCardinality() {
return false
}
rit := rc.getShortIterator()
bit := o.getShortIterator()
//k := 0
for rit.hasNext() {
if bit.next() != rit.next() {
return false
}
//k++
}
return true
}
func (rc *runContainer16) iaddReturnMinimized(x uint16) container {
rc.Add(x)
return rc
}
func (rc *runContainer16) iadd(x uint16) (wasNew bool) {
return rc.Add(x)
}
func (rc *runContainer16) iremoveReturnMinimized(x uint16) container {
rc.removeKey(x)
return rc
}
func (rc *runContainer16) iremove(x uint16) bool {
return rc.removeKey(x)
}
func (rc *runContainer16) or(a container) container {
if rc.isFull() {
return rc.clone()
}
switch c := a.(type) {
case *runContainer16:
return rc.union(c)
case *arrayContainer:
return rc.orArray(c)
case *bitmapContainer:
return rc.orBitmapContainer(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) orCardinality(a container) int {
switch c := a.(type) {
case *runContainer16:
return int(rc.unionCardinality(c))
case *arrayContainer:
return rc.orArrayCardinality(c)
case *bitmapContainer:
return rc.orBitmapContainerCardinality(c)
}
panic("unsupported container type")
}
// orBitmapContainer finds the union of rc and bc.
func (rc *runContainer16) orBitmapContainer(bc *bitmapContainer) container {
bc2 := newBitmapContainerFromRun(rc)
return bc2.iorBitmap(bc)
}
func (rc *runContainer16) andBitmapContainerCardinality(bc *bitmapContainer) int {
answer := 0
for i := range rc.iv {
answer += bc.getCardinalityInRange(uint(rc.iv[i].start), uint(rc.iv[i].last())+1)
}
//bc.computeCardinality()
return answer
}
func (rc *runContainer16) orBitmapContainerCardinality(bc *bitmapContainer) int {
return rc.getCardinality() + bc.getCardinality() - rc.andBitmapContainerCardinality(bc)
}
// orArray finds the union of rc and ac.
func (rc *runContainer16) orArray(ac *arrayContainer) container {
if ac.isEmpty() {
return rc.clone()
}
if rc.isEmpty() {
return ac.clone()
}
intervals, cardMinusOne := runArrayUnionToRuns(rc, ac)
result := newRunContainer16TakeOwnership(intervals)
if len(intervals) >= 2048 && cardMinusOne >= arrayDefaultMaxSize {
return newBitmapContainerFromRun(result)
}
if len(intervals)*2 > 1+int(cardMinusOne) {
return result.toArrayContainer()
}
return result
}
// orArray finds the union of rc and ac.
func (rc *runContainer16) orArrayCardinality(ac *arrayContainer) int {
return ac.getCardinality() + rc.getCardinality() - rc.andArrayCardinality(ac)
}
func (rc *runContainer16) ior(a container) container {
if rc.isFull() {
return rc
}
switch c := a.(type) {
case *runContainer16:
return rc.inplaceUnion(c)
case *arrayContainer:
return rc.iorArray(c)
case *bitmapContainer:
return rc.iorBitmapContainer(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) inplaceUnion(rc2 *runContainer16) container {
for _, p := range rc2.iv {
last := int(p.last())
for i := int(p.start); i <= last; i++ {
rc.Add(uint16(i))
}
}
return rc
}
func (rc *runContainer16) iorBitmapContainer(bc *bitmapContainer) container {
it := bc.getShortIterator()
for it.hasNext() {
rc.Add(it.next())
}
return rc
}
func (rc *runContainer16) iorArray(ac *arrayContainer) container {
if rc.isEmpty() {
return ac.clone()
}
if ac.isEmpty() {
return rc
}
var cardMinusOne uint16
//TODO: perform the union algorithm in-place using rc.iv
// this can be done with methods like the in-place array container union
// but maybe lazily moving the remaining elements back.
rc.iv, cardMinusOne = runArrayUnionToRuns(rc, ac)
if len(rc.iv) >= 2048 && cardMinusOne >= arrayDefaultMaxSize {
return newBitmapContainerFromRun(rc)
}
if len(rc.iv)*2 > 1+int(cardMinusOne) {
return rc.toArrayContainer()
}
return rc
}
func runArrayUnionToRuns(rc *runContainer16, ac *arrayContainer) ([]interval16, uint16) {
pos1 := 0
pos2 := 0
length1 := len(ac.content)
length2 := len(rc.iv)
target := make([]interval16, 0, len(rc.iv))
// have to find the first range
// options are
// 1. from array container
// 2. from run container
var previousInterval interval16
var cardMinusOne uint16
if ac.content[0] < rc.iv[0].start {
previousInterval.start = ac.content[0]
previousInterval.length = 0
pos1++
} else {
previousInterval.start = rc.iv[0].start
previousInterval.length = rc.iv[0].length
pos2++
}
for pos1 < length1 || pos2 < length2 {
if pos1 < length1 {
s1 := ac.content[pos1]
if s1 <= previousInterval.start+previousInterval.length {
pos1++
continue
}
if previousInterval.last() < MaxUint16 && previousInterval.last()+1 == s1 {
previousInterval.length++
pos1++
continue
}
}
if pos2 < length2 {
range2 := rc.iv[pos2]
if range2.start <= previousInterval.last() || range2.start > 0 && range2.start-1 == previousInterval.last() {
pos2++
if previousInterval.last() < range2.last() {
previousInterval.length = range2.last() - previousInterval.start
}
continue
}
}
cardMinusOne += previousInterval.length + 1
target = append(target, previousInterval)
if pos2 == length2 || pos1 < length1 && ac.content[pos1] < rc.iv[pos2].start {
previousInterval.start = ac.content[pos1]
previousInterval.length = 0
pos1++
} else {
previousInterval = rc.iv[pos2]
pos2++
}
}
cardMinusOne += previousInterval.length
target = append(target, previousInterval)
return target, cardMinusOne
}
// lazyIOR is described (not yet implemented) in
// this nice note from @lemire on
// https://github.com/RoaringBitmap/roaring/pull/70#issuecomment-263613737
//
// Description of lazyOR and lazyIOR from @lemire:
//
// Lazy functions are optional and can be simply
// wrapper around non-lazy functions.
//
// The idea of "laziness" is as follows. It is
// inspired by the concept of lazy evaluation
// you might be familiar with (functional programming
// and all that). So a roaring bitmap is
// such that all its containers are, in some
// sense, chosen to use as little memory as
// possible. This is nice. Also, all bitsets
// are "cardinality aware" so that you can do
// fast rank/select queries, or query the
// cardinality of the whole bitmap... very fast,
// without latency.
//
// However, imagine that you are aggregating 100
// bitmaps together. So you OR the first two, then OR
// that with the third one and so forth. Clearly,
// intermediate bitmaps don't need to be as
// compressed as possible, right? They can be
// in a "dirty state". You only need the end
// result to be in a nice state... which you
// can achieve by calling repairAfterLazy at the end.
//
// The Java/C code does something special for
// the in-place lazy OR runs. The idea is that
// instead of taking two run containers and
// generating a new one, we actually try to
// do the computation in-place through a
// technique invented by @gssiyankai (pinging him!).
// What you do is you check whether the host
// run container has lots of extra capacity.
// If it does, you move its data at the end of
// the backing array, and then you write
// the answer at the beginning. What this
// trick does is minimize memory allocations.
//
func (rc *runContainer16) lazyIOR(a container) container {
// not lazy at the moment
return rc.ior(a)
}
// lazyOR is described above in lazyIOR.
func (rc *runContainer16) lazyOR(a container) container {
// not lazy at the moment
return rc.or(a)
}
func (rc *runContainer16) intersects(a container) bool {
// TODO: optimize by doing inplace/less allocation
isect := rc.and(a)
return !isect.isEmpty()
}
func (rc *runContainer16) xor(a container) container {
switch c := a.(type) {
case *arrayContainer:
return rc.xorArray(c)
case *bitmapContainer:
return rc.xorBitmap(c)
case *runContainer16:
return rc.xorRunContainer16(c)
}
panic("unsupported container type")
}
func (rc *runContainer16) iandNot(a container) container {
switch c := a.(type) {
case *arrayContainer:
return rc.iandNotArray(c)
case *bitmapContainer:
return rc.iandNotBitmap(c)
case *runContainer16:
return rc.iandNotRunContainer16(c)
}
panic("unsupported container type")
}
// flip the values in the range [firstOfRange,endx)
func (rc *runContainer16) inot(firstOfRange, endx int) container {
if firstOfRange > endx {
panic(fmt.Sprintf("invalid %v = endx > firstOfRange = %v", endx, firstOfRange))
}
if firstOfRange > endx {
return rc
}
// TODO: minimize copies, do it all inplace; not() makes a copy.
rc = rc.Not(firstOfRange, endx)
return rc
}
func (rc *runContainer16) rank(x uint16) int {
n := int(len(rc.iv))
xx := int(x)
w, already, _ := rc.search(xx)
if w < 0 {
return 0
}
if !already && w == n-1 {
return rc.getCardinality()
}
var rnk int
if !already {
for i := int(0); i <= w; i++ {
rnk += rc.iv[i].runlen()
}
return int(rnk)
}
for i := int(0); i < w; i++ {
rnk += rc.iv[i].runlen()
}
rnk += int(x-rc.iv[w].start) + 1
return int(rnk)
}
func (rc *runContainer16) selectInt(x uint16) int {
var offset int
for k := range rc.iv {
nextOffset := offset + rc.iv[k].runlen()
if nextOffset > int(x) {
return int(int(rc.iv[k].start) + (int(x) - offset))
}
offset = nextOffset
}
panic("cannot select x")
}
func (rc *runContainer16) andNotRunContainer16(b *runContainer16) container {
return rc.AndNotRunContainer16(b)
}
func (rc *runContainer16) andNotArray(ac *arrayContainer) container {
rcb := rc.toBitmapContainer()
acb := ac.toBitmapContainer()
return rcb.andNotBitmap(acb)
}
func (rc *runContainer16) andNotBitmap(bc *bitmapContainer) container {
rcb := rc.toBitmapContainer()
return rcb.andNotBitmap(bc)
}
func (rc *runContainer16) toBitmapContainer() *bitmapContainer {
bc := newBitmapContainer()
for i := range rc.iv {
bc.iaddRange(int(rc.iv[i].start), int(rc.iv[i].last())+1)
}
bc.computeCardinality()
return bc
}
func (rc *runContainer16) iandNotRunContainer16(x2 *runContainer16) container {
rcb := rc.toBitmapContainer()
x2b := x2.toBitmapContainer()
rcb.iandNotBitmapSurely(x2b)
// TODO: check size and optimize the return value
// TODO: is inplace modification really required? If not, elide the copy.
rc2 := newRunContainer16FromBitmapContainer(rcb)
*rc = *rc2
return rc
}
func (rc *runContainer16) iandNotArray(ac *arrayContainer) container {
rcb := rc.toBitmapContainer()
acb := ac.toBitmapContainer()
rcb.iandNotBitmapSurely(acb)
// TODO: check size and optimize the return value
// TODO: is inplace modification really required? If not, elide the copy.
rc2 := newRunContainer16FromBitmapContainer(rcb)
*rc = *rc2
return rc
}
func (rc *runContainer16) iandNotBitmap(bc *bitmapContainer) container {
rcb := rc.toBitmapContainer()
rcb.iandNotBitmapSurely(bc)
// TODO: check size and optimize the return value
// TODO: is inplace modification really required? If not, elide the copy.
rc2 := newRunContainer16FromBitmapContainer(rcb)
*rc = *rc2
return rc
}
func (rc *runContainer16) xorRunContainer16(x2 *runContainer16) container {
rcb := rc.toBitmapContainer()
x2b := x2.toBitmapContainer()
return rcb.xorBitmap(x2b)
}
func (rc *runContainer16) xorArray(ac *arrayContainer) container {
rcb := rc.toBitmapContainer()
acb := ac.toBitmapContainer()
return rcb.xorBitmap(acb)
}
func (rc *runContainer16) xorBitmap(bc *bitmapContainer) container {
rcb := rc.toBitmapContainer()
return rcb.xorBitmap(bc)
}
// convert to bitmap or array *if needed*
func (rc *runContainer16) toEfficientContainer() container {
sizeAsRunContainer := rc.getSizeInBytes()
sizeAsBitmapContainer := bitmapContainerSizeInBytes()
card := rc.getCardinality()
sizeAsArrayContainer := arrayContainerSizeInBytes(card)
if sizeAsRunContainer <= minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) {
return rc
}
if card <= arrayDefaultMaxSize {
return rc.toArrayContainer()
}
bc := newBitmapContainerFromRun(rc)
return bc
}
func (rc *runContainer16) toArrayContainer() *arrayContainer {
ac := newArrayContainer()
for i := range rc.iv {
ac.iaddRange(int(rc.iv[i].start), int(rc.iv[i].last())+1)
}
return ac
}
func newRunContainer16FromContainer(c container) *runContainer16 {
switch x := c.(type) {
case *runContainer16:
return x.Clone()
case *arrayContainer:
return newRunContainer16FromArray(x)
case *bitmapContainer:
return newRunContainer16FromBitmapContainer(x)
}
panic("unsupported container type")
}
// And finds the intersection of rc and b.
func (rc *runContainer16) And(b *Bitmap) *Bitmap {
out := NewBitmap()
for _, p := range rc.iv {
plast := p.last()
for i := p.start; i <= plast; i++ {
if b.Contains(uint32(i)) {
out.Add(uint32(i))
}
}
}
return out
}
// Xor returns the exclusive-or of rc and b.
func (rc *runContainer16) Xor(b *Bitmap) *Bitmap {
out := b.Clone()
for _, p := range rc.iv {
plast := p.last()
for v := p.start; v <= plast; v++ {
w := uint32(v)
if out.Contains(w) {
out.RemoveRange(uint64(w), uint64(w+1))
} else {
out.Add(w)
}
}
}
return out
}
// Or returns the union of rc and b.
func (rc *runContainer16) Or(b *Bitmap) *Bitmap {
out := b.Clone()
for _, p := range rc.iv {
plast := p.last()
for v := p.start; v <= plast; v++ {
out.Add(uint32(v))
}
}
return out
}
// serializedSizeInBytes returns the number of bytes of memory
// required by this runContainer16. This is for the
// Roaring format, as specified https://github.com/RoaringBitmap/RoaringFormatSpec/
func (rc *runContainer16) serializedSizeInBytes() int {
// number of runs in one uint16, then each run
// needs two more uint16
return 2 + len(rc.iv)*4
}
func (rc *runContainer16) addOffset(x uint16) (container, container) {
var low, high *runContainer16
if len(rc.iv) == 0 {
return nil, nil
}
first := uint32(rc.iv[0].start) + uint32(x)
if highbits(first) == 0 {
// Some elements will fall into low part, allocate a container.
// Checking the first one is enough because they are ordered.
low = newRunContainer16()
}
last := uint32(rc.iv[len(rc.iv)-1].start)
last += uint32(rc.iv[len(rc.iv)-1].length)
last += uint32(x)
if highbits(last) > 0 {
// Some elements will fall into high part, allocate a container.
// Checking the last one is enough because they are ordered.
high = newRunContainer16()
}
for _, iv := range rc.iv {
val := int(iv.start) + int(x)
finalVal := int(val) + int(iv.length)
if val <= 0xffff {
if finalVal <= 0xffff {
low.iv = append(low.iv, interval16{uint16(val), iv.length})
} else {
low.iv = append(low.iv, interval16{uint16(val), uint16(0xffff - val)})
high.iv = append(high.iv, interval16{uint16(0), uint16(finalVal & 0xffff)})
}
} else {
high.iv = append(high.iv, interval16{uint16(val & 0xffff), iv.length})
}
}
// Ensure proper nil interface.
if low == nil {
return nil, high
}
if high == nil {
return low, nil
}
return low, high
}
| {
"content_hash": "da64db8fb277999563951947fd5c0649",
"timestamp": "",
"source": "github",
"line_count": 2603,
"max_line_length": 151,
"avg_line_length": 25.516327314636957,
"alnum_prop": 0.669462051521402,
"repo_name": "RoaringBitmap/roaring",
"id": "4ce48a294cafc4a216185e3b6baf9ba634e6a2c8",
"size": "67903",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "runcontainer.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5487"
},
{
"name": "Go",
"bytes": "781033"
},
{
"name": "Makefile",
"bytes": "6274"
}
],
"symlink_target": ""
} |
'use strict';
var LIBRARY = require('./_library')
, global = require('./_global')
, ctx = require('./_ctx')
, classof = require('./_classof')
, $export = require('./_export')
, isObject = require('./_is-object')
, aFunction = require('./_a-function')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, speciesConstructor = require('./_species-constructor')
, task = require('./_task').set
, microtask = require('./_microtask')()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = require('./_redefine-all')($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
}); | {
"content_hash": "19b86ff9ffde4d8e0b61d8cd25737269",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 119,
"avg_line_length": 34.42809364548495,
"alnum_prop": 0.5695550806294929,
"repo_name": "sarataha/yalla-netlob",
"id": "ae642f577b6e787c8469fbf3d6b6ffc54196187e",
"size": "10294",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "node_modules/core-js/modules/es6.promise.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "46599"
},
{
"name": "HTML",
"bytes": "72331"
},
{
"name": "JavaScript",
"bytes": "337675"
}
],
"symlink_target": ""
} |
var MagnificPopup = function() {
'use strict';
// Handle Magnific Popup
var handleMagnificPopup = function() {
// Image popup - vertical fit
$(document).ready(function() {
$('.js__popup__image').magnificPopup({
type: 'image',
closeOnContentClick: true,
mainClass: 'mfp-img-mobile',
image: {
verticalFit: true,
}
});
});
// Popup gallery
$(document).ready(function() {
$('.js__popup__gallery').magnificPopup({
delegate: 'a.js__popup__gallery-child',
type: 'image',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
}
});
});
// Multiple Galleries with a single popup
$(document).ready(function() {
$('.js__popup__multiple-image').magnificPopup({
type: 'image',
tLoading: 'Loading image #%curr%...',
fixedContentPos: true,
gallery: {
enabled: true,
navigateByImgClick: true,
arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
preload: [0,1], // Will preload 0 - before current, and 1 after the current image
}
});
});
// Video iframes
$(document).ready(function() {
$('.js__popup__youtube, .js__popup__vimeo').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: true
});
});
}
return {
init: function() {
handleMagnificPopup(); // initial setup for Magnific Popup
}
}
}();
$(document).ready(function() {
MagnificPopup.init();
});
| {
"content_hash": "337ca96b85c81473a705aa774ec69a1d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 107,
"avg_line_length": 27.02777777777778,
"alnum_prop": 0.540082219938335,
"repo_name": "martinzhou2015/SRCMS",
"id": "db3a00ed891f7daa9915d9a71ee14211483004ac",
"size": "1964",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Public/Index/js/components/magnific-popup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "647257"
},
{
"name": "HTML",
"bytes": "509535"
},
{
"name": "JavaScript",
"bytes": "3037377"
},
{
"name": "Makefile",
"bytes": "29"
},
{
"name": "PHP",
"bytes": "1604544"
},
{
"name": "Smarty",
"bytes": "62326"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>circuits: 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.10.0 / circuits - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">ยซ Up</a>
<h1>
circuits
<small>
8.9.0
<span class="label label-info">Not compatible ๐ผ</span>
</small>
</h1>
<p>๐
<em><script>document.write(moment("2020-07-29 03:23:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-29 03:23:42 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.10.0 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/circuits"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Circuits"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: hardware verification"
"category: Computer Science/Architecture"
]
authors: [
"Laurent Arditi"
]
bug-reports: "https://github.com/coq-contribs/circuits/issues"
dev-repo: "git+https://github.com/coq-contribs/circuits.git"
synopsis: "Some proofs of hardware (adder, multiplier, memory block instruction)"
description: """
definition and proof of a combinatorial adder, a
sequential multiplier, a memory block instruction"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/circuits/archive/v8.9.0.tar.gz"
checksum: "md5=c37c234a02f07103936671d8488c68f4"
}
</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-circuits.8.9.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0).
The following dependencies couldn't be met:
- coq-circuits -> coq < 8.10~ -> 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-circuits.8.9.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": "d83e80d73049b2a7949ea0df1925998a",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 159,
"avg_line_length": 40.188235294117646,
"alnum_prop": 0.5401053864168618,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "814bda87acce7240268ea256b2b569aa9d80d513",
"size": "6857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/extra-dev/8.10.0/circuits/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.cipango.util;
import java.util.Iterator;
import javax.servlet.sip.SipURI;
public class SipURIProxy extends URIProxy implements SipURI
{
static final long serialVersionUID = -8783776759537945045L;
private SipURI _uri;
public SipURIProxy(SipURI uri)
{
super(uri);
_uri = uri;
}
public String getUser()
{
return _uri.getUser();
}
public void setUser(String user)
{
_uri.setUser(user);
}
public String getUserPassword()
{
return _uri.getUserPassword();
}
public void setUserPassword(String passwd)
{
_uri.setUserPassword(passwd);
}
public String getHost()
{
return _uri.getHost();
}
public void setHost(String host)
{
_uri.setHost(host);
}
public int getPort()
{
return _uri.getPort();
}
public void setPort(int port)
{
_uri.setPort(port);
}
public boolean isSecure()
{
return _uri.isSecure();
}
public void setSecure(boolean secure)
{
_uri.setSecure(secure);
}
public String getTransportParam()
{
return _uri.getTransportParam();
}
public void setTransportParam(String param)
{
_uri.setTransportParam(param);
}
public String getMAddrParam()
{
return _uri.getMAddrParam();
}
public void setMAddrParam(String param)
{
_uri.setTransportParam(param);
}
public String getMethodParam()
{
return _uri.getMethodParam();
}
public void setMethodParam(String param)
{
_uri.setMethodParam(param);
}
public int getTTLParam()
{
return _uri.getTTLParam();
}
public void setTTLParam(int ttl)
{
_uri.setTTLParam(ttl);
}
public String getUserParam()
{
return _uri.getUserParam();
}
public void setUserParam(String param)
{
_uri.setUserParam(param);
}
public boolean getLrParam()
{
return _uri.getLrParam();
}
public void setLrParam(boolean lr)
{
_uri.setLrParam(lr);
}
public String getHeader(String name)
{
return _uri.getHeader(name);
}
public void setHeader(String name, String value)
{
_uri.setHeader(name, value);
}
public Iterator<String> getHeaderNames()
{
return _uri.getHeaderNames();
}
public void removeHeader(String name)
{
_uri.removeHeader(name);
}
}
| {
"content_hash": "166045cc596d24fc67c75b09b180c3e2",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 63,
"avg_line_length": 18.114864864864863,
"alnum_prop": 0.5490488623647892,
"repo_name": "tjpdj1988/cipango",
"id": "a1c7b7d4fc6dcca44d7e16718d9562b2ffa15d46",
"size": "3506",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "cipango-server/src/main/java/org/cipango/util/SipURIProxy.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1730"
},
{
"name": "CSS",
"bytes": "6635"
},
{
"name": "HTML",
"bytes": "1785"
},
{
"name": "Java",
"bytes": "2649503"
},
{
"name": "JavaScript",
"bytes": "4641"
},
{
"name": "Makefile",
"bytes": "1799"
},
{
"name": "Ruby",
"bytes": "68481"
},
{
"name": "Shell",
"bytes": "5446"
},
{
"name": "XSLT",
"bytes": "7166"
}
],
"symlink_target": ""
} |
using base::ASCIIToUTF16;
using base::WideToUTF16;
namespace views {
namespace examples {
namespace {
const char* kElideBehaviors[] = { "No Elide", "Truncate", "Elide Head",
"Elide Middle", "Elide Tail", "Elide Email", "Fade Tail" };
const char* kAlignments[] = { "Left", "Center", "Right", "Head" };
// A Label with a clamped preferred width to demonstrate eliding or wrapping.
class PreferredSizeLabel : public Label {
public:
PreferredSizeLabel() : Label() {
SetBorder(Border::CreateSolidBorder(1, SK_ColorGRAY));
}
~PreferredSizeLabel() override {}
// Label:
gfx::Size GetPreferredSize() const override {
return gfx::Size(50, Label::GetPreferredSize().height());
}
private:
DISALLOW_COPY_AND_ASSIGN(PreferredSizeLabel);
};
} // namespace
LabelExample::LabelExample()
: ExampleBase("Label"),
textfield_(NULL),
alignment_(NULL),
elide_behavior_(NULL),
multiline_(NULL),
shadows_(NULL),
custom_label_(NULL) {
}
LabelExample::~LabelExample() {
// Remove the views first as some reference combobox models.
container()->RemoveAllChildViews(true);
}
void LabelExample::CreateExampleView(View* container) {
// A very simple label example, followed by additional helpful examples.
container->SetLayoutManager(new BoxLayout(BoxLayout::kVertical, 0, 0, 10));
Label* label = new Label(ASCIIToUTF16("Hello world!"));
container->AddChildView(label);
const wchar_t hello_world_hebrew[] =
L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd!";
label = new Label(WideToUTF16(hello_world_hebrew));
label->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
container->AddChildView(label);
label = new Label(WideToUTF16(L"A UTF16 surrogate pair: \x5d0\x5b0"));
label->SetHorizontalAlignment(gfx::ALIGN_RIGHT);
container->AddChildView(label);
label = new Label(ASCIIToUTF16("A left-aligned blue label."));
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
label->SetEnabledColor(SK_ColorBLUE);
container->AddChildView(label);
label = new Label(WideToUTF16(L"Password!"));
label->SetObscured(true);
container->AddChildView(label);
label = new Label(ASCIIToUTF16("A Courier-18 label with shadows."));
label->SetFontList(gfx::FontList("Courier, 18px"));
gfx::ShadowValues shadows(1,
gfx::ShadowValue(gfx::Vector2d(), 1, SK_ColorRED));
gfx::ShadowValue shadow(gfx::Vector2d(2, 2), 0, SK_ColorGRAY);
shadows.push_back(shadow);
label->SetShadows(shadows);
container->AddChildView(label);
label = new PreferredSizeLabel();
label->SetText(ASCIIToUTF16("A long label will elide toward its logical end "
"if the text's width exceeds the label's available width."));
container->AddChildView(label);
label = new PreferredSizeLabel();
label->SetText(ASCIIToUTF16("A multi-line label will wrap onto subsequent "
"lines if the text's width exceeds the label's available width, which is "
"helpful for extemely long text used to demonstrate line wrapping."));
label->SetMultiLine(true);
container->AddChildView(label);
label = new Label(ASCIIToUTF16("Label with thick border"));
label->SetBorder(Border::CreateSolidBorder(20, SK_ColorRED));
container->AddChildView(label);
AddCustomLabel(container);
}
void LabelExample::ButtonPressed(Button* button, const ui::Event& event) {
if (button == multiline_) {
custom_label_->SetMultiLine(multiline_->checked());
} else if (button == shadows_) {
gfx::ShadowValues shadows;
if (shadows_->checked()) {
shadows.push_back(gfx::ShadowValue(gfx::Vector2d(), 1, SK_ColorRED));
shadows.push_back(gfx::ShadowValue(gfx::Vector2d(2, 2), 0, SK_ColorGRAY));
}
custom_label_->SetShadows(shadows);
}
custom_label_->parent()->parent()->Layout();
custom_label_->SchedulePaint();
}
void LabelExample::OnPerformAction(Combobox* combobox) {
if (combobox == alignment_) {
custom_label_->SetHorizontalAlignment(
static_cast<gfx::HorizontalAlignment>(combobox->selected_index()));
} else if (combobox == elide_behavior_) {
custom_label_->SetElideBehavior(
static_cast<gfx::ElideBehavior>(combobox->selected_index()));
}
}
void LabelExample::ContentsChanged(Textfield* sender,
const base::string16& new_contents) {
custom_label_->SetText(new_contents);
custom_label_->parent()->parent()->Layout();
}
void LabelExample::AddCustomLabel(View* container) {
View* control_container = new View();
control_container->SetBorder(Border::CreateSolidBorder(2, SK_ColorGRAY));
control_container->set_background(
Background::CreateSolidBackground(SK_ColorLTGRAY));
GridLayout* layout = GridLayout::CreatePanel(control_container);
control_container->SetLayoutManager(layout);
ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL,
0.0f, GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL,
1.0f, GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 0);
layout->AddView(new Label(ASCIIToUTF16("Content: ")));
textfield_ = new Textfield();
textfield_->SetText(ASCIIToUTF16("Use the provided controls to configure the "
"content and presentation of this custom label."));
textfield_->SetSelectionRange(gfx::Range());
textfield_->set_controller(this);
layout->AddView(textfield_);
alignment_ = AddCombobox(layout, "Alignment: ", kAlignments,
arraysize(kAlignments));
elide_behavior_ = AddCombobox(layout, "Elide Behavior: ", kElideBehaviors,
arraysize(kElideBehaviors));
column_set = layout->AddColumnSet(1);
column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING,
0, GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING,
0, GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 1);
multiline_ = new Checkbox(base::ASCIIToUTF16("Multiline"));
multiline_->set_listener(this);
layout->AddView(multiline_);
shadows_ = new Checkbox(base::ASCIIToUTF16("Shadows"));
shadows_->set_listener(this);
layout->AddView(shadows_);
layout->AddPaddingRow(0, 8);
column_set = layout->AddColumnSet(2);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL,
1, GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 2);
custom_label_ = new PreferredSizeLabel();
custom_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
custom_label_->SetElideBehavior(gfx::NO_ELIDE);
custom_label_->SetText(textfield_->text());
layout->AddView(custom_label_);
container->AddChildView(control_container);
}
Combobox* LabelExample::AddCombobox(GridLayout* layout,
const char* name,
const char** strings,
int count) {
layout->StartRow(0, 0);
layout->AddView(new Label(base::ASCIIToUTF16(name)));
ExampleComboboxModel* model = new ExampleComboboxModel(strings, count);
example_combobox_models_.push_back(make_scoped_ptr(model));
Combobox* combobox = new Combobox(model);
combobox->SetSelectedIndex(0);
combobox->set_listener(this);
layout->AddView(combobox);
return combobox;
}
} // namespace examples
} // namespace views
| {
"content_hash": "1a45e68146bdf46a58129f6d761e6d9d",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 80,
"avg_line_length": 36.57920792079208,
"alnum_prop": 0.680470970361348,
"repo_name": "js0701/chromium-crosswalk",
"id": "98ea080ac0883b72a4c21e9d30a095acc89e4414",
"size": "8126",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "ui/views/examples/label_example.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content=""/>
<meta name="author" content=""/>
<title>EduManage - Add new Subject</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet"/>
<!-- Custom CSS -->
<link href="../dist/css/common.min.css" rel="stylesheet"/>
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">EduManage</a>
</div>
<!-- /.navbar-header -->
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-envelope fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-messages">
<li>
<a href="#">
<div>
<strong>John Smith</strong>
<span class="pull-right text-muted">
<em>Yesterday</em>
</span>
</div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>Read All Messages</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-messages -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-tasks">
<li>
<a href="#">
<div>
<p>
<strong>Task 1</strong>
<span class="pull-right text-muted">40% Complete</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Tasks</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-tasks -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-bell fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="#">
<div>
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small">4 minutes ago</span>
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a class="text-center" href="#">
<strong>See All Alerts</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>
</ul>
<!-- /.dropdown-alerts -->
</li>
<!-- /.dropdown -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#"><i class="fa fa-user fa-fw"></i> User Profile</a>
</li>
<li><a href="#"><i class="fa fa-gear fa-fw"></i> Settings</a>
</li>
<li class="divider"></li>
<li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Search..."/>
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<!-- /input-group -->
</li>
<li>
<a href="index.html"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a>
</li>
<li>
<a href="staff.html"><i class="fa fa-users fa-fw"></i> Staff</a>
</li>
<li>
<a href="student.html"><i class="fa fa-user-circle-o fa-fw"></i> Student</a>
</li>
<li>
<a class="active" href="#"><i class="fa fa-shield fa-fw"></i> Administration<span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse in">
<li>
<a href="course.html"><i class="fa fa-file-text fa-fw"></i> Course</a>
</li>
<li>
<a href="class.html"><i class="fa fa-window-maximize fa-fw"></i> Class</a>
</li>
<li>
<a class="active" href="subject.html"><i class="fa fa-book fa-fw"></i> Subject</a>
</li>
</ul>
<!-- /.nav-second-level -->
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side -->
</nav>
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<div class="panel panel-primary">
<div class="panel-heading">
Subject details
</div>
<!-- /.panel-heading -->
<form role="form">
<div class="panel-body">
<div class="row">
<div class="col-md-5 col-sm-12">
<div class="form-group">
<label for="subjectName" class="control-label">Subject Name</label>
<input type="text" class="form-control" id="subjectName" placeholder="Subject Name" />
</div>
<div class="form-group">
<label for="subjectCode" class="control-label">Subject Code</label>
<input type="text" class="form-control" id="subjectCode" placeholder="Subject Code" />
</div>
<div class="form-group">
<label for="Course" class="control-label">Course</label>
<select name="Course" id="Course" class="form-control">
<option selected disabled value="Select Course">Select Course</option>
<option value="BBM">BBM</option>
<option value="B.Com">B.Com</option>
<option value="B.Sc">B.Sc</option>
<option value="B.A">B.A</option>
<option value="BCA">BCA</option>
</select>
</div>
<div class="form-group">
<label for="studentGender" class="control-label">Type</label>
<div>
<label class="radio-inline">
<input type="radio" name="type" id="mandatory" value="mandatory"> Mandatory
</label>
<label class="radio-inline">
<input type="radio" name="type" id="optional" value="optional"> Optional
</label>
</div>
</div>
</div>
</div>
</div>
<!-- /.panel-body -->
<div class="panel-footer">
<div class="row">
<div class="col-lg-12 text-right">
<button type="button" class="btn btn-default">Cancel</button>
<button type="reset" class="btn btn-default">Clear</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
<!-- /.panel-footer -->
</form>
</div>
<!-- /.panel -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/common.min.js"></script>
</body>
</html>
| {
"content_hash": "47f6cc10604e890a0350fd369c47f31d",
"timestamp": "",
"source": "github",
"line_count": 279,
"max_line_length": 182,
"avg_line_length": 48.655913978494624,
"alnum_prop": 0.36220994475138124,
"repo_name": "Prasanna185/EduManage",
"id": "30f54badbb91ca49cba806b9718555ac13a81923",
"size": "13575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pages/subject_register.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "175502"
},
{
"name": "JavaScript",
"bytes": "3823"
}
],
"symlink_target": ""
} |
from tempest.api.network import base
from tempest import test
class DHCPAgentSchedulersTestJSON(base.BaseAdminNetworkTest):
_interface = 'json'
@classmethod
@test.safe_setup
def setUpClass(cls):
super(DHCPAgentSchedulersTestJSON, cls).setUpClass()
if not test.is_extension_enabled('dhcp_agent_scheduler', 'network'):
msg = "dhcp_agent_scheduler extension not enabled."
raise cls.skipException(msg)
# Create a network and make sure it will be hosted by a
# dhcp agent: this is done by creating a regular port
cls.network = cls.create_network()
cls.subnet = cls.create_subnet(cls.network)
cls.cidr = cls.subnet['cidr']
cls.port = cls.create_port(cls.network)
@test.attr(type='smoke')
def test_list_dhcp_agent_hosting_network(self):
_, body = self.admin_client.list_dhcp_agent_hosting_network(
self.network['id'])
@test.attr(type='smoke')
def test_list_networks_hosted_by_one_dhcp(self):
resp, body = self.admin_client.list_dhcp_agent_hosting_network(
self.network['id'])
agents = body['agents']
self.assertIsNotNone(agents)
agent = agents[0]
self.assertTrue(self._check_network_in_dhcp_agent(
self.network['id'], agent))
def _check_network_in_dhcp_agent(self, network_id, agent):
network_ids = []
_, body = self.admin_client.list_networks_hosted_by_one_dhcp_agent(
agent['id'])
networks = body['networks']
for network in networks:
network_ids.append(network['id'])
return network_id in network_ids
@test.attr(type='smoke')
def test_add_remove_network_from_dhcp_agent(self):
# The agent is now bound to the network, we can free the port
self.client.delete_port(self.port['id'])
self.ports.remove(self.port)
agent = dict()
agent['agent_type'] = None
resp, body = self.admin_client.list_agents()
agents = body['agents']
for a in agents:
if a['agent_type'] == 'DHCP agent':
agent = a
break
self.assertEqual(agent['agent_type'], 'DHCP agent', 'Could not find '
'DHCP agent in agent list though dhcp_agent_scheduler'
' is enabled.')
network = self.create_network()
network_id = network['id']
if self._check_network_in_dhcp_agent(network_id, agent):
self._remove_network_from_dhcp_agent(network_id, agent)
self._add_dhcp_agent_to_network(network_id, agent)
else:
self._add_dhcp_agent_to_network(network_id, agent)
self._remove_network_from_dhcp_agent(network_id, agent)
def _remove_network_from_dhcp_agent(self, network_id, agent):
_, body = self.admin_client.remove_network_from_dhcp_agent(
agent_id=agent['id'],
network_id=network_id)
self.assertFalse(self._check_network_in_dhcp_agent(
network_id, agent))
def _add_dhcp_agent_to_network(self, network_id, agent):
_, body = self.admin_client.add_dhcp_agent_to_network(agent['id'],
network_id)
self.assertTrue(self._check_network_in_dhcp_agent(
network_id, agent))
class DHCPAgentSchedulersTestXML(DHCPAgentSchedulersTestJSON):
_interface = 'xml'
| {
"content_hash": "0304044a7fbda7546fde02c01ec6f2c8",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 79,
"avg_line_length": 40.46511627906977,
"alnum_prop": 0.603448275862069,
"repo_name": "cloudbase/lis-tempest",
"id": "c84d1a7c36f73ed78d1b5dd674df3ede1312e199",
"size": "4082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tempest/api/network/admin/test_dhcp_agent_scheduler.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "3377111"
},
{
"name": "Shell",
"bytes": "8663"
}
],
"symlink_target": ""
} |
const toml = require('toml')
const defaultEventsFile = require('raw-loader!../../conf/events.toml')
let eventConfig = toml.parse(defaultEventsFile)
const canvas = document.createElement('canvas')
canvas.width = 16 * 32 * 2
canvas.height = 16 * 32
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'white'
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)'
ctx.lineWidth = 2
let fontface = 'Tahoma, sans-serif'
ctx.textBaseline = 'middle'
ctx.textAlign = 'center'
ctx.imageSmoothingEnabled = false
const tree = []
const categories = new Map()
function buildTree () {
tree.length = 0
categories.clear()
eventConfig.Subcategories.forEach((o) => {
categories.set(o.category, o)
})
eventConfig.Categories.forEach(({name, multiplayer}) => {
})
}
function drawEvents () {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.imageSmoothingEnabled = false
ctx.save()
for (let i = 0; i < 256; i++) {
let event = eventConfig.Events[i] || {category: null}
let category = categories.get(event.category)
let hue = typeof event.hue === 'number' ? event.hue : (category && typeof category.hue === 'number' ? category.hue : null)
let saturation = typeof event.saturation === 'number' ? event.saturation : (category && typeof category.saturation === 'number' ? category.saturation : 100)
let brightness = typeof event.brightness === 'number' ? event.brightness : (category && typeof category.brightness === 'number' ? category.brightness : 40)
let stroke = typeof event.stroke === 'boolean' ? event.stroke : (category && typeof category.stroke === 'boolean' ? category.stroke : true)
if (hue == null) {
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'
ctx.strokeStyle = 'rgba(255, 255, 255, 0.6)'
} else {
ctx.fillStyle = 'hsla(' + hue + ', ' + saturation + '%, ' + (brightness / 4) + '%, 0.6)'
ctx.strokeStyle = 'hsla(' + hue + ', ' + saturation + '%, ' + brightness + '%, ' + (stroke ? 1 : 0.2) + ')'
}
ctx.save()
ctx.beginPath()
ctx.rect((i % 16) * 32, Math.floor(i / 16) * 32, 32, 32)
ctx.clip()
ctx.beginPath()
ctx.rect((i % 16) * 32, Math.floor(i / 16) * 32, 32, 32)
ctx.fill()
ctx.stroke()
ctx.restore()
ctx.drawImage(canvas, (i % 16) * 32, Math.floor(i / 16) * 32, 32, 32, (i % 16) * 32 + 16 * 32, Math.floor(i / 16) * 32, 32, 32)
ctx.save()
ctx.translate((i % 16) * 32 + 16 * 32, Math.floor(i / 16) * 32)
ctx.fillStyle = ctx.strokeStyle
ctx.beginPath()
ctx.moveTo(1, 1)
ctx.lineTo(1, 6)
ctx.lineTo(12, 1)
ctx.moveTo(31, 31)
ctx.lineTo(31, 26)
ctx.lineTo(20, 31)
ctx.fill()
ctx.restore()
if (i > 0) {
ctx.clearRect(0, 0, 32, 32)
ctx.save()
ctx.beginPath()
ctx.rect(0, 0, 32, 32)
ctx.clip()
ctx.translate(16, 16)
if (!event.bottom) {
findFontSize(event.top)
ctx.fillStyle = 'black'
ctx.fillText(event.top, 1, 1)
ctx.fillStyle = 'white'
ctx.fillText(event.top, 0, 0)
ctx.fillText(event.top, 0, 0)
} else {
let size = Math.min(findFontSize(event.top), findFontSize(event.bottom))
let fontstyle = size <= 10 ? 'bold' : ''
ctx.font = fontstyle + ' ' + size + 'px ' + fontface
ctx.textBaseline = 'bottom'
ctx.fillStyle = 'black'
ctx.fillText(event.top, 1, 2)
ctx.fillStyle = 'white'
ctx.fillText(event.top, 0, 1)
ctx.fillText(event.top, 0, 1)
ctx.textBaseline = 'top'
ctx.fillStyle = 'black'
ctx.fillText(event.bottom, 1, 0)
ctx.fillStyle = 'white'
ctx.fillText(event.bottom, 0, -1)
ctx.fillText(event.bottom, 0, -1)
}
ctx.restore()
ctx.drawImage(canvas, 0, 0, 32, 32, (i % 16) * 32, Math.floor(i / 16) * 32, 32, 32)
ctx.drawImage(canvas, 0, 0, 32, 32, (i % 16) * 32 + 16 * 32, Math.floor(i / 16) * 32, 32, 32)
}
}
ctx.clearRect(0, 0, 32, 32)
ctx.restore()
}
function findFontSize (text) {
let fontSize = 12.5
do {
fontSize -= 0.5
let fontstyle = fontSize <= 10 ? 'bold' : ''
ctx.font = fontstyle + ' ' + fontSize + 'px ' + fontface
} while (ctx.measureText(text).width > 33 && fontSize >= 9)
return fontSize
}
buildTree()
drawEvents()
const events = {
canvas,
ctx
}
module.exports = events
| {
"content_hash": "a88173d001444a31b83aff23f9a62fdb",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 160,
"avg_line_length": 30.25874125874126,
"alnum_prop": 0.5881673214698405,
"repo_name": "daniel-j/webjcs",
"id": "1d827c57d9fe8863e9bb08e86698ac84e66c594c",
"size": "4328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/events.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23700"
},
{
"name": "GLSL",
"bytes": "5959"
},
{
"name": "HTML",
"bytes": "555"
},
{
"name": "JavaScript",
"bytes": "188134"
},
{
"name": "Makefile",
"bytes": "3331"
}
],
"symlink_target": ""
} |
#import <Foundation/NSObject.h>
@class NSMethodSignature, NSInvocation;
@interface NSProxy <NSObject> {
Class isa;
}
+allocWithZone:(NSZone *)zone;
+alloc;
+(Class)class;
//+(BOOL)respondsToSelector:(SEL)selector;
-(void)dealloc;
-(void)finalize;
-(NSMethodSignature *)methodSignatureForSelector:(SEL)selector;
-(void)forwardInvocation:(NSInvocation *)invocation;
-(NSString *)description;
@end
| {
"content_hash": "61e421b9ad4887a49b5d283473612f28",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 63,
"avg_line_length": 15.76923076923077,
"alnum_prop": 0.7414634146341463,
"repo_name": "mpw/marcelweiher-libobjc2",
"id": "0108aa1d9f87e1d2f61578daf19ab0c1145c0f7a",
"size": "1487",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Foundation/NSProxy.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "11083"
},
{
"name": "C",
"bytes": "537717"
},
{
"name": "C++",
"bytes": "27437"
},
{
"name": "M",
"bytes": "117203"
},
{
"name": "Mathematica",
"bytes": "94396"
},
{
"name": "Matlab",
"bytes": "34902"
},
{
"name": "Objective-C",
"bytes": "7379762"
},
{
"name": "Objective-C++",
"bytes": "53957"
},
{
"name": "Shell",
"bytes": "301"
}
],
"symlink_target": ""
} |
๏ปฟ
table.app-launcher-apps {
border-radius: 20px;
background: #111111;
border-collapse: separate; /* override bootstrap if necessary */
padding: 36px 23px 36px 23px;
}
table.app-launcher-apps tr td {
min-width: 100px;
margin-bottom: 15px;
font-size: 18px;
text-align: center;
padding: 13px;
}
table.app-launcher-apps tr td a div {
border-radius: 24px;
border: none;
box-shadow: inset 0px 2px 2px 2px rgba(255, 255, 255, 0.2);
background-repeat: no-repeat;
background-position: center center;
width: 100px;
height: 100px;
margin: 0 auto 5px;
vertical-align: middle;
font-size: 68px;
}
table.app-launcher-apps tr td a {
text-decoration: none;
display: block;
white-space: nowrap;
width: 120px;
overflow: hidden; /* "overflow" value must be different from "visible" */
text-overflow: ellipsis;
transition: all .07s ease-in-out;
}
table.app-launcher-apps tr td a:hover {
transform: scale(1.05);
}
table.app-launcher-apps tr td a:link {
color: #eee;
}
table.app-launcher-apps tr td a:visited {
color: #eee;
}
table.app-launcher-apps tr td a:hover {
color: #fff;
}
table.app-launcher-apps tr td a:active {
color: #eee;
}
table.app-launcher-apps .app-launcher-icon-a {
background: radial-gradient(#8e3, #370);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-b {
font-style: italic;
background: linear-gradient(#f91, #c60);
color: #010;
}
table.app-launcher-apps .app-launcher-icon-c {
background: linear-gradient(#c4c,#909);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-d {
background: linear-gradient(#49e, #27c);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-e {
background: linear-gradient(#49e, #27c);
color: #fff;
}
table.app-launcher-apps .app-launcher-icon-f {
font-style: italic;
background: linear-gradient(#7d3, #3a0);
color: #fff
}
table.app-launcher-apps .app-launcher-icon-g {
background: linear-gradient(#49e, #27c);
color: #fff;
}
table.app-launcher-apps .app-launcher-icon-h {
background: linear-gradient(#7d3, #3a0);
color: #fff
}
table.app-launcher-apps .app-launcher-icon-i {
font-style: italic;
background: linear-gradient(#49e, #27c);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-j {
background: linear-gradient(#7d3, #3a0);
color: #fff
}
table.app-launcher-apps .app-launcher-icon-k {
background: linear-gradient(#49e, #27c);
color: #fff;
}
table.app-launcher-apps .app-launcher-icon-l {
font-style: italic;
font-family: serif;
font-size: 50px;
background: #0912f4;
color: #eee;
}
table.app-launcher-apps .app-launcher-icon-m {
background: linear-gradient(#fff, #ccc);
border: none;
color: #111;
}
table.app-launcher-apps .app-launcher-icon-n {
background: linear-gradient(#c4c,#909);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-o {
background: linear-gradient(#ccf,#33e);
color: #eee;
font-weight: bold;
border: none;
}
table.app-launcher-apps .app-launcher-icon-p {
font-style: italic;
background: linear-gradient(#c4c,#909);
color: #fff;
border: none;
}
table.app-launcher-apps .app-launcher-icon-q {
background: linear-gradient(#ccf,#33e);
color: #eee;
}
table.app-launcher-apps .app-launcher-icon-r {
background: linear-gradient(#c4c,#909);
color: #fff;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-s {
background: linear-gradient(#7d3, #3a0);
color: #fff
}
/* BEGIN: Example of overriding default icon with an image. */
table.app-launcher-apps .app-launcher-icon-settings {
background-image: url('../images/settings.png');
background-size: 100px 100px;
color: #fff;
box-shadow: none;
}
table.app-launcher-apps .app-launcher-icon-s.app-launcher-icon-settings span {
display: none;
}
/* END: Example of overriding default icon with an image. */
table.app-launcher-apps .app-launcher-icon-t {
font-style: italic;
background: #fd0;
color: #000104;
font-weight: bold;
}
table.app-launcher-apps .app-launcher-icon-u {
background: linear-gradient(#49e, #27c);
color: #fff;
}
table.app-launcher-apps .app-launcher-icon-v {
background: linear-gradient(#fff, #ccc);
color: #111;
}
table.app-launcher-apps .app-launcher-icon-w {
font-style: italic;
background: linear-gradient(#fff, #ccc);
color: #111;
}
table.app-launcher-apps .app-launcher-icon-x {
background: linear-gradient(#f91, #c60);
color: #010;
}
table.app-launcher-apps .app-launcher-icon-y {
background: linear-gradient(#f91, #c60);
color: #010;
}
table.app-launcher-apps .app-launcher-icon-z {
background: linear-gradient(#fff, #ccc);
color: #111;
}
| {
"content_hash": "2ad4315644c3ce7eef43e2f7d4335c20",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 91,
"avg_line_length": 26.095238095238095,
"alnum_prop": 0.6626115166261152,
"repo_name": "jesslilly/app-launcher.js",
"id": "d413de408e2364f22ced8694ce57d6228714583e",
"size": "4934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app-launcher/wwwroot/css/app-launcher.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "16740"
},
{
"name": "CSS",
"bytes": "5861"
},
{
"name": "HTML",
"bytes": "6663"
},
{
"name": "JavaScript",
"bytes": "6706"
}
],
"symlink_target": ""
} |
socialcrawler
=============
Social Crawler provides the ability of data retrieval from various social web sites in RDF format.
| {
"content_hash": "cab0e6e954fdba5c78a544bc0adf2d54",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 98,
"avg_line_length": 32,
"alnum_prop": 0.7421875,
"repo_name": "GalaksiyaIT/socialcrawler",
"id": "7eebd8f294a83d51c3c857388a466173cdd66e20",
"size": "128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "576263"
}
],
"symlink_target": ""
} |
class CreatePagesDomainAcmeOrders < ActiveRecord::Migration[5.1]
include Gitlab::Database::MigrationHelpers
# Set this constant to true if this migration requires downtime.
DOWNTIME = false
# rubocop:disable Migration/PreventStrings
# rubocop:disable Migration/AddLimitToTextColumns
def change
create_table :pages_domain_acme_orders do |t|
t.references :pages_domain, null: false, index: true, foreign_key: { on_delete: :cascade }, type: :integer
t.datetime_with_timezone :expires_at, null: false
t.timestamps_with_timezone null: false
t.string :url, null: false
t.string :challenge_token, null: false, index: true
t.text :challenge_file_content, null: false
t.text :encrypted_private_key, null: false
t.text :encrypted_private_key_iv, null: false
end
end
# rubocop:enable Migration/AddLimitToTextColumns
# rubocop:enable Migration/PreventStrings
end
| {
"content_hash": "0165db1d6117970ab8e1c479e49dd310",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 112,
"avg_line_length": 34.48148148148148,
"alnum_prop": 0.7271750805585392,
"repo_name": "mmkassem/gitlabhq",
"id": "75636031193d0e1fd47a66f8c528561e4f01d8f5",
"size": "1095",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "db/migrate/20190429082448_create_pages_domain_acme_orders.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113683"
},
{
"name": "CoffeeScript",
"bytes": "139197"
},
{
"name": "Cucumber",
"bytes": "119759"
},
{
"name": "HTML",
"bytes": "447030"
},
{
"name": "JavaScript",
"bytes": "29805"
},
{
"name": "Ruby",
"bytes": "2417833"
},
{
"name": "Shell",
"bytes": "14336"
}
],
"symlink_target": ""
} |
__author__ = 'Ahmad Syarif'
import pika
import json
class CommandHandler(object):
avatarKey = 'avatar.NAO.command'
def __init__(self):
credential = pika.PlainCredentials('lumen', 'lumen')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', credential))
self.channel = connection.channel()
pass
def sendCommand(self,command):
self.channel.basic_publish(exchange='amq.topic',routing_key=CommandHandler.avatarKey,body=command)
pass
def LS_say(self,toSay):
par = json.dumps({'text':toSay})
com = json.dumps({'type':'texttospeech','method':'say','parameter':{'text':toSay}})
self.sendCommand(command=com)
pass
def LS_goToPosture(self,posture,speed):
com = json.dumps({'type':'posture','method':'goToPosture','parameter':{'postureName':posture,'speed':speed}})
self.sendCommand(command=com)
pass
def LS_wakeUp(self):
com = json.dumps({'type':'motion','method':'wakeUp'})
self.sendCommand(command=com)
pass
def LS_rest(self):
com = json.dumps({'type':'motion','method':'rest'})
self.sendCommand(command=com)
pass
pass
| {
"content_hash": "bc1185d9d7dbacf1bf2d8df4bbecd0c6",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 117,
"avg_line_length": 39.67741935483871,
"alnum_prop": 0.6317073170731707,
"repo_name": "ahmadsyarif/Python-AgentIntelligent",
"id": "355866df24e63e98aeaccb91f7515367689c943a",
"size": "1230",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Command.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "12204"
}
],
"symlink_target": ""
} |
iOS version of: [Ping Pong Scoreboard "PPS"](https://github.com/jexia-inc/pingpong) based on the Jexia platform
#TODO: Contributing
**Guidelines to**:
* Coding Rules
* Commit
* Submitting a Pull Request
* Review
* Issues
| {
"content_hash": "e088508ca5f62b9fecce4487914c90fc",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 111,
"avg_line_length": 20.363636363636363,
"alnum_prop": 0.7366071428571429,
"repo_name": "jexia-inc/pingpong-ios",
"id": "847fd06ff37fb3142764f7fe85467f28f52e88fe",
"size": "239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
cp `ls -1 $xmm_rpcdata/*MOS1*ImagingEvts.ds` ./mos1evts_barycen.ds
cp $PWD/../src_evt.reg ./
# Make barycentric correction on the clean event file
barycen table=mos1evts_barycen.ds:EVENTS
# Get the coordinates from the .reg file
while read LINE
do
srcregion=$LINE
done < src_evt.reg
export srcregion
export mos1table=mos1evts_barycen.ds
export fsrcname="mos1evts_src_0310keV.ds"
export fimgname="mos1evts_src_img_0310keV.ds"
export emin=300
export emax=10000
source mos1selev.sh
export fsrcname="mos1evts_src_032keV.ds"
export fimgname="mos1evts_src_img_032keV.ds"
export emin=300
export emax=2000
source mos1selev.sh
export fsrcname="mos1evts_src_245keV.ds"
export fimgname="mos1evts_src_img_245keV.ds"
export emin=2000
export emax=4500
source mos1selev.sh
export fsrcname="mos1evts_src_4510keV.ds"
export fimgname="mos1evts_src_img_4510keV.ds"
export emin=4500
export emax=10000
source mos1selev.sh
| {
"content_hash": "c160585607f53e16a04f14024263cb85",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 66,
"avg_line_length": 24,
"alnum_prop": 0.7905701754385965,
"repo_name": "evandromr/bash_xmmscripts",
"id": "42415270810be760669f5d99f1e121a80840584c",
"size": "925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mos1/events/mos1eventscript.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "53820"
}
],
"symlink_target": ""
} |
class Post < ActiveRecord::Base
self.table_name = "wp_posts"
has_many :post_meta, :class_name => "PostMeta", :dependent => :destroy
has_many :tags
def self.clear_existing_listings
Post.delete_all("post_type = 'listing'")
end
def self.generate(properties, website)
properties.each do |property|
post = Post.new
post.post_date = post.post_date_gmt = post.post_modified = post.post_modified_gmt = DateTime.now
post.post_author = 1
post.post_type = 'listing'
post.post_name = property.id
post.guid = "#{website}/?post_type=listing&p=#{property.id}"
post.post_content = property.description
post.post_title = property.display_address
post.create_postmeta(property)
post.save!
post.reload
post.associate_taxonomy(property.location, 'property_location')
post.associate_taxonomy('#{buyorrent(property.trans_type_id)}', 'property_buyorrent')
post.associate_price_range(property.price)
property.photos.each do |photo|
attachment = Post.new
attachment.post_date = attachment.post_date_gmt = attachment.post_modified = attachment.post_modified_gmt = DateTime.now
attachment.post_author = 1
attachment.post_parent = post.id
attachment.post_type = 'attachment'
attachment.post_name = File.basename(photo.filename)
attachment.post_title = File.basename(photo.filename)
attachment.post_status = 'inherit'
attachment.post_mime_type = 'image/jpeg'
attachment.guid = photo.remote_url + "&width=300"
attachment.create_photo_meta(File.basename(photo.filename))
attachment.save!
end
end
end
def associate_price_range(price)
sql = %{
SELECT
wp_term_taxonomy.term_taxonomy_id,
wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'property_pricerange'
}
rows = self.connection.select_all(sql)
rows.each do |row|
boundaries = row["name"].split("-")
if price > boundaries[0].to_i && price < boundaries[1].to_i
sql = "INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES (#{self.id}, #{row["term_taxonomy_id"]})"
self.connection.execute(sql)
end
end
end
def associate_taxonomy(key, category)
return if key.blank?
key = Property.locate(key) if category == "property_location"
sql = %{
SELECT term_taxonomy_id
FROM wp_terms
JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE name = '#{key}' AND taxonomy = '#{category}'
}
taxonomy_id = self.connection.select_value(sql)
if taxonomy_id
sql = "INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES (#{self.id}, #{taxonomy_id})"
self.connection.execute(sql)
end
end
def create_photo_meta(filename)
self.post_meta.build({meta_key: '_wp_attached_file', meta_value: filename})
end
def create_postmeta(property)
entries = [
{meta_key: 'price_value', meta_value: property.price},
{meta_key: 'baths_value', meta_value: property.bathrooms},
{meta_key: 'cr_value', meta_value: 'Residential'},
{meta_key: 'google_location_value', meta_value: property.postcode},
{meta_key: 'beds_value', meta_value: property.bedrooms},
{meta_key: 'propertytype_value', meta_value: Property.classify(property.property_type.to_i)},
{meta_key: 'address_1_value', meta_value: property.address_1},
{meta_key: 'address_2_value', meta_value: property.address_2},
{meta_key: 'postcode_value', meta_value: property.postcode},
{meta_key: 'slideshow_value', meta_value: property.featured ? 'Yes' : 'No'},
{meta_key: 'rob_value', meta_value: 'Rent'},
{meta_key: 'streetview_value', meta_value: 'Yes'},
{meta_key: 'toolong_value', meta_value: 'No'},
{meta_key: 'location_level1_value', meta_value: Property.locate(property.location)},
{meta_key: 'citystatezip_value', meta_value: property.town},
{meta_key: 'deckpatio_value', meta_value: 'No Deck or Patio'}
]
entries.each_index do |i|
self.post_meta.build(entries[i])
end
end
def buyorrent(value)
if value == "1"
"Buy"
else
"Rent"
end
end
end
| {
"content_hash": "3b54875d333c5be372c2d31b85a7a56b",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 130,
"avg_line_length": 39.62608695652174,
"alnum_prop": 0.618608733816107,
"repo_name": "docteurdiam/dezrez",
"id": "025b19f966319f9ad048a1ef8430702a6fd37f2a",
"size": "4557",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dezrez/post.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "43879"
}
],
"symlink_target": ""
} |
package com.justwayward.reader.view.recyclerview.swipe;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
import android.widget.FrameLayout;
public class SwipeRefreshLayout extends FrameLayout {
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .5f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
// Whether or not the starting offset has been determined.
private boolean mOriginalOffsetCalculated = false;
private float mInitialMotionY;
private float mInitialDownY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private CircleImageView mCircleView;
private int mCircleViewIndex = -1;
protected int mFrom;
private float mStartingScale;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private Animation mScaleDownToStartAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
// Whether the client has set a custom starting position;
private boolean mUsingCustomStart;
private AnimationListener mRefreshListener = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh();
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
setColorViewAlpha(MAX_ALPHA);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop,
true /* requires update */);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
mScale = scale;
mCircleView.setVisibility(View.GONE);
mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
mSpinnerFinalOffset = end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
mTotalDragDistance = mSpinnerFinalOffset;
requestDisallowInterceptTouchEvent(true);
}
protected int getChildDrawingOrder(int childCount, int i) {
if (mCircleViewIndex < 0) {
return i;
} else if (i == childCount - 1) {
// Draw the selected child last
return mCircleViewIndex;
} else if (i >= mCircleViewIndex) {
// Move the children after the selected child earlier one
return i + 1;
} else {
// Keep the children before the selected child the same
return i;
}
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
mCircleView.setVisibility(View.GONE);
addView(mCircleView);
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset + mOriginalOffsetTop);
} else {
endTarget = (int) mSpinnerFinalOffset;
}
setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop,
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
mCircleView.setAnimationListener(listener);
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* @deprecated Use {@link #setProgressBackgroundColorSchemeResource(int)}
*/
@Deprecated
public void setProgressBackgroundColor(int colorRes) {
setProgressBackgroundColorSchemeResource(colorRes);
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColorSchemeResource(int colorRes) {
setProgressBackgroundColorSchemeColor(getResources().getColor(colorRes));
}
/**
* Set the background color of the progress spinner disc.
*
* @param color
*/
public void setProgressBackgroundColorSchemeColor(int color) {
mCircleView.setBackgroundColor(color);
mProgress.setBackgroundColor(color);
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getClass().isAssignableFrom(RecyclerView.class)) {
mTarget = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed,left,top,right,bottom);
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
mOriginalOffsetCalculated = true;
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
mCircleViewIndex = -1;
// Get the index of the circleview.
for (int index = 0; index < getChildCount(); index++) {
if (getChildAt(index) == mCircleView) {
mCircleViewIndex = index;
break;
}
}
}
/**
* Get the diameter of the progress circle that is displayed as part of the
* swipe to refresh layout. This is not valid until a measure pass has
* completed.
*
* @return Diameter in pixels of the progress circle view.
*/
public int getProgressCircleDiameter() {
return mCircleView != null ?mCircleView.getMeasuredHeight() : 0;
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
// //For make it can work when my recycler view is in Gone.
// return false;
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return ViewCompat.canScrollVertically(mTarget, -1) || mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialDownY = getMotionEventY(ev, mActivePointerId);
if (initialDownY == -1) {
return false;
}
mInitialDownY = initialDownY;
break;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
final float yDiff = y - mInitialDownY;
if (yDiff > mTouchSlop && !mIsBeingDragged) {
mInitialMotionY = mInitialDownY + mTouchSlop;
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
//Why Nope?
super.requestDisallowInterceptTouchEvent(b);
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset
- mOriginalOffsetTop : mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop
+ (int) ((slingshotDist * dragPercent) + extraMove);
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (!mScale) {
ViewCompat.setScaleX(mCircleView, 1f);
ViewCompat.setScaleY(mCircleView, 1f);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = adjustedPercent * .8f;
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
if (mActivePointerId == INVALID_POINTER) {
if (action == MotionEvent.ACTION_UP) {
Log.e(LOG_TAG, "Got ACTION_UP event but don't have an active pointer id.");
}
return false;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
AnimationListener listener = null;
if (!mScale) {
listener = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (!mScale) {
startScaleDownAnimation(null);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
}
animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
if (mScale) {
// Scale the item back down
startScaleDownReturnToStartAnimation(from, listener);
} else {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = 0;
if (!mUsingCustomStart) {
endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
} else {
endTarget = (int) mSpinnerFinalOffset;
}
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
mProgress.setArrowScale(1 - interpolatedTime);
}
};
private void moveToStart(float interpolatedTime) {
int targetTop = 0;
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
moveToStart(interpolatedTime);
}
};
private void startScaleDownReturnToStartAnimation(int from,
AnimationListener listener) {
mFrom = from;
if (isAlphaUsedForScale()) {
mStartingScale = mProgress.getAlpha();
} else {
mStartingScale = ViewCompat.getScaleX(mCircleView);
}
mScaleDownToStartAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime));
setAnimationProgress(targetScale);
moveToStart(interpolatedTime);
}
};
mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownToStartAnimation);
}
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
}
| {
"content_hash": "a665f026bc8a1780149f010b47bd621d",
"timestamp": "",
"source": "github",
"line_count": 921,
"max_line_length": 99,
"avg_line_length": 38.48751357220413,
"alnum_prop": 0.6021666149462578,
"repo_name": "weiwenqiang/GitHub",
"id": "d556b896a83c18304de5268c2af790eb7954483f",
"size": "36055",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "MVP/BookReader-master/app/src/main/java/com/justwayward/reader/view/recyclerview/swipe/SwipeRefreshLayout.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "87"
},
{
"name": "C",
"bytes": "42062"
},
{
"name": "C++",
"bytes": "12137"
},
{
"name": "CMake",
"bytes": "202"
},
{
"name": "CSS",
"bytes": "75087"
},
{
"name": "Clojure",
"bytes": "12036"
},
{
"name": "FreeMarker",
"bytes": "21704"
},
{
"name": "Groovy",
"bytes": "55083"
},
{
"name": "HTML",
"bytes": "61549"
},
{
"name": "Java",
"bytes": "42222825"
},
{
"name": "JavaScript",
"bytes": "216823"
},
{
"name": "Kotlin",
"bytes": "24319"
},
{
"name": "Makefile",
"bytes": "19490"
},
{
"name": "Perl",
"bytes": "280"
},
{
"name": "Prolog",
"bytes": "1030"
},
{
"name": "Python",
"bytes": "13032"
},
{
"name": "Scala",
"bytes": "310450"
},
{
"name": "Shell",
"bytes": "27802"
}
],
"symlink_target": ""
} |
๏ปฟ//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace JPAssetReader.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JPAssetReader.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon JPSkull {
get {
object obj = ResourceManager.GetObject("JPSkull", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap RexSkull {
get {
object obj = ResourceManager.GetObject("RexSkull", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| {
"content_hash": "04a1b5325da06cd741b8078798cea00c",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 179,
"avg_line_length": 42.59036144578313,
"alnum_prop": 0.5943422913719943,
"repo_name": "Stefander/JPMeshConverter",
"id": "c0aa93e2401a3f9d7ed19d01c056700a96a2f913",
"size": "3537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "D3DMeshConverter/Properties/Resources.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "65096"
}
],
"symlink_target": ""
} |
import * as Phaser from 'phaser'
import {BootState} from './states/boot.ts'
import {MenuState} from './states/menu.ts'
import {SplashState} from './states/splash.ts'
import {GameState} from './states/game.ts'
class Game extends Phaser.Game {
constructor() {
let width = 160;
let height = 144;
super(width, height, Phaser.CANVAS, 'content', null)
this.state.add('Boot', BootState)
this.state.add('Splash', SplashState)
this.state.add('Menu', MenuState)
this.state.add('Game', GameState)
this.state.start('Boot')
}
}
new Game()
| {
"content_hash": "6d65475f83eb56a6a62733567626798d",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 60,
"avg_line_length": 24.2,
"alnum_prop": 0.628099173553719,
"repo_name": "QuipHop/codeinemassacre",
"id": "041234ae21f2951439a3ff8838bb657c8617575f",
"size": "696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1898"
},
{
"name": "JavaScript",
"bytes": "3271156"
},
{
"name": "TypeScript",
"bytes": "35590"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>actuary: 52 s ๐</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.15.1 / actuary - 2.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">ยซ Up</a>
<h1>
actuary
<small>
2.2
<span class="label label-success">52 s ๐</span>
</small>
</h1>
<p>๐
<em><script>document.write(moment("2022-04-22 11:54:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-22 11:54:29 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-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.15.1 Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.12.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.1 Official release 4.12.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/Yosuke-Ito-345/Actuary"
dev-repo: "git+https://github.com/Yosuke-Ito-345/Actuary.git"
bug-reports: "https://github.com/Yosuke-Ito-345/Actuary/issues"
license: "MIT"
synopsis: "Formalization of actuarial mathematics in Coq"
description: """
This package formalizes basic actuarial mathematics using Coq and
the Mathematical Components and Coquelicot libraries. This includes
the theory of interest, life tables, annuities, and reserves."""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"coq" {>= "8.12"}
"coq-mathcomp-ssreflect" {>= "1.12"}
"coq-coquelicot" {>= "3.1.0"}
]
tags: [
"category:Mathematics/Real Calculus and Topology"
"keyword:present value"
"keyword:life tables"
"keyword:annuities"
"keyword:reserves"
"keyword:actuarial mathematics"
"logpath:Actuary"
"date:2021-12-18"
]
authors: [
"Yosuke Ito"
]
url {
src: "https://github.com/Yosuke-Ito-345/Actuary/archive/v2.2.tar.gz"
checksum: "sha512=0805c63fa2eac6782716ff0f63fb59e125e24dff1ed6a8356d4020d5325b3e579ba5de548f7a1cec5832dd46d1e2892a43d841ee1f1e8f2affde305db498d1fc"
}
</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-actuary.2.2 coq.8.15.1</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-actuary.2.2 coq.8.15.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>4 m 59 s</dd>
</dl>
<h2>Install ๐</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-actuary.2.2 coq.8.15.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>52 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 3 M</p>
<ul>
<li>792 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Premium.glob</code></li>
<li>359 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Premium.vo</code></li>
<li>297 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Interest.glob</code></li>
<li>263 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Reserve.glob</code></li>
<li>247 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Basics.glob</code></li>
<li>227 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/LifeTable.glob</code></li>
<li>173 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Interest.vo</code></li>
<li>169 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Basics.vo</code></li>
<li>161 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/LifeTable.vo</code></li>
<li>133 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Reserve.vo</code></li>
<li>87 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Examples.glob</code></li>
<li>81 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Premium.v</code></li>
<li>80 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Examples.vo</code></li>
<li>35 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Basics.v</code></li>
<li>34 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Reserve.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/all_Actuary.vo</code></li>
<li>32 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Interest.v</code></li>
<li>30 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/LifeTable.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/Examples.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/all_Actuary.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.12.1/lib/coq/user-contrib/Actuary/all_Actuary.v</code></li>
</ul>
<h2>Uninstall ๐งน</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-actuary.2.2</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": "b9b01bc2bb56e9efea20a8bb8d45645d",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 159,
"avg_line_length": 49.234375,
"alnum_prop": 0.5689199196022426,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "c8e8d222f94152d36855cd08c3320164a3e5f1cc",
"size": "9478",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.12.1-2.0.8/released/8.15.1/actuary/2.2.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.