code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package com.nagopy.android.disablemanager2;
import android.os.Build;
import com.android.uiautomator.core.UiSelector;
@SuppressWarnings("unused")
public class UiSelectorBuilder {
private UiSelector uiSelector;
public UiSelector build() {
return uiSelector;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder() {
uiSelector = new UiSelector();
}
/**
* @since API Level 16
*/
public UiSelectorBuilder text(String text) {
uiSelector = uiSelector.text(text);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder textMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.textMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textStartsWith(String text) {
uiSelector = uiSelector.textStartsWith(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textContains(String text) {
uiSelector = uiSelector.textContains(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder className(String className) {
uiSelector = uiSelector.className(className);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder classNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.classNameMatches(regex);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder className(Class<?> type) {
uiSelector = uiSelector.className(type.getName());
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder description(String desc) {
uiSelector = uiSelector.description(desc);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder descriptionMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.descriptionMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionStartsWith(String desc) {
uiSelector = uiSelector.descriptionStartsWith(desc);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionContains(String desc) {
uiSelector = uiSelector.descriptionContains(desc);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceId(String id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceId(id);
}
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceIdMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceIdMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder index(final int index) {
uiSelector = uiSelector.index(index);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder instance(final int instance) {
uiSelector = uiSelector.instance(instance);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder enabled(boolean val) {
uiSelector = uiSelector.enabled(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focused(boolean val) {
uiSelector = uiSelector.focused(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focusable(boolean val) {
uiSelector = uiSelector.focusable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder scrollable(boolean val) {
uiSelector = uiSelector.scrollable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder selected(boolean val) {
uiSelector = uiSelector.selected(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder checked(boolean val) {
uiSelector = uiSelector.checked(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder clickable(boolean val) {
uiSelector = uiSelector.clickable(val);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder checkable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.checkable(val);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder longClickable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.longClickable(val);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder childSelector(UiSelector selector) {
uiSelector = uiSelector.childSelector(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder fromParent(UiSelector selector) {
uiSelector = uiSelector.fromParent(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder packageName(String name) {
uiSelector = uiSelector.packageName(name);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder packageNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.packageNameMatches(regex);
}
return this;
}
}
| 75py/DisableManager | uiautomator/src/main/java/com/nagopy/android/disablemanager2/UiSelectorBuilder.java | Java | apache-2.0 | 6,177 |
package com.salesmanager.shop.model.entity;
import java.io.Serializable;
public abstract class ReadableList implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int totalPages;//totalPages
private int number;//number of record in current page
private long recordsTotal;//total number of records in db
private int recordsFiltered;
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalCount) {
this.totalPages = totalCount;
}
public long getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
} | shopizer-ecommerce/shopizer | sm-shop-model/src/main/java/com/salesmanager/shop/model/entity/ReadableList.java | Java | apache-2.0 | 950 |
# coding: UTF-8
name 'ops_tcpdump_handler'
maintainer 'Operations Infrastructure Team - Cerner Innovation, Inc.'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Installs/Configures ops_tcpdump_handler'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.1.0'
supports 'ubuntu'
supports 'centos'
supports 'redhat'
depends 'runit', '~> 1.5'
| cerner/ops_tcpdump_handler | metadata.rb | Ruby | apache-2.0 | 444 |
/*
* @(#)file SASLOutputStream.java
* @(#)author Sun Microsystems, Inc.
* @(#)version 1.10
* @(#)lastedit 07/03/08
* @(#)build @BUILD_TAG_PLACEHOLDER@
*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and
* Distribution License("CDDL")(collectively, the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy of the
* License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the
* LEGAL_NOTICES folder that accompanied this code. See the License for the
* specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file found at
* http://opendmk.dev.java.net/legal_notices/licenses.txt
* or in the LEGAL_NOTICES folder that accompanied this code.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.
*
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
*
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding
*
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license."
*
* If you don't indicate a single choice of license, a recipient has the option
* to distribute your version of this file under either the CDDL or the GPL
* Version 2, or to extend the choice of license to its licensees as provided
* above. However, if you add GPL Version 2 code and therefore, elected the
* GPL Version 2 license, then the option applies only if the new code is made
* subject to such option by the copyright holder.
*
*/
package com.sun.jmx.remote.opt.security;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslServer;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.jmx.remote.opt.util.ClassLogger;
public class SASLOutputStream extends OutputStream {
private int rawSendSize = 65536;
private byte[] lenBuf = new byte[4]; // buffer for storing length
private OutputStream out; // underlying output stream
private SaslClient sc;
private SaslServer ss;
public SASLOutputStream(SaslClient sc, OutputStream out)
throws IOException {
super();
this.out = out;
this.sc = sc;
this.ss = null;
String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public SASLOutputStream(SaslServer ss, OutputStream out)
throws IOException {
super();
this.out = out;
this.ss = ss;
this.sc = null;
String str = (String) ss.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public void write(int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte)b;
write(buffer, 0, 1);
}
public void write(byte[] buffer, int offset, int total) throws IOException {
int count;
byte[] wrappedToken, saslBuffer;
// "Packetize" buffer to be within rawSendSize
if (logger.traceOn()) {
logger.trace("write", "Total size: " + total);
}
for (int i = 0; i < total; i += rawSendSize) {
// Calculate length of current "packet"
count = (total - i) < rawSendSize ? (total - i) : rawSendSize;
// Generate wrapped token
if (sc != null)
wrappedToken = sc.wrap(buffer, offset+i, count);
else
wrappedToken = ss.wrap(buffer, offset+i, count);
// Write out length
intToNetworkByteOrder(wrappedToken.length, lenBuf, 0, 4);
if (logger.traceOn()) {
logger.trace("write", "sending size: " + wrappedToken.length);
}
out.write(lenBuf, 0, 4);
// Write out wrapped token
out.write(wrappedToken, 0, wrappedToken.length);
}
}
public void close() throws IOException {
if (sc != null)
sc.dispose();
else
ss.dispose();
out.close();
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
private void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more " +
"than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "SASLOutputStream");
}
| nickman/heliosutils | src/main/java/com/sun/jmx/remote/opt/security/SASLOutputStream.java | Java | apache-2.0 | 5,384 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_17a.html">Class Test_AbaRouteValidator_17a</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_36860_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a.html?line=42657#src-42657" >testAbaNumberCheck_36860_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:46:26
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36860_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=9592#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=9592#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=9592#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | dcarda/aba.route.validator | target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a_testAbaNumberCheck_36860_bad_7eg.html | HTML | apache-2.0 | 10,987 |
# -*- coding:utf-8 -*-
#
# Copyright (c) 2017 mooncake. All Rights Reserved
####
# @brief
# @author Eric Yue ( [email protected] )
# @version 0.0.1
from distutils.core import setup
V = "0.7"
setup(
name = 'mooncake_utils',
packages = ['mooncake_utils'],
version = V,
description = 'just a useful utils for mooncake personal project.',
author = 'mooncake',
author_email = '[email protected]',
url = 'https://github.com/ericyue/mooncake_utils',
download_url = 'https://github.com/ericyue/mooncake_utils/archive/%s.zip' % V,
keywords = ['utils','data','machine-learning'], # arbitrary keywords
classifiers = [],
)
| ericyue/mooncake_utils | setup.py | Python | apache-2.0 | 646 |
function f1(a) {
try {
throw "x";
} catch (arguments) {
console.log(arguments);
}
}
f1(3);
| csgordon/SJS | jscomp/tests/scope7.js | JavaScript | apache-2.0 | 123 |
# Sorosporium hodsonii Zundel SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycologia 22(3): 152 (1930)
#### Original name
Sorosporium hodsonii Zundel
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Ustilaginomycetes/Urocystidiales/Glomosporiaceae/Thecaphora/Sorosporium hodsonii/README.md | Markdown | apache-2.0 | 206 |
#!/bin/bash
# Note: this requires the fix from:
# https://github.com/kubernetes/kubernetes/pull/24299
(
# Clean-up from previous run
kubectl delete rc app
kubectl delete secret creds
kubectl delete ServiceBroker mongodb-sb
kubectl delete ServiceInstance mongodb-instance1
kubectl delete ServiceBinding mongodb-instance1-binding1
kubectl delete thirdpartyresource service-broker.cncf.org
kubectl delete thirdpartyresource service-instance.cncf.org
kubectl delete thirdpartyresource service-binding.cncf.org
) > /dev/null 2>&1
kubectl get thirdpartyresources
set -ex
# First create the new resource types
kubectl create -f - <<-EOF
apiVersion: extensions/v1beta1
kind: ThirdPartyResource
metadata:
name: service-broker.cncf.org
versions:
- name: v1
EOF
kubectl create -f - <<-EOF
apiVersion: extensions/v1beta1
kind: ThirdPartyResource
metadata:
name: service-instance.cncf.org
versions:
- name: v1
EOF
kubectl create -f - <<-EOF
apiVersion: extensions/v1beta1
kind: ThirdPartyResource
metadata:
name: service-binding.cncf.org
versions:
- name: v1
EOF
sleep 10
# Verify everything is there
curl http://localhost:8080/apis/cncf.org/v1/namespaces/default/servicebrokers
curl http://localhost:8080/apis/cncf.org/v1/namespaces/default/serviceinstances
curl http://localhost:8080/apis/cncf.org/v1/namespaces/default/servicebindings
# New create instances of each type
kubectl create -f - <<-EOF
apiVersion: cncf.org/v1
kind: ServiceBroker
metadata:
name: mongodb-sb
EOF
kubectl create -f - <<-EOF
apiVersion: cncf.org/v1
kind: ServiceInstance
metadata:
name: mongodb-instance1
EOF
kubectl create -f - <<-EOF
apiVersion: cncf.org/v1
kind: ServiceBinding
metadata:
name: mongodb-instance1-binding1
creds:
user: john
password: letMeIn
EOF
# And the secret to hold our creds
kubectl create -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
name: creds
data:
vcap-services: eyAidXNlciI6ICJqb2huIiwgInBhc3N3b3JkIjogImxldE1lSW4iIH0=
type: myspecial/secret
EOF
sleep 10
# Now create the app with VCAP_SERVICES binding info
kubectl create -f - <<EOF
apiVersion: v1
kind: ReplicationController
metadata:
name: app
spec:
replicas: 1
selector:
version: v1.0
template:
metadata:
name: myserver
labels:
version: v1.0
spec:
containers:
- name: nginx
image: nginx
env:
- name: VCAP_SERVICES
valueFrom:
secretKeyRef:
name: creds
key: vcap-services
EOF
sleep 15
# Prove it worked
kubectl exec `kubectl get pods --template "{{ (index .items 0).metadata.name }}"` -- env
| MHBauer/servicebroker | k8s/sample.sh | Shell | apache-2.0 | 2,869 |
---
title: 集群感知的服务路由
description: 利用 Istio 的水平分割 EDS 来创建多集群网格。
weight: 85
keywords: [kubernetes,multicluster]
---
这个示例展示了如何使用[单一控制平面拓扑](/zh/docs/concepts/multicluster-deployments/#单一控制平面拓扑)配置一个多集群网格,并使用 Istio 的`水平分割 EDS(Endpoints Discovery Service,Endpoint 发现服务)`特性(在 Istio 1.1 中引入),通过 ingress gateway 将服务请求路由到 remote 集群。水平分割 EDS 使 Istio 可以基于请求来源的位置,将其路由到不同的 endpoint。
按照此示例中的说明,您将设置一个两集群网格,如下图所示:
{{< image width="80%" ratio="36.01%"
link="/docs/examples/multicluster/split-horizon-eds/diagram.svg"
caption="单个 Istio 控制平面配置水平分割 EDS,跨越多个 Kubernetes 集群" >}}
`local` 集群将运行 Istio Pilot 和其它 Istio 控制平面组件,而 `remote` 集群仅运行 Istio Citadel、Sidecar Injector 和 Ingress gateway。不需要 VPN 连接,不同集群中的工作负载之间也无需直接网络访问。
## 开始之前
除了安装 Istio 的先决条件之外,此示例还需要以下条件:
* 两个 Kubernetes 集群(称之为 `local` 和 `remote`)。
{{< warning >}}
为了运行此配置,要求必须可以从 `local` 集群访问 `remote` 集群的 Kubernetes API server。
{{< /warning >}}
* `kubectl` 命令使用 `--context` 参数,同时访问 `local` 和 `remote` 集群。请使用下列命令列出您的 context:
{{< text bash >}}
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
cluster1 cluster1 [email protected] default
cluster2 cluster2 [email protected] default
{{< /text >}}
* 使用配置的 context 名称导出以下环境变量:
{{< text bash >}}
$ export CTX_LOCAL=<KUBECONFIG_LOCAL_CONTEXT_NAME>
$ export CTX_REMOTE=<KUBECONFIG_REMOTE_CONTEXT_NAME>
{{< /text >}}
## 多集群设置示例
在此示例中,您将安装对控制平面和应用程序 pod 都启用了双向 TLS 的 Istio。为了共享根 CA,您将使用同一个来自 Istio 示例目录的证书,在 `local` 和 `remote` 集群上创建一个相同的 `cacerts` secret。
下面的说明还设置了 `remote` 集群,包含一个无 selector 的 service 和具有 `local` Istio ingress gateway 地址的 `istio-pilot.istio-system` endpoint。这将用于通过 ingress gateway 安全地访问 `local` pilot,而无需双向 TLS 终止。
### 配置 local 集群
1. 定义网格网络:
默认情况下 Istio 的 `global.meshNetworks` 值为空,但是您需要对其进行修改以为 `remote` 集群上的 endpoint 定义一个新的网络。修改 `install/kubernetes/helm/istio/values.yaml` 并添加一个 `network2` 定义:
{{< text yaml >}}
meshNetworks:
network2:
endpoints:
- fromRegistry: remote_kubecfg
gateways:
- address: 0.0.0.0
port: 443
{{< /text >}}
请注意,gateway address 被设置为 `0.0.0.0`。这是一个临时占位符,稍后将被更新为 `remote` 集群 gateway 的公共 IP 地址,此 gateway 将在下一小节中部署。
1. 使用 Helm 创建 Istio `local` deployment YAML:
{{< text bash >}}
$ helm template --namespace=istio-system \
--values @install/kubernetes/helm/istio/values.yaml@ \
--set global.mtls.enabled=true \
--set global.enableTracing=false \
--set security.selfSigned=false \
--set mixer.telemetry.enabled=false \
--set mixer.policy.enabled=false \
--set global.useMCP=false \
--set global.controlPlaneSecurityEnabled=true \
--set gateways.istio-egressgateway.enabled=false \
--set global.meshExpansion.enabled=true \
install/kubernetes/helm/istio > istio-auth.yaml
{{< /text >}}
1. 部署 Istio 到 `local` 集群:
{{< text bash >}}
$ kubectl create --context=$CTX_LOCAL ns istio-system
$ kubectl create --context=$CTX_LOCAL secret generic cacerts -n istio-system --from-file=samples/certs/ca-cert.pem --from-file=samples/certs/ca-key.pem --from-file=samples/certs/root-cert.pem --from-file=samples/certs/cert-chain.pem
$ for i in install/kubernetes/helm/istio-init/files/crd*yaml; do kubectl apply --context=$CTX_LOCAL -f $i; done
$ kubectl create --context=$CTX_LOCAL -f istio-auth.yaml
{{< /text >}}
通过检查 `local` pod 的状态等待其被拉起:
{{< text bash >}}
$ kubectl get pods --context=$CTX_LOCAL -n istio-system
{{< /text >}}
### 设置 remote 集群
1. 导出 `local` gateway 地址:
{{< text bash >}}
$ export LOCAL_GW_ADDR=$(kubectl get --context=$CTX_LOCAL svc --selector=app=istio-ingressgateway \
-n istio-system -o jsonpath="{.items[0].status.loadBalancer.ingress[0].ip}")
{{< /text >}}
此命令将值设置为 gateway 的公共 IP,但请注意,您也可以将其设置为一个 DNS 名称(如果有)。
1. 使用 Helm 创建 Istio `remote` deployment YAML:
{{< text bash >}}
$ helm template install/kubernetes/helm/istio-remote \
--name istio-remote \
--namespace=istio-system \
--set global.mtls.enabled=true \
--set global.enableTracing=false \
--set gateways.enabled=true \
--set gateways.istio-egressgateway.enabled=false \
--set gateways.istio-ingressgateway.enabled=true \
--set security.selfSigned=false \
--set global.controlPlaneSecurityEnabled=true \
--set global.createRemoteSvcEndpoints=true \
--set global.remotePilotCreateSvcEndpoint=true \
--set global.remotePilotAddress=${LOCAL_GW_ADDR} \
--set global.disablePolicyChecks=true \
--set global.policyCheckFailOpen=true \
--set gateways.istio-ingressgateway.env.ISTIO_META_NETWORK="network2" \
--set global.network="network2" > istio-remote-auth.yaml
{{< /text >}}
1. 部署 Istio 到 `remote` 集群:
{{< text bash >}}
$ kubectl create --context=$CTX_REMOTE ns istio-system
$ kubectl create --context=$CTX_REMOTE secret generic cacerts -n istio-system --from-file=samples/certs/ca-cert.pem --from-file=samples/certs/ca-key.pem --from-file=samples/certs/root-cert.pem --from-file=samples/certs/cert-chain.pem
$ kubectl create --context=$CTX_REMOTE -f istio-remote-auth.yaml
{{< /text >}}
通过检查 `remote` pod 的状态等待其被拉起:
{{< text bash >}}
$ kubectl get pods --context=$CTX_REMOTE -n istio-system
{{< /text >}}
1. 更新网格网络配置中的 gateway 地址:
* 确定 `remote` 网关地址:
{{< text bash >}}
$ kubectl get --context=$CTX_REMOTE svc --selector=app=istio-ingressgateway -n istio-system -o jsonpath="{.items[0].status.loadBalancer.ingress[0].ip}"
169.61.102.93
{{< /text >}}
* 编辑 istio configmap:
{{< text bash >}}
$ kubectl edit cm -n istio-system --context=$CTX_LOCAL istio
{{< /text >}}
* 将 `network2` 的 gateway address 从 `0.0.0.0` 修改为 `remote` gateway 地址,保存并退出。
一旦保存,Pilot 将自动读取并更新网络配置。
1. 准备环境变量以构建 service account `istio-multi` 的 `remote_kubecfg` 文件:
{{< text bash >}}
$ CLUSTER_NAME=$(kubectl --context=$CTX_REMOTE config view --minify=true -o "jsonpath={.clusters[].name}")
$ SERVER=$(kubectl --context=$CTX_REMOTE config view --minify=true -o "jsonpath={.clusters[].cluster.server}")
$ SECRET_NAME=$(kubectl --context=$CTX_REMOTE get sa istio-multi -n istio-system -o jsonpath='{.secrets[].name}')
$ CA_DATA=$(kubectl get --context=$CTX_REMOTE secret ${SECRET_NAME} -n istio-system -o "jsonpath={.data['ca\.crt']}")
$ TOKEN=$(kubectl get --context=$CTX_REMOTE secret ${SECRET_NAME} -n istio-system -o "jsonpath={.data['token']}" | base64 --decode)
{{< /text >}}
{{< idea >}}
许多系统上使用 `openssl enc -d -base64 -A` 替代 `base64 --decode`。
{{< /idea >}}
1. 在工作目录创建 `remote_kubecfg` 文件:
{{< text bash >}}
$ cat <<EOF > remote_kubecfg
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: ${CA_DATA}
server: ${SERVER}
name: ${CLUSTER_NAME}
contexts:
- context:
cluster: ${CLUSTER_NAME}
user: ${CLUSTER_NAME}
name: ${CLUSTER_NAME}
current-context: ${CLUSTER_NAME}
kind: Config
preferences: {}
users:
- name: ${CLUSTER_NAME}
user:
token: ${TOKEN}
EOF
{{< /text >}}
### 开始监听 remote 集群
执行下列命令,添加并标记 `remote` Kubernetes 的 secret。执行这些命令之后,local Istio Pilot 将开始监听 `remote` 集群的 service 和 instance,就像在 `local` 集群中一样。
{{< text bash >}}
$ kubectl create --context=$CTX_LOCAL secret generic iks --from-file remote_kubecfg -n istio-system
$ kubectl label --context=$CTX_LOCAL secret iks istio/multiCluster=true -n istio-system
{{< /text >}}
现在您已经设置了 `local` 和 `remote` 集群,可以开始部署示例 service。
## 示例 service
在这个实例中,您将了解到一个 service 的流量是如何被分发到 local endpoint 和 remote gateway。如上图所示,您将为 `helloworld` service 部署两个实例,一个在 `local` 集群,另一个在 `remote` 集群。两个实例的区别在于其 `helloworld` 镜像的版本。
### 在 remote 集群部署 helloworld v2
1. 使用 sidecar 自动注入标签创建一个 `sample` namespace:
{{< text bash >}}
$ kubectl create --context=$CTX_REMOTE ns sample
$ kubectl label --context=$CTX_REMOTE namespace sample istio-injection=enabled
{{< /text >}}
1. 使用以下内容创建 `helloworld-v2.yaml` 文件:
{{< text yaml >}}
apiVersion: v1
kind: Service
metadata:
name: helloworld
labels:
app: helloworld
spec:
ports:
- port: 5000
name: http
selector:
app: helloworld
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: helloworld-v2
spec:
replicas: 1
template:
metadata:
labels:
app: helloworld
version: v2
spec:
containers:
- name: helloworld
image: istio/examples-helloworld-v2
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5000
{{< /text >}}
1. 部署此文件:
{{< text bash >}}
$ kubectl create --context=$CTX_REMOTE -f helloworld-v2.yaml -n sample
{{< /text >}}
### 在 local 集群部署 helloworld v1
1. 使用 sidecar 自动注入标签创建一个 `sample` namespace:
{{< text bash >}}
$ kubectl create --context=$CTX_LOCAL ns sample
$ kubectl label --context=$CTX_LOCAL namespace sample istio-injection=enabled
{{< /text >}}
1. 使用以下内容创建 `helloworld-v1.yaml` 文件:
{{< text yaml >}}
apiVersion: v1
kind: Service
metadata:
name: helloworld
labels:
app: helloworld
spec:
ports:
- port: 5000
name: http
selector:
app: helloworld
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: helloworld-v1
spec:
replicas: 1
template:
metadata:
labels:
app: helloworld
version: v1
spec:
containers:
- name: helloworld
image: istio/examples-helloworld-v1
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5000
{{< /text >}}
1. 使用下列内容创建 `helloworld-gateway.yaml` 文件:
{{< text yaml >}}
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: helloworld-gateway
namespace: sample
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 443
name: tls
protocol: TLS
tls:
mode: AUTO_PASSTHROUGH
hosts:
- "*"
{{< /text >}}
虽然是本地部署,这个 Gateway 实例仍然会影响 `remote` 集群,方法是将其配置为允许相关 remote service(基于 SNI)通过,但保持从源到目标 sidecar 的双向 TLS。
1. 部署此文件:
{{< text bash >}}
$ kubectl create --context=$CTX_LOCAL -f helloworld-v1.yaml -n sample
$ kubectl create --context=$CTX_LOCAL -f helloworld-gateway.yaml -n sample
{{< /text >}}
### 横向分割 EDS 实战
我们将从另一个集群中 `sleep` service 请求 `helloworld.sample` service。
1. 部署 `sleep` service:
{{< text bash >}}
$ kubectl create --context=$CTX_LOCAL -f @samples/sleep/sleep.yaml@ -n sample
{{< /text >}}
1. 多次请求 `helloworld.sample` service:
{{< text bash >}}
$ kubectl exec --context=$CTX_LOCAL -it -n sample $(kubectl get pod --context=$CTX_LOCAL -n sample -l app=sleep -o jsonpath={.items[0].metadata.name}) -- curl helloworld.sample:5000/hello
{{< /text >}}
如果设置正确,到 `helloworld.sample` service 的流量将在 local 和 remote 实例之间进行分发,导致响应 body 中 `v1` 或 `v2` 都可能出现。
{{< text bash >}}
$ kubectl exec --context=$CTX_LOCAL -it -n sample $(kubectl get pod --context=$CTX_LOCAL -n sample -l app=sleep -o jsonpath={.items[0].metadata.name}) -- curl helloworld.sample:5000/hello
Defaulting container name to sleep.
Use 'kubectl describe pod/sleep-57f9d6fd6b-q4k4h -n sample' to see all of the containers in this pod.
Hello version: v2, instance: helloworld-v2-758dd55874-6x4t8
{{< /text >}}
{{< text bash >}}
$ kubectl exec --context=$CTX_LOCAL -it -n sample $(kubectl get pod --context=$CTX_LOCAL -n sample -l app=sleep -o jsonpath={.items[0].metadata.name}) -- curl helloworld.sample:5000/hello
Defaulting container name to sleep.
Use 'kubectl describe pod/sleep-57f9d6fd6b-q4k4h -n sample' to see all of the containers in this pod.
Hello version: v1, instance: helloworld-v1-86f77cd7bd-cpxhv
{{< /text >}}
您可以通过打印 sleep pod 的 `istio-proxy` 容器日志来验证访问的 endpoint 的 IP 地址。
{{< text bash >}}
$ kubectl logs --context=$CTX_LOCAL -n sample $(kubectl get pod --context=$CTX_LOCAL -n sample -l app=sleep -o jsonpath={.items[0].metadata.name}) istio-proxy
[2018-11-25T12:37:52.077Z] "GET /hello HTTP/1.1" 200 - 0 60 190 189 "-" "curl/7.60.0" "6e096efe-f550-4dfa-8c8c-ba164baf4679" "helloworld.sample:5000" "192.23.120.32:443" outbound|5000||helloworld.sample.svc.cluster.local - 10.20.194.146:5000 10.10.0.89:59496 -
[2018-11-25T12:38:06.745Z] "GET /hello HTTP/1.1" 200 - 0 60 171 170 "-" "curl/7.60.0" "6f93c9cc-d32a-4878-b56a-086a740045d2" "helloworld.sample:5000" "10.10.0.90:5000" outbound|5000||helloworld.sample.svc.cluster.local - 10.20.194.146:5000 10.10.0.89:59646 -
{{< /text >}}
v2 被调用时将记录 remote gateway IP `192.23.120.32:443`,v1 被调用时将记录 local 实例 IP `10.10.0.90:5000`。
## 清理
执行下列命令清理 demo service __和__ Istio 组件。
清理 `remote` 集群:
{{< text bash >}}
$ kubectl delete --context=$CTX_REMOTE -f istio-remote-auth.yaml
$ kubectl delete --context=$CTX_REMOTE ns istio-system
$ kubectl delete --context=$CTX_REMOTE -f helloworld-v2.yaml -n sample
$ kubectl delete --context=$CTX_REMOTE ns sample
{{< /text >}}
清理 `local` 集群:
{{< text bash >}}
$ kubectl delete --context=$CTX_LOCAL -f istio-auth.yaml
$ kubectl delete --context=$CTX_LOCAL ns istio-system
$ helm delete --purge --kube-context=$CTX_LOCAL istio-init
$ kubectl delete --context=$CTX_LOCAL -f helloworld-v1.yaml -n sample
$ kubectl delete --context=$CTX_LOCAL -f @samples/sleep/sleep.yaml@ -n sample
$ kubectl delete --context=$CTX_LOCAL ns sample
{{< /text >}}
| geeknoid/istio.github.io | content_zh/docs/examples/multicluster/split-horizon-eds/index.md | Markdown | apache-2.0 | 16,049 |
# Copyright 2014 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import copy
import datetime
import re
import mock
import six
from osprofiler import profiler
from osprofiler.tests import test
class ProfilerGlobMethodsTestCase(test.TestCase):
def test_get_profiler_not_inited(self):
profiler.clean()
self.assertIsNone(profiler.get())
def test_get_profiler_and_init(self):
p = profiler.init("secret", base_id="1", parent_id="2")
self.assertEqual(profiler.get(), p)
self.assertEqual(p.get_base_id(), "1")
# NOTE(boris-42): until we make first start we don't have
self.assertEqual(p.get_id(), "2")
def test_start_not_inited(self):
profiler.clean()
profiler.start("name")
def test_start(self):
p = profiler.init("secret", base_id="1", parent_id="2")
p.start = mock.MagicMock()
profiler.start("name", info="info")
p.start.assert_called_once_with("name", info="info")
def test_stop_not_inited(self):
profiler.clean()
profiler.stop()
def test_stop(self):
p = profiler.init("secret", base_id="1", parent_id="2")
p.stop = mock.MagicMock()
profiler.stop(info="info")
p.stop.assert_called_once_with(info="info")
class ProfilerTestCase(test.TestCase):
def test_profiler_get_shorten_id(self):
uuid_id = "4e3e0ec6-2938-40b1-8504-09eb1d4b0dee"
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
result = prof.get_shorten_id(uuid_id)
expected = "850409eb1d4b0dee"
self.assertEqual(expected, result)
def test_profiler_get_shorten_id_int(self):
short_id_int = 42
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
result = prof.get_shorten_id(short_id_int)
expected = "2a"
self.assertEqual(expected, result)
def test_profiler_get_base_id(self):
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
self.assertEqual(prof.get_base_id(), "1")
@mock.patch("osprofiler.profiler.uuidutils.generate_uuid")
def test_profiler_get_parent_id(self, mock_generate_uuid):
mock_generate_uuid.return_value = "42"
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
prof.start("test")
self.assertEqual(prof.get_parent_id(), "2")
@mock.patch("osprofiler.profiler.uuidutils.generate_uuid")
def test_profiler_get_base_id_unset_case(self, mock_generate_uuid):
mock_generate_uuid.return_value = "42"
prof = profiler._Profiler("secret")
self.assertEqual(prof.get_base_id(), "42")
self.assertEqual(prof.get_parent_id(), "42")
@mock.patch("osprofiler.profiler.uuidutils.generate_uuid")
def test_profiler_get_id(self, mock_generate_uuid):
mock_generate_uuid.return_value = "43"
prof = profiler._Profiler("secret")
prof.start("test")
self.assertEqual(prof.get_id(), "43")
@mock.patch("osprofiler.profiler.datetime")
@mock.patch("osprofiler.profiler.uuidutils.generate_uuid")
@mock.patch("osprofiler.profiler.notifier.notify")
def test_profiler_start(self, mock_notify, mock_generate_uuid,
mock_datetime):
mock_generate_uuid.return_value = "44"
now = datetime.datetime.utcnow()
mock_datetime.datetime.utcnow.return_value = now
info = {"some": "info"}
payload = {
"name": "test-start",
"base_id": "1",
"parent_id": "2",
"trace_id": "44",
"info": info,
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%S.%f"),
}
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
prof.start("test", info=info)
mock_notify.assert_called_once_with(payload)
@mock.patch("osprofiler.profiler.datetime")
@mock.patch("osprofiler.profiler.notifier.notify")
def test_profiler_stop(self, mock_notify, mock_datetime):
now = datetime.datetime.utcnow()
mock_datetime.datetime.utcnow.return_value = now
prof = profiler._Profiler("secret", base_id="1", parent_id="2")
prof._trace_stack.append("44")
prof._name.append("abc")
info = {"some": "info"}
prof.stop(info=info)
payload = {
"name": "abc-stop",
"base_id": "1",
"parent_id": "2",
"trace_id": "44",
"info": info,
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%S.%f"),
}
mock_notify.assert_called_once_with(payload)
self.assertEqual(len(prof._name), 0)
self.assertEqual(prof._trace_stack, collections.deque(["1", "2"]))
def test_profiler_hmac(self):
hmac = "secret"
prof = profiler._Profiler(hmac, base_id="1", parent_id="2")
self.assertEqual(hmac, prof.hmac_key)
class WithTraceTestCase(test.TestCase):
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_with_trace(self, mock_start, mock_stop):
with profiler.Trace("a", info="a1"):
mock_start.assert_called_once_with("a", info="a1")
mock_start.reset_mock()
with profiler.Trace("b", info="b1"):
mock_start.assert_called_once_with("b", info="b1")
mock_stop.assert_called_once_with()
mock_stop.reset_mock()
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_with_trace_etype(self, mock_start, mock_stop):
def foo():
with profiler.Trace("foo"):
raise ValueError("bar")
self.assertRaises(ValueError, foo)
mock_start.assert_called_once_with("foo", info=None)
mock_stop.assert_called_once_with(info={
"etype": "ValueError",
"message": "bar"
})
@profiler.trace("function", info={"info": "some_info"})
def traced_func(i):
return i
@profiler.trace("hide_args", hide_args=True)
def trace_hide_args_func(a, i=10):
return (a, i)
@profiler.trace("foo", hide_args=True)
def test_fn_exc():
raise ValueError()
@profiler.trace("hide_result", hide_result=False)
def trace_with_result_func(a, i=10):
return (a, i)
class TraceDecoratorTestCase(test.TestCase):
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_duplicate_trace_disallow(self, mock_start, mock_stop):
@profiler.trace("test")
def trace_me():
pass
self.assertRaises(
ValueError,
profiler.trace("test-again", allow_multiple_trace=False),
trace_me)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_with_args(self, mock_start, mock_stop):
self.assertEqual(1, traced_func(1))
expected_info = {
"info": "some_info",
"function": {
"name": "osprofiler.tests.unit.test_profiler.traced_func",
"args": str((1,)),
"kwargs": str({})
}
}
mock_start.assert_called_once_with("function", info=expected_info)
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_without_args(self, mock_start, mock_stop):
self.assertEqual((1, 2), trace_hide_args_func(1, i=2))
expected_info = {
"function": {
"name": "osprofiler.tests.unit.test_profiler"
".trace_hide_args_func"
}
}
mock_start.assert_called_once_with("hide_args", info=expected_info)
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_with_exception(self, mock_start, mock_stop):
self.assertRaises(ValueError, test_fn_exc)
expected_info = {
"function": {
"name": "osprofiler.tests.unit.test_profiler.test_fn_exc"
}
}
expected_stop_info = {"etype": "ValueError", "message": ""}
mock_start.assert_called_once_with("foo", info=expected_info)
mock_stop.assert_called_once_with(info=expected_stop_info)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_with_result(self, mock_start, mock_stop):
self.assertEqual((1, 2), trace_with_result_func(1, i=2))
start_info = {
"function": {
"name": "osprofiler.tests.unit.test_profiler"
".trace_with_result_func",
"args": str((1,)),
"kwargs": str({"i": 2})
}
}
stop_info = {
"function": {
"result": str((1, 2))
}
}
mock_start.assert_called_once_with("hide_result", info=start_info)
mock_stop.assert_called_once_with(info=stop_info)
class FakeTracedCls(object):
def method1(self, a, b, c=10):
return a + b + c
def method2(self, d, e):
return d - e
def method3(self, g=10, h=20):
return g * h
def _method(self, i):
return i
@profiler.trace_cls("rpc", info={"a": 10})
class FakeTraceClassWithInfo(FakeTracedCls):
pass
@profiler.trace_cls("a", info={"b": 20}, hide_args=True)
class FakeTraceClassHideArgs(FakeTracedCls):
pass
@profiler.trace_cls("rpc", trace_private=True)
class FakeTracePrivate(FakeTracedCls):
pass
class FakeTraceStaticMethodBase(FakeTracedCls):
@staticmethod
def static_method(arg):
return arg
@profiler.trace_cls("rpc", trace_static_methods=True)
class FakeTraceStaticMethod(FakeTraceStaticMethodBase):
pass
@profiler.trace_cls("rpc")
class FakeTraceStaticMethodSkip(FakeTraceStaticMethodBase):
pass
class FakeTraceClassMethodBase(FakeTracedCls):
@classmethod
def class_method(cls, arg):
return arg
@profiler.trace_cls("rpc")
class FakeTraceClassMethodSkip(FakeTraceClassMethodBase):
pass
def py3_info(info):
# NOTE(boris-42): py33 I hate you.
info_py3 = copy.deepcopy(info)
new_name = re.sub("FakeTrace[^.]*", "FakeTracedCls",
info_py3["function"]["name"])
info_py3["function"]["name"] = new_name
return info_py3
def possible_mock_calls(name, info):
# NOTE(boris-42): py33 I hate you.
return [mock.call(name, info=info), mock.call(name, info=py3_info(info))]
class TraceClsDecoratorTestCase(test.TestCase):
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_args(self, mock_start, mock_stop):
fake_cls = FakeTraceClassWithInfo()
self.assertEqual(30, fake_cls.method1(5, 15))
expected_info = {
"a": 10,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceClassWithInfo.method1"),
"args": str((fake_cls, 5, 15)),
"kwargs": str({})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_kwargs(self, mock_start, mock_stop):
fake_cls = FakeTraceClassWithInfo()
self.assertEqual(50, fake_cls.method3(g=5, h=10))
expected_info = {
"a": 10,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceClassWithInfo.method3"),
"args": str((fake_cls,)),
"kwargs": str({"g": 5, "h": 10})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_without_private(self, mock_start, mock_stop):
fake_cls = FakeTraceClassHideArgs()
self.assertEqual(10, fake_cls._method(10))
self.assertFalse(mock_start.called)
self.assertFalse(mock_stop.called)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_without_args(self, mock_start, mock_stop):
fake_cls = FakeTraceClassHideArgs()
self.assertEqual(40, fake_cls.method1(5, 15, c=20))
expected_info = {
"b": 20,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceClassHideArgs.method1"),
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("a", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_private_methods(self, mock_start, mock_stop):
fake_cls = FakeTracePrivate()
self.assertEqual(5, fake_cls._method(5))
expected_info = {
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTracePrivate._method"),
"args": str((fake_cls, 5)),
"kwargs": str({})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
@test.testcase.skip(
"Static method tracing was disabled due the bug. This test should be "
"skipped until we find the way to address it.")
def test_static(self, mock_start, mock_stop):
fake_cls = FakeTraceStaticMethod()
self.assertEqual(25, fake_cls.static_method(25))
expected_info = {
"function": {
# fixme(boris-42): Static methods are treated differently in
# Python 2.x and Python 3.x. So in PY2 we
# expect to see method4 because method is
# static and doesn't have reference to class
# - and FakeTraceStatic.method4 in PY3
"name":
"osprofiler.tests.unit.test_profiler"
".method4" if six.PY2 else
"osprofiler.tests.unit.test_profiler.FakeTraceStatic"
".method4",
"args": str((25,)),
"kwargs": str({})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_static_method_skip(self, mock_start, mock_stop):
self.assertEqual(25, FakeTraceStaticMethodSkip.static_method(25))
self.assertFalse(mock_start.called)
self.assertFalse(mock_stop.called)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_class_method_skip(self, mock_start, mock_stop):
self.assertEqual("foo", FakeTraceClassMethodSkip.class_method("foo"))
self.assertFalse(mock_start.called)
self.assertFalse(mock_stop.called)
@six.add_metaclass(profiler.TracedMeta)
class FakeTraceWithMetaclassBase(object):
__trace_args__ = {"name": "rpc",
"info": {"a": 10}}
def method1(self, a, b, c=10):
return a + b + c
def method2(self, d, e):
return d - e
def method3(self, g=10, h=20):
return g * h
def _method(self, i):
return i
class FakeTraceDummy(FakeTraceWithMetaclassBase):
def method4(self, j):
return j
class FakeTraceWithMetaclassHideArgs(FakeTraceWithMetaclassBase):
__trace_args__ = {"name": "a",
"info": {"b": 20},
"hide_args": True}
def method5(self, k, l):
return k + l
class FakeTraceWithMetaclassPrivate(FakeTraceWithMetaclassBase):
__trace_args__ = {"name": "rpc",
"trace_private": True}
def _new_private_method(self, m):
return 2 * m
class TraceWithMetaclassTestCase(test.TestCase):
def test_no_name_exception(self):
def define_class_with_no_name():
@six.add_metaclass(profiler.TracedMeta)
class FakeTraceWithMetaclassNoName(FakeTracedCls):
pass
self.assertRaises(TypeError, define_class_with_no_name, 1)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_args(self, mock_start, mock_stop):
fake_cls = FakeTraceWithMetaclassBase()
self.assertEqual(30, fake_cls.method1(5, 15))
expected_info = {
"a": 10,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceWithMetaclassBase.method1"),
"args": str((fake_cls, 5, 15)),
"kwargs": str({})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_kwargs(self, mock_start, mock_stop):
fake_cls = FakeTraceWithMetaclassBase()
self.assertEqual(50, fake_cls.method3(g=5, h=10))
expected_info = {
"a": 10,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceWithMetaclassBase.method3"),
"args": str((fake_cls,)),
"kwargs": str({"g": 5, "h": 10})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_without_private(self, mock_start, mock_stop):
fake_cls = FakeTraceWithMetaclassHideArgs()
self.assertEqual(10, fake_cls._method(10))
self.assertFalse(mock_start.called)
self.assertFalse(mock_stop.called)
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_without_args(self, mock_start, mock_stop):
fake_cls = FakeTraceWithMetaclassHideArgs()
self.assertEqual(20, fake_cls.method5(5, 15))
expected_info = {
"b": 20,
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceWithMetaclassHideArgs.method5")
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("a", expected_info))
mock_stop.assert_called_once_with()
@mock.patch("osprofiler.profiler.stop")
@mock.patch("osprofiler.profiler.start")
def test_private_methods(self, mock_start, mock_stop):
fake_cls = FakeTraceWithMetaclassPrivate()
self.assertEqual(10, fake_cls._new_private_method(5))
expected_info = {
"function": {
"name": ("osprofiler.tests.unit.test_profiler"
".FakeTraceWithMetaclassPrivate._new_private_method"),
"args": str((fake_cls, 5)),
"kwargs": str({})
}
}
self.assertEqual(1, len(mock_start.call_args_list))
self.assertIn(mock_start.call_args_list[0],
possible_mock_calls("rpc", expected_info))
mock_stop.assert_called_once_with()
| stackforge/osprofiler | osprofiler/tests/unit/test_profiler.py | Python | apache-2.0 | 21,196 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ja">
<head>
<!-- Generated by javadoc (1.8.0_242) on Fri Aug 21 11:53:10 JST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>クラス jp.cafebabe.pochi.core.config.Valueの使用 (pochi: extensible birthmark toolkit 1.0.0 API)</title>
<meta name="date" content="2020-08-21">
<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="\u30AF\u30E9\u30B9 jp.cafebabe.pochi.core.config.Value\u306E\u4F7F\u7528 (pochi: extensible birthmark toolkit 1.0.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>ブラウザのJavaScriptが無効になっています。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="ナビゲーション・リンクをスキップ">ナビゲーション・リンクをスキップ</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="ナビゲーション">
<li><a href="../../../../../../overview-summary.html">概要</a></li>
<li><a href="../package-summary.html">パッケージ</a></li>
<li><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/Value.html" title="jp.cafebabe.pochi.core.config内のクラス">クラス</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">階層ツリー</a></li>
<li><a href="../../../../../../deprecated-list.html">非推奨</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">ヘルプ</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>前</li>
<li>次</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?jp/cafebabe/pochi/birthmarks/config/class-use/Value.html" target="_top">フレーム</a></li>
<li><a href="Value.html" target="_top">フレームなし</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">すべてのクラス</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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="クラスの使用 jp.cafebabe.pochi.core.config.Value" class="title">クラスの使用<br>jp.cafebabe.pochi.birthmarks.config.Value</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="表、パッケージのリストおよび説明の使用">
<caption><span><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/Value.html" title="jp.cafebabe.pochi.core.config内のクラス">Value</a>を使用しているパッケージ</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">パッケージ</th>
<th class="colLast" scope="col">説明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#jp.cafebabe.pochi.core.config">jp.cafebabe.pochi.core.config</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="jp.cafebabe.pochi.core.config">
<!-- -->
</a>
<h3><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/package-summary.html">jp.cafebabe.pochi.core.config</a>での<a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/Value.html" title="jp.cafebabe.pochi.core.config内のクラス">Value</a>の使用</h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="表、サブクラスのリストおよび説明の使用">
<caption><span><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/package-summary.html">jp.cafebabe.pochi.core.config</a>での<a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/Value.html" title="jp.cafebabe.pochi.core.config内のクラス">Value</a>のサブクラス</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">修飾子とタイプ</th>
<th class="colLast" scope="col">クラスと説明</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/ItemKey.html" title="jp.cafebabe.pochi.core.config内のクラス">ItemKey</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/ItemValue.html" title="jp.cafebabe.pochi.core.config内のクラス">ItemValue</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="ナビゲーション・リンクをスキップ">ナビゲーション・リンクをスキップ</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="ナビゲーション">
<li><a href="../../../../../../overview-summary.html">概要</a></li>
<li><a href="../package-summary.html">パッケージ</a></li>
<li><a href="../../../../../../jp/cafebabe/pochi/birthmarks/config/Value.html" title="jp.cafebabe.pochi.core.config内のクラス">クラス</a></li>
<li class="navBarCell1Rev">使用</li>
<li><a href="../package-tree.html">階層ツリー</a></li>
<li><a href="../../../../../../deprecated-list.html">非推奨</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">ヘルプ</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>前</li>
<li>次</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?jp/cafebabe/pochi/birthmarks/config/class-use/Value.html" target="_top">フレーム</a></li>
<li><a href="Value.html" target="_top">フレームなし</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">すべてのクラス</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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020. All rights reserved.</small></p>
</body>
</html>
| tamada/pochi | v1.0.0/apidocs/jp/cafebabe/pochi/birthmarks/config/class-use/Value.html | HTML | apache-2.0 | 7,307 |
package blended.itestsupport.condition
import akka.testkit.{TestActorRef, TestProbe}
import blended.itestsupport.condition.ConditionActor.CheckCondition
import blended.itestsupport.condition.ConditionActor.ConditionCheckResult
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import akka.actor.ActorSystem
class ParallelCheckerSpec extends AnyWordSpec
with Matchers {
private implicit val system : ActorSystem = ActorSystem("ParallelChecker")
"The Condition Checker" should {
"respond with a satisfied message on an empty list of conditions" in {
val probe = TestProbe()
val checker = TestActorRef(ConditionActor.props(ParallelComposedCondition()))
checker.tell(CheckCondition, probe.ref)
probe.expectMsg(ConditionCheckResult(List.empty[Condition], List.empty[Condition]))
}
"respond with a satisfied message after a single wrapped condition has been satisfied" in {
val probe = TestProbe()
val conditions = (1 to 1).map { i => new AlwaysTrue() }.toList
val condition = ParallelComposedCondition(conditions.toSeq:_*)
val checker = TestActorRef(ConditionActor.props(condition))
checker.tell(CheckCondition, probe.ref)
probe.expectMsg(ConditionCheckResult(conditions, List.empty[Condition]))
}
"respond with a satisfied message after some wrapped conditions have been satisfied" in {
val probe = TestProbe()
val conditions = (1 to 5).map { i => new AlwaysTrue() }.toList
val condition = ParallelComposedCondition(conditions.toSeq:_*)
val checker = TestActorRef(ConditionActor.props(condition))
checker.tell(CheckCondition, probe.ref)
probe.expectMsg(ConditionCheckResult(conditions, List.empty[Condition]))
}
"respond with a timeout message after a single wrapped condition has timed out" in {
val probe = TestProbe()
val conditions = (1 to 1).map { i => new NeverTrue() }.toList
val condition = ParallelComposedCondition(conditions.toSeq:_*)
val checker = TestActorRef(ConditionActor.props(condition))
checker.tell(CheckCondition, probe.ref)
probe.expectMsg(ConditionCheckResult(List.empty[Condition], conditions))
}
"respond with a timeout message containing the timed out conditions only" in {
val probe = TestProbe()
val conditions = List(
new AlwaysTrue(),
new AlwaysTrue(),
new NeverTrue(),
new AlwaysTrue(),
new AlwaysTrue()
)
val condition = ParallelComposedCondition(conditions.toSeq:_*)
val checker = TestActorRef(ConditionActor.props(condition))
checker.tell(CheckCondition, probe.ref)
probe.expectMsg(ConditionCheckResult(
conditions.filter(_.isInstanceOf[AlwaysTrue]),
conditions.filter(_.isInstanceOf[NeverTrue])
))
}
}
}
| woq-blended/blended | blended.itestsupport/src/test/scala/blended/itestsupport/condition/ParallelCheckerSpec.scala | Scala | apache-2.0 | 2,881 |
<?php
namespace CultuurNet\UDB3\EventSourcing\DBAL;
class NonCompatibleUuid
{
/**
* @var string
*/
private $uuid;
/**
* DummyUuid constructor.
* @param string $uuid
*/
public function __construct($uuid)
{
$this->uuid = $uuid;
}
}
| cultuurnet/udb3-php | test/EventSourcing/DBAL/NonCompatibleUuid.php | PHP | apache-2.0 | 290 |
// JavaScript Document
var flag1=true;
var flag2=true;
$(function () {
/*********************/
$.ajax({
type : 'POST',
dataType : 'json',
url : 'baseNeiName.do',
async : true,
cache : false,
error : function(request) {
bootbox.alert({
message : "请求异常",
size : 'small'
});
},
success : function(data) {
var i = 0;
for ( var item in data) {
$("#baselistid").after(
"<option value="+data[i].id+">"
+ data[i].name + "</option>");
i++;
}
}
});
/**************************/
/*########*/
$(document).on("click", "#Submit", function() {
var projectname=$("#projectname").val();
var name=$("#name").val();
var address=$("#address").val();
var budget=$("#budget").val();
budget=budget.trim();
var baselist=$("#baselist").val();
var reason=$("#reason").val();
var strmoney=/^[0-9]*$/.test(budget);
var money=budget.substring(1,0);
if(projectname==""){
bootbox.alert({
message : "请填写项目名称",
size : 'small'
});
return 0;
}
else if(name==""){
bootbox.alert({
message : "请填写报修人",
size : 'small'
});
return 0;
}
else if(address==""){
bootbox.alert({
message : "请填写具体位置",
size : 'small'
});
return 0;
}
else if(budget==""){
bootbox.alert({
message : "请填写预算金额",
size : 'small'
});
return 0;
}
else if(strmoney==false){
bootbox.alert({
message : "预算金额只能为数字",
size : 'small'
});
return 0;
}
else if(budget.length>1&&money==0){
bootbox.alert({
message : "请填写正确的预算金额格式,第一个数字不能为零",
size : 'small'
});
return 0;
}
else if(baselist=="请选择"){
bootbox.alert({
message : "请选择基地",
size : 'small'
});
return 0;
}
else if(reason==""){
bootbox.alert({
message : "请填写原因",
size : 'small'
});
return 0;
}
if (!flag1) {
bootbox.alert({
message: "上传资料仅限于rar,zip压缩包格式",
size: 'small'
});
$("#applyfile").val('');
return;
}
if (!flag2) {
bootbox.alert({
message: "上传资料大小不能大于10M",
size: 'small'
});
$("#applyfile").val('');
return;
}
/*************/
$("#applyform").submit();
/*************/
})
$('#applyfile').change(function() {
var filepath = $(this).val();
var file_size = this.files[0].size;
var size = file_size / 1024;
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".RAR" && ext != ".ZIP") {
bootbox.alert({
message: "上传资料仅限于rar,zip压缩包格式",
size: 'small'
});
$("#applyfile").val('');
flag1=false;
return;
}
if (size > 1024 * 10) {
bootbox.alert({
message: "上传资料大小不能大于10M",
size: 'small'
});
$("#applyfile").val('');
flag2=false;
return;
}
flag1=true;
flag2=true;
});
/*########*/
}); | pange123/PB_Management | 后台页面/WebRoot/js/myNeed/Repairpply.js | JavaScript | apache-2.0 | 3,500 |
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Spark NLP 3.4.2 ScalaDoc - com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask</title>
<meta name="description" content="Spark NLP 3.4.2 ScalaDoc - com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask" />
<meta name="keywords" content="Spark NLP 3.4.2 ScalaDoc com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../../../lib/jquery.min.js"></script>
<script type="text/javascript" src="../../../../../lib/jquery.panzoom.min.js"></script>
<script type="text/javascript" src="../../../../../lib/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="../../../../../lib/index.js"></script>
<script type="text/javascript" src="../../../../../index.js"></script>
<script type="text/javascript" src="../../../../../lib/scheduler.js"></script>
<script type="text/javascript" src="../../../../../lib/template.js"></script>
<script type="text/javascript">
/* this variable can be used by the JS to determine the path to the root document */
var toRoot = '../../../../../';
</script>
</head>
<body>
<div id="search">
<span id="doc-title">Spark NLP 3.4.2 ScalaDoc<span id="doc-version"></span></span>
<span class="close-results"><span class="left"><</span> Back</span>
<div id="textfilter">
<span class="input">
<input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
<i class="clear material-icons"></i>
<i id="search-icon" class="material-icons"></i>
</span>
</div>
</div>
<div id="search-results">
<div id="search-progress">
<div id="progress-fill"></div>
</div>
<div id="results-content">
<div id="entity-results"></div>
<div id="member-results"></div>
</div>
</div>
<div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;">
<div id="content-container" style="-webkit-overflow-scrolling: touch;">
<div id="subpackage-spacer">
<div id="packages">
<h1>Packages</h1>
<ul>
<li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="_root_"></a><a id="root:_root_"></a>
<span class="permalink">
<a href="../../../../../index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../../../../index.html"><span class="name">root</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="_root_.com" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="com"></a><a id="com:com"></a>
<span class="permalink">
<a href="../../../../../com/index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../../../index.html"><span class="name">com</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="com.johnsnowlabs" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="johnsnowlabs"></a><a id="johnsnowlabs:johnsnowlabs"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../../index.html"><span class="name">johnsnowlabs</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../../index.html" class="extype" name="com">com</a></dd></dl></div>
</li><li name="com.johnsnowlabs.ml" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ml"></a><a id="ml:ml"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../index.html"><span class="name">ml</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="com.johnsnowlabs">johnsnowlabs</a></dd></dl></div>
</li><li name="com.johnsnowlabs.ml.tensorflow" visbl="pub" class="indented4 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="tensorflow"></a><a id="tensorflow:tensorflow"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../index.html"><span class="name">tensorflow</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="com.johnsnowlabs.ml">ml</a></dd></dl></div>
</li><li name="com.johnsnowlabs.ml.tensorflow.sign" visbl="pub" class="indented5 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="sign"></a><a id="sign:sign"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/index.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="index.html"><span class="name">sign</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="com.johnsnowlabs.ml.tensorflow">tensorflow</a></dd></dl></div>
</li><li name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants" visbl="pub" class="indented6 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ModelSignatureConstants"></a><a id="ModelSignatureConstants:ModelSignatureConstants"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<a title="Based on BERT SavedModel reference, for instance:" href="ModelSignatureConstants$.html"><span class="name">ModelSignatureConstants</span></a>
</span>
<p class="shortcomment cmt">Based on BERT SavedModel reference, for instance:</p><div class="fullcomment"><div class="comment cmt"><p>Based on BERT SavedModel reference, for instance:</p><p>signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):</p><p>inputs['attention_mask'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: serving_default_attention_mask:0</p><p>inputs['input_ids'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: serving_default_input_ids:0</p><p>inputs['token_type_ids'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: serving_default_token_type_ids:0</p><p>The given SavedModel SignatureDef contains the following output(s):</p><p>outputs['last_hidden_state'] tensor_info:
dtype: DT_FLOAT
shape: (-1, -1, 768)
name: StatefulPartitionedCall:0</p><p>outputs['pooler_output'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 768)
name: StatefulPartitionedCall:1</p><p>Method name is: tensorflow/serving/predict*
</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign">sign</a></dd></dl></div>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="" title=""></a>
<a href="" title="">AttentionMask</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$AttentionMaskV1$.html" title=""></a>
<a href="ModelSignatureConstants$$AttentionMaskV1$.html" title="">AttentionMaskV1</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DType$.html" title=""></a>
<a href="ModelSignatureConstants$$DType$.html" title="">DType</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DecoderAttentionMask$.html" title=""></a>
<a href="ModelSignatureConstants$$DecoderAttentionMask$.html" title="">DecoderAttentionMask</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DecoderEncoderInputIds$.html" title=""></a>
<a href="ModelSignatureConstants$$DecoderEncoderInputIds$.html" title="">DecoderEncoderInputIds</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DecoderInputIds$.html" title=""></a>
<a href="ModelSignatureConstants$$DecoderInputIds$.html" title="">DecoderInputIds</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DecoderOutput$.html" title=""></a>
<a href="ModelSignatureConstants$$DecoderOutput$.html" title="">DecoderOutput</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$DimCount$.html" title=""></a>
<a href="ModelSignatureConstants$$DimCount$.html" title="">DimCount</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$EncoderAttentionMask$.html" title=""></a>
<a href="ModelSignatureConstants$$EncoderAttentionMask$.html" title="">EncoderAttentionMask</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$EncoderInputIds$.html" title=""></a>
<a href="ModelSignatureConstants$$EncoderInputIds$.html" title="">EncoderInputIds</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$EncoderOutput$.html" title=""></a>
<a href="ModelSignatureConstants$$EncoderOutput$.html" title="">EncoderOutput</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$InputIds$.html" title=""></a>
<a href="ModelSignatureConstants$$InputIds$.html" title="">InputIds</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$InputIdsV1$.html" title=""></a>
<a href="ModelSignatureConstants$$InputIdsV1$.html" title="">InputIdsV1</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$LastHiddenState$.html" title=""></a>
<a href="ModelSignatureConstants$$LastHiddenState$.html" title="">LastHiddenState</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$LastHiddenStateV1$.html" title=""></a>
<a href="ModelSignatureConstants$$LastHiddenStateV1$.html" title="">LastHiddenStateV1</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$LogitsOutput$.html" title=""></a>
<a href="ModelSignatureConstants$$LogitsOutput$.html" title="">LogitsOutput</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$Name$.html" title=""></a>
<a href="ModelSignatureConstants$$Name$.html" title="">Name</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$PoolerOutput$.html" title=""></a>
<a href="ModelSignatureConstants$$PoolerOutput$.html" title="">PoolerOutput</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$PoolerOutputV1$.html" title=""></a>
<a href="ModelSignatureConstants$$PoolerOutputV1$.html" title="">PoolerOutputV1</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$SerializedSize$.html" title=""></a>
<a href="ModelSignatureConstants$$SerializedSize$.html" title="">SerializedSize</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$ShapeDimList$.html" title=""></a>
<a href="ModelSignatureConstants$$ShapeDimList$.html" title="">ShapeDimList</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="trait" href="ModelSignatureConstants$$TFInfoDescriptor.html" title=""></a>
<a href="ModelSignatureConstants$$TFInfoDescriptor.html" title="">TFInfoDescriptor</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="trait" href="ModelSignatureConstants$$TFInfoNameMapper.html" title=""></a>
<a href="ModelSignatureConstants$$TFInfoNameMapper.html" title="">TFInfoNameMapper</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$TokenTypeIds$.html" title=""></a>
<a href="ModelSignatureConstants$$TokenTypeIds$.html" title="">TokenTypeIds</a>
</li><li class="current-entities indented6">
<span class="separator"></span>
<a class="object" href="ModelSignatureConstants$$TokenTypeIdsV1$.html" title=""></a>
<a href="ModelSignatureConstants$$TokenTypeIdsV1$.html" title="">TokenTypeIdsV1</a>
</li>
</ul>
</div>
</div>
<div id="content">
<body class="object value">
<div id="definition">
<div class="big-circle object">o</div>
<p id="owner"><a href="../../../../index.html" class="extype" name="com">com</a>.<a href="../../../index.html" class="extype" name="com.johnsnowlabs">johnsnowlabs</a>.<a href="../../index.html" class="extype" name="com.johnsnowlabs.ml">ml</a>.<a href="../index.html" class="extype" name="com.johnsnowlabs.ml.tensorflow">tensorflow</a>.<a href="index.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign">sign</a>.<a href="ModelSignatureConstants$.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants">ModelSignatureConstants</a></p>
<h1>AttentionMask<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span></h1>
<h3><span class="morelinks"></span></h3>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">AttentionMask</span><span class="result"> extends <a href="ModelSignatureConstants$$TFInfoNameMapper.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">TFInfoNameMapper</a> with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="toggleContainer block">
<span class="toggle">
Linear Supertypes
</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <a href="ModelSignatureConstants$$TFInfoNameMapper.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">TFInfoNameMapper</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div class="toggle"></div>
<div id="memberfilter">
<i class="material-icons arrow"></i>
<span class="input">
<input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />
</span>
<i class="clear material-icons"></i>
</div>
<div id="filterby">
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div class="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask"><span>AttentionMask</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper"><span>TFInfoNameMapper</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div class="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
</div>
<div id="template">
<div id="allMembers">
<div class="values members">
<h3>Value Members</h3>
<ol>
<li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#!=(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html###():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#==(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#asInstanceOf[T0]:T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a><a id="clone():AnyRef"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#clone():Object" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#eq(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a><a id="equals(Any):Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#equals(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#finalize():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#getClass():Class[_]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#isInstanceOf[T0]:Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask#key" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="key:String"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#key:String" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">key</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask">AttentionMask</a> → <a href="ModelSignatureConstants$$TFInfoNameMapper.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">TFInfoNameMapper</a></dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#ne(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#notify():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#notifyAll():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#synchronized[T0](x$1:=>T0):T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask#value" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="value:String"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#value:String" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">value</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.AttentionMask">AttentionMask</a> → <a href="ModelSignatureConstants$$TFInfoNameMapper.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">TFInfoNameMapper</a></dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#wait():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a>
<span class="permalink">
<a href="../../../../../com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html#wait(x$1:Long):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li>
</ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.Product">
<h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3>
</div><div class="parent" name="scala.Equals">
<h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3>
</div><div class="parent" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">
<h3>Inherited from <a href="ModelSignatureConstants$$TFInfoNameMapper.html" class="extype" name="com.johnsnowlabs.ml.tensorflow.sign.ModelSignatureConstants.TFInfoNameMapper">TFInfoNameMapper</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</div>
</div>
</div>
</body>
</html>
| JohnSnowLabs/spark-nlp | docs/api/com/johnsnowlabs/ml/tensorflow/sign/ModelSignatureConstants$$AttentionMask$.html | HTML | apache-2.0 | 44,854 |
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Copyright (c) 1999-2007 IVT Corporation
*
* All rights reserved.
*
---------------------------------------------------------------------------*/
/////////////////////////////////////////////////////////////////////////////
// Module Name:
// Btsdk_Stru.h
// Abstract:
// This module defines BlueSoleil SDK structures.
// Usage:
// #include "Btsdk_Stru.h"
//
// Author://
//
// Revision History:
// 2007-12-25 Created
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _BTSDK_STRU_H
#define _BTSDK_STRU_H
/*************** Structure Definition ******************/
typedef struct _BtSdkCallbackStru
{
BTUINT16 type; /*type of callback*/
void *func; /*callback function*/
}BtSdkCallbackStru, *PBtSdkCallbackStru;
typedef struct _BtSdkLocalLMPInfoStru
{
BTUINT8 lmp_feature[8]; /* LMP features */
BTUINT16 manuf_name; /* the name of the manufacturer */
BTUINT16 lmp_subversion; /* the sub version of the LMP firmware */
BTUINT8 lmp_version; /* the main version of the LMP firmware */
BTUINT8 hci_version; /* HCI version */
BTUINT16 hci_revision; /* HCI revision */
BTUINT8 country_code; /* country code */
} BtSdkLocalLMPInfoStru, *PBtSdkLocalLMPInfoStru;
typedef struct _BtSdkVendorCmdStru
{
BTUINT16 ocf; /* OCF Range (10 bits): 0x0000-0x03FF */
BTUINT8 param_len; /* length of param in bytes */
BTUINT8 param[1]; /* Parameters to be packed in the vendor command. Little endian is adopted. */
} BtSdkVendorCmdStru, *PBtSdkVendorCmdStru;
typedef struct _BtSdkEventParamStru
{
BTUINT8 ev_code; /* Event code. */
BTUINT8 param_len; /* length of param in bytes */
BTUINT8 param[1]; /* Event parameters. */
} BtSdkEventParamStru, *PBtSdkEventParamStru;
typedef struct _BtSdkRemoteLMPInfoStru
{
BTUINT8 lmp_feature[8]; /* LMP features */
BTUINT16 manuf_name; /* the name of the manufacturer */
BTUINT16 lmp_subversion; /* the sub version of the LMP firmware */
BTUINT8 lmp_version; /* the main version of the LMP firmware */
} BtSdkRemoteLMPInfoStru, *PBtSdkRemoteLMPInfoStru;
typedef struct _BtSdkRemoteDevicePropertyStru
{
BTUINT32 mask; /*Specifies members available.*/
BTDEVHDL dev_hdl; /*Handle assigned to the device record*/
BTUINT8 bd_addr[BTSDK_BDADDR_LEN]; /*BT address of the device record*/
BTUINT8 name[BTSDK_DEVNAME_LEN]; /*Name of the device record, must be in UTF-8*/
BTUINT32 dev_class; /*Device class*/
BtSdkRemoteLMPInfoStru lmp_info; /* LMP info */
BTUINT8 link_key[BTSDK_LINKKEY_LEN]; /* link key for this device. */
} BtSdkRemoteDevicePropertyStru;
typedef BtSdkRemoteDevicePropertyStru* PBtSdkRemoteDevicePropertyStru;
/* Parameters of Hold_Mode command */
typedef struct _BtSdkHoldModeStru {
BTUINT16 conn_hdl; /* reserved, set it to 0. */
BTUINT16 max; /* Hold mode max interval. */
BTUINT16 min; /* Hold mode min interval. */
} BtSdkHoldModeStru;
typedef BtSdkHoldModeStru* PBtSdkHoldModeStru;
/* Parameters of Sniff_Mode command */
typedef struct _BtSdkSniffModeStru {
BTUINT16 conn_hdl; /* reserved, set it to 0. */
BTUINT16 max; /* Sniff mode max interval. */
BTUINT16 min; /* Sniff mode min interval. */
BTUINT16 attempt; /* Sniff mode attempt value. */
BTUINT16 timeout; /* Sniff mode timeout value. */
} BtSdkSniffModeStru;
typedef BtSdkSniffModeStru* PBtSdkSniffModeStru;
/* Parameters of Park_Mode (V1.1) or Park_State (V1.2) command */
typedef struct _BtSdkParkModeStru {
BTUINT16 conn_hdl; /* reserved, set it to 0. */
BTUINT16 max; /* Beacon max interval. */
BTUINT16 min; /* Beacon min interval. */
} BtSdkParkModeStru;
typedef BtSdkParkModeStru* PBtSdkParkModeStru;
/* Basic SDP Element */
typedef struct _BtSdkUUIDStru
{
BTUINT32 Data1;
BTUINT16 Data2;
BTUINT16 Data3;
BTUINT8 Data4[8];
} BtSdkUUIDStru, *PBtSdkUUIDStru;
typedef struct _BtSdkSDPSearchPatternStru
{
BTUINT32 mask; /*Specifies the valid bytes in the uuid*/
BtSdkUUIDStru uuid; /*UUID value*/
} BtSdkSDPSearchPatternStru, *PBtSdkSDPSearchPatternStru;
/* Remote service record attributes */
typedef struct _BtSdkRemoteServiceAttrStru
{
BTUINT16 mask; /*Decide which parameter to be retrieved*/
union
{
BTUINT16 svc_class; /* For Compatibility */
BTUINT16 service_class;
}; /*Type of this service record*/
BTDEVHDL dev_hdl; /*Handle to the remote device which provides this service.*/
BTUINT8 svc_name[BTSDK_SERVICENAME_MAXLENGTH]; /*Service name in UTF-8*/
BTLPVOID ext_attributes; /*Free by the APP*/
BTUINT16 status;
} BtSdkRemoteServiceAttrStru, *PBtSdkRemoteServiceAttrStru;
typedef struct _BtSdkRmtSPPSvcExtAttrStru
{
BTUINT32 size; /*Size of BtSdkRmtSPPSvcExtAttrStru*/
BTUINT8 server_channel; /*Server channel value of this SPP service record*/
} BtSdkRmtSPPSvcExtAttrStru, *PBtSdkRmtSPPSvcExtAttrStru;
typedef struct _BtSdkConnectionPropertyStru
{
BTUINT32 role : 2;
BTUINT32 result : 30;
BTDEVHDL device_handle;
BTSVCHDL service_handle;
BTUINT16 service_class;
BTUINT32 duration;
BTUINT32 received_bytes;
BTUINT32 sent_bytes;
} BtSdkConnectionPropertyStru, *PBtSdkConnectionPropertyStru;
typedef struct _BtSdkFileTransferReqStru
{
BTDEVHDL dev_hdl; /* Handle to the remote device tries to upload/delete the file. */
BTUINT16 operation; /* Specify the operation on the file.
It can be one of the following values:
BTSDK_APP_EV_FTP_PUT: The remote device request to upload the file.
BTSDK_APP_EV_FTP_DEL_FILE: The remote device request to delete the file.
BTSDK_APP_EV_FTP_DEL_FOLDER: The remote device request to delete the folder. In this case,
file_name specify the name of the folder to be deleted.
*/
BTUINT16 flag; /* Flag specifies the current status of uploading/deleting.
It can be one of the following values:
BTSDK_ER_CONTINUE: The remote device request to upload/delete the file.
BTSDK_ER_SUCCESS: The remote device uploads/deletes the file successfully.
Other value: Error code specifies the reason of uploading/deleting failure.
*/
BTUINT8 file_name[BTSDK_PATH_MAXLENGTH]; /* the name of the file uploaded/deleted or to be uploaded/deleted */
} BtSdkFileTransferReqStru, *PBtSdkFileTransferReqStru;
typedef struct _BtSdkAppExtSPPAttrStru
{
BTUINT32 size; /* Size of this structure */
BTUINT32 sdp_record_handle; /* 32bit interger specifies the SDP service record handle */
BtSdkUUIDStru service_class_128; /* 128bit UUID specifies the service class of this service record */
BTUINT8 svc_name[BTSDK_SERVICENAME_MAXLENGTH]; /* Service name, in UTF-8 */
BTUINT8 rf_svr_chnl; /* RFCOMM server channel assigned to this service record */
BTUINT8 com_index; /* Index of the local COM port assigned to this service record */
} BtSdkAppExtSPPAttrStru, *PBtSdkAppExtSPPAttrStru;
/* lParam for SPP */
typedef struct _BtSdkSPPConnParamStru
{
BTUINT32 size;
BTUINT16 mask; //Reserved set 0
BTUINT8 com_index;
} BtSdkSPPConnParamStru, *PBtSdkSPPConnParamStru;
/* lParam for OPP */
typedef struct _BtSdkOPPConnParamStru
{
BTUINT32 size; /*Size of this structure, use for verification and versioning.*/
BTUINT8 inbox_path[BTSDK_PATH_MAXLENGTH]; /*must in UTF-8*/
BTUINT8 outbox_path[BTSDK_PATH_MAXLENGTH]; /*must in UTF-8*/
BTUINT8 own_card[BTSDK_CARDNAME_MAXLENGTH]; /*must in UTF-8*/
} BtSdkOPPConnParamStru, *PBtSdkOPPConnParamStru;
/* lParam for DUN */
typedef struct _BtSdkDUNConnParamStru
{
BTUINT32 size;
BTUINT16 mask; //Reserved set 0
BTUINT8 com_index;
} BtSdkDUNConnParamStru, *PBtSdkDUNConnParamStru;
/* lParam for FAX */
typedef struct _BtSdkFAXConnParamStru
{
BTUINT32 size;
BTUINT16 mask; //Reserved set 0
BTUINT8 com_index;
} BtSdkFAXConnParamStru, *PBtSdkFAXConnParamStru;
/* Used By +COPS */
typedef struct Btsdk_HFP_COPSInfo {
BTUINT8 mode; /* current mode and provides no information with regard to the name of the operator */
BTUINT8 format; /* the format of the operator parameter string */
BTUINT8 operator_len;
BTINT8 operator_name[1]; /* the string in alphanumeric format representing the name of the network operator */
} Btsdk_HFP_COPSInfoStru, *PBtsdk_HFP_COPSInfoStru;
/* Used By +BINP, +CNUM, +CLIP, +CCWA */
typedef struct Btsdk_HFP_PhoneInfo {
BTUINT8 type; /* the format of the phone number provided */
BTUINT8 service; /* Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax). */
BTUINT8 num_len; /* the length of the phone number provided */
BTINT8 number[32]; /* subscriber number, the length shall be PHONENUM_MAX_DIGITS */
BTUINT8 name_len; /* length of subaddr */
BTINT8 alpha_str[1]; /* string type subaddress of format specified by <cli_validity> */
} Btsdk_HFP_PhoneInfoStru, *PBtsdk_HFP_PhoneInfoStru;
/* Used By +CLCC */
typedef struct Btsdk_HFP_CLCCInfo {
BTUINT8 idx; /* The numbering (start with 1) of the call given by the sequence of setting up or receiving the calls */
BTUINT8 dir; /* Direction, 0=outgoing, 1=incoming */
BTUINT8 status; /* 0=active, 1=held, 2=dialling(outgoing), 3=alerting(outgoing), 4=incoming(incoming), 5=waiting(incoming) */
BTUINT8 mode; /* 0=voice, 1=data, 2=fax */
BTUINT8 mpty; /* 0=not multiparty, 1=multiparty */
BTUINT8 type; /* the format of the phone number provided */
BTUINT8 num_len; /* the length of the phone number provided */
BTINT8 number[1]; /* phone number */
} Btsdk_HFP_CLCCInfoStru, *PBtsdk_HFP_CLCCInfoStru;
/* current state mask code for function HFP_AG_SetCurIndicatorVal */
typedef struct Btsdk_HFP_CINDInfo {
BTUINT8 service; /* 0=unavailable, 1=available */
BTUINT8 call; /* 0=no active call, 1=have active call */
BTUINT8 callsetup; /* 0=no callsetup, 1=incoming, 2=outgoing, 3=outalert */
BTUINT8 callheld; /* 0=no callheld, 1=active-hold, 2=onhold */
BTUINT8 signal; /* 0~5 */
BTUINT8 roam; /* 0=no roam, 1= roam */
BTUINT8 battchg; /* 0~5 */
} Btsdk_HFP_CINDInfoStru, *PBtsdk_HFP_CINDInfoStru;
/* Parameter of the BTSDK_HFP_EV_SLC_ESTABLISHED_IND and BTSDK_HFP_EV_SLC_RELEASED_IND events */
typedef struct Btsdk_HFP_ConnInfo {
BTUINT16 role; /* 16bit UUID specifies the local role of the connection:
BTSDK_CLS_HANDSFREE - Local device acts as a HF.
BTSDK_CLS_HANDSFREE_AG - Local device acts as a Hands-free AG.
BTSDK_CLS_HEADSET - Local device acts as a HS.
BTSDK_CLS_HEADSET_AG - Local device acts as a Headset AG. */
BTDEVHDL dev_hdl; /* Handle to the remote device. */
} Btsdk_HFP_ConnInfoStru, *PBtsdk_HFP_ConnInfoStru;
/* Used by BTSDK_HFP_EV_ATCMD_RESULT */
typedef struct Btsdk_HFP_ATCmdResult {
BTUINT16 cmd_code; /* Which AT command code got an error */
BTUINT8 result_code; /* What result occurs, BTSDK_HFP_APPERR_TIMEOUT, CME Error Code or standard error result code */
} Btsdk_HFP_ATCmdResultStru, *PBtsdk_HFP_ATCmdResultStru;
/* lParam of Btsdk_StartClient, Btsdk_StartClientEx and Btsdk_ConnectShortCutEx; and,
ext_attributes of BtSdkLocalServerAttrStru. */
typedef struct _BtSdkHFPUIParam {
BTUINT32 size; /* Must set to sizeof(BtSdkHFPConnParamStru) */
BTUINT16 mask; /* Reserved, set to 0 */
BTUINT16 features; /* Local supported features.
1) For HSP, it shall be 0.
2) For HFP-HF, it can be the bit OR operation of following values:
BTSDK_HF_BRSF_NREC, BTSDK_HF_BRSF_3WAYCALL, BTSDK_HF_BRSF_CLIP,
BTSDK_HF_BRSF_BVRA, BTSDK_HF_BRSF_RMTVOLCTRL, BTSDK_HF_BRSF_ENHANCED_CALLSTATUS,
BTSDK_HF_BRSF_ENHANCED_CALLCONTROL.
3) For HFP-AG, it can be the bit OR operation of following values:
BTSDK_AG_BRSF_3WAYCALL, BTSDK_AG_BRSF_NREC, BTSDK_AG_BRSF_BVRA,
BTSDK_AG_BRSF_INBANDRING, BTSDK_AG_BRSF_BINP, BTSDK_AG_BRSF_REJECT_CALL,
BTSDK_AG_BRSF_ENHANCED_CALLSTATUS, BTSDK_AG_BRSF_ENHANCED_CALLCONTROL,
BTSDK_AG_BRSF_EXTENDED_ERRORRESULT.
*/
} BtSdkHFPUIParamStru, *PBtSdkHFPUIParamStru,
BtSdkHFPConnParamStru, *PBtSdkHFPConnParamStru,
BtSdkLocalHFPServerAttrStru, *PBtSdkHFPLocalHFPServerAttrStru;
typedef struct _BtSdk_SDAP_PNPINFO
{
BTUINT16 size;
BTUINT16 mask;
BTUINT32 svc_hdl;
BTUINT16 spec_id;
BTUINT16 vendor_id;
BTUINT16 product_id;
BTUINT16 version_value;
BTUINT16 vendor_id_src;
}BtSdk_SDAP_PNPINFO, *PBtSdk_SDAP_PNPINFO;
typedef struct _BtSdkRmtDISvcExtAttrStru
{
BTUINT32 size;
BTUINT16 mask;
BTUINT16 spec_id;
BTUINT16 vendor_id;
BTUINT16 product_id;
BTUINT16 version;
BTBOOL primary_record;
BTUINT16 vendor_id_source;
BTUINT16 list_size;
BTUINT8 str_url_list[1];
} BtSdkRmtDISvcExtAttrStru, *PBtSdkRmtDISvcExtAttrStru;
#endif | favoritas37/QBluetoothZero | examples/RemoteBrowser/BlueSoleil_SDK_2.0.5/include/Btsdk_Stru.h | C | apache-2.0 | 13,230 |
/*
* Copyright 2019 The Project Oak Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const showGreenIconForExtensionPages = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: chrome.runtime.id,
schemes: ['chrome-extension'],
pathEquals: '/index.html',
},
}),
],
actions: [new chrome.declarativeContent.SetIcon({ path: 'icon-green.png' })],
};
chrome.runtime.onInstalled.addListener(function () {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
chrome.declarativeContent.onPageChanged.addRules([
showGreenIconForExtensionPages,
]);
});
});
async function loadPageInASecureSandbox({ id: tabId }) {
const src = (
await new Promise((resolve) =>
chrome.tabs.executeScript(tabId, { file: 'getInnerHtml.js' }, resolve)
)
)?.[0];
// It's possible that the chrome extension cannot read the source code, either
// because it is served via a non-permitted scheme (eg `chrome-extension://`),
// or bc the user/adminstrator has denied this extension access to the page.
if (!src) {
chrome.notifications.create(undefined, {
type: 'basic',
title: 'Could not sandbox this page',
message: 'The extension does not have permission to modify this page.',
iconUrl: 'icon-red.png',
isClickable: false,
eventTime: Date.now(),
});
return;
}
const searchParams = new URLSearchParams({ src });
const url = `index.html?${searchParams.toString()}`;
chrome.tabs.update({ url });
}
chrome.browserAction.onClicked.addListener(loadPageInASecureSandbox);
| project-oak/oak | chrome_extension/background.js | JavaScript | apache-2.0 | 2,181 |
/*******************************************************************************
* Copyright © 2012-2015 eBay Software Foundation
* This program is dual licensed under the MIT and Apache 2.0 licenses.
* Please see LICENSE for more information.
*******************************************************************************/
package com.ebay.pulsar.analytics.metricstore.druid.query.sql;
/**
*
* @author mingmwang
*
*/
public class HllConstants {
public static final String HLLPREFIX = "hllhaving_";
}
| pulsarIO/pulsar-reporting-api | pulsarquery-druid/src/main/java/com/ebay/pulsar/analytics/metricstore/druid/query/sql/HllConstants.java | Java | apache-2.0 | 514 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Copyright 2014 Thomas Barnekow (cloning, Flat OPC (with Eric White))
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.IO.Packaging;
using System.Globalization;
using DocumentFormat.OpenXml;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
#endif
using static System.ReflectionExtensions;
namespace DocumentFormat.OpenXml.Packaging
{
internal struct RelationshipProperty
{
internal string Id;
internal string RelationshipType;
internal TargetMode TargetMode;
internal Uri TargetUri;
};
/// <summary>
/// Defines the base class for PackageRelationshipPropertyCollection and PackagePartRelationshipPropertyCollection objects.
/// </summary>
abstract internal class RelationshipCollection : List<RelationshipProperty>
{
protected PackageRelationshipCollection BasePackageRelationshipCollection { get; set; }
internal bool StrictTranslation { get; set; }
/// <summary>
/// This method fills the collection with PackageRels from the PackageRelationshipCollection that is given in the sub class.
/// </summary>
protected void Build()
{
foreach (PackageRelationship relationship in this.BasePackageRelationshipCollection)
{
bool found;
string transitionalNamespace;
RelationshipProperty relationshipProperty;
relationshipProperty.TargetUri = relationship.TargetUri;
relationshipProperty.TargetMode = relationship.TargetMode;
relationshipProperty.Id = relationship.Id;
relationshipProperty.RelationshipType = relationship.RelationshipType;
// If packageRel.RelationshipType is something for Strict, it tries to get the equivalent in Transitional.
found = NamespaceIdMap.TryGetTransitionalRelationship(relationshipProperty.RelationshipType, out transitionalNamespace);
if (found)
{
relationshipProperty.RelationshipType = transitionalNamespace;
this.StrictTranslation = true;
}
this.Add(relationshipProperty);
}
}
internal void UpdateRelationshipTypesInPackage()
{
// Update the relationshipTypes when editable.
if (this.GetPackage().FileOpenAccess != FileAccess.Read)
{
for (int index = 0; index < this.Count; index++)
{
RelationshipProperty relationshipProperty = this[index];
this.ReplaceRelationship(relationshipProperty.TargetUri, relationshipProperty.TargetMode, relationshipProperty.RelationshipType, relationshipProperty.Id);
}
}
}
abstract internal void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId);
abstract internal Package GetPackage();
}
/// <summary>
/// Represents a collection of relationships that are obtained from the package.
/// </summary>
internal class PackageRelationshipPropertyCollection : RelationshipCollection
{
public Package BasePackage { get; set; }
public PackageRelationshipPropertyCollection(Package package)
{
this.BasePackage = package;
if (this.BasePackage == null)
{
throw new ArgumentNullException(nameof(BasePackage));
}
this.BasePackageRelationshipCollection = this.BasePackage.GetRelationships();
this.Build();
}
internal override void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId)
{
this.BasePackage.DeleteRelationship(strId);
this.BasePackage.CreateRelationship(targetUri, targetMode, strRelationshipType, strId);
}
internal override Package GetPackage()
{
return this.BasePackage;
}
}
/// <summary>
/// Represents a collection of relationships that are obtained from the package part.
/// </summary>
internal class PackagePartRelationshipPropertyCollection : RelationshipCollection
{
public PackagePart BasePackagePart { get; set; }
public PackagePartRelationshipPropertyCollection(PackagePart packagePart)
{
this.BasePackagePart = packagePart;
if (this.BasePackagePart == null)
{
throw new ArgumentNullException(nameof(BasePackagePart));
}
this.BasePackageRelationshipCollection = this.BasePackagePart.GetRelationships();
this.Build();
}
internal override void ReplaceRelationship(Uri targetUri, TargetMode targetMode, string strRelationshipType, string strId)
{
this.BasePackagePart.DeleteRelationship(strId);
this.BasePackagePart.CreateRelationship(targetUri, targetMode, strRelationshipType, strId);
}
internal override Package GetPackage()
{
return this.BasePackagePart.Package;
}
}
/// <summary>
/// Represents a base class for strong typed Open XML document classes.
/// </summary>
public abstract class OpenXmlPackage : OpenXmlPartContainer, IDisposable
{
#region private data members
//internal object _lock = new object( );
private bool _disposed;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Package _metroPackage;
private FileAccess _accessMode;
private string _mainPartContentType;
// compression level for content that is stored in a PackagePart.
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private CompressionOption _compressionOption = CompressionOption.Normal;
private PartUriHelper _partUriHelper = new PartUriHelper();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private PartExtensionProvider _partExtensionProvider = new PartExtensionProvider();
private LinkedList<DataPart> _dataPartList = new LinkedList<DataPart>();
#endregion
internal OpenSettings OpenSettings { get; set; }
private bool _strictTranslation = false;
internal bool StrictTranslation
{
get
{
return this._strictTranslation;
}
set
{
this._strictTranslation = value;
}
}
#region internal constructors
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class.
/// </summary>
protected OpenXmlPackage()
: base()
{
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied Open XML package.
/// </summary>
/// <param name="package">The target package for the OpenXmlPackage class.</param>
/// <exception cref="ArgumentNullException">Thrown when package is a null reference.</exception>
/// <exception cref="IOException">Thrown when package is not opened with read access.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the package is not a valid Open XML document.</exception>
internal void OpenCore(Package package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
if (package.FileOpenAccess == FileAccess.Write)
{
// TODO: move this line to derived class
throw new IOException(ExceptionMessages.PackageMustCanBeRead);
}
this._accessMode = package.FileOpenAccess;
this._metroPackage = package;
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class with access to a specified Open XML package.
/// </summary>
/// <param name="package">The target package for the OpenXmlPackage class.</param>
/// <exception cref="ArgumentNullException">Thrown when package is a null reference.</exception>
/// <exception cref="IOException">Thrown when package is not opened with write access.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the package is not a valid Open XML document.</exception>
internal void CreateCore(Package package)
{
if (package == null)
{
throw new ArgumentNullException(nameof(package));
}
//if (package.FileOpenAccess != FileAccess.Write)
//{
// // TODO: move this line to derived class
// throw new IOException(ExceptionMessages.PackageAccessModeShouldBeWrite);
//}
this._accessMode = package.FileOpenAccess;
this._metroPackage = package;
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied I/O stream class.
/// </summary>
/// <param name="stream">The I/O stream on which to open the package.</param>
/// <param name="readWriteMode">Indicates whether or not the package is in read/write mode. False indicates read-only mode.</param>
/// <exception cref="IOException">Thrown when the specified stream is write-only. The package to open requires read or read/write permission.</exception>
internal void OpenCore(Stream stream, bool readWriteMode)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (readWriteMode)
{
this._accessMode = FileAccess.ReadWrite;
}
else
{
this._accessMode = FileAccess.Read;
}
this._metroPackage = Package.Open(stream, (this._accessMode == FileAccess.Read) ? FileMode.Open : FileMode.OpenOrCreate, this._accessMode);
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied I/O stream class.
/// </summary>
/// <param name="stream">The I/O stream on which to open the package.</param>
/// <exception cref="IOException">Thrown when the specified stream is read-only. The package to open requires write or read/write permission. </exception>
internal void CreateCore(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new OpenXmlPackageException(ExceptionMessages.StreamAccessModeShouldBeWrite);
}
this._accessMode = FileAccess.ReadWrite;
//this._accessMode = FileAccess.Write;
// below line will exception by Package. Packaging API bug?
// this._metroPackage = Package.Open(stream, FileMode.Create, packageAccess);
this._metroPackage = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the specified file.
/// </summary>
/// <param name="path">The path and file name of the target package for the OpenXmlPackage.</param>
/// <param name="readWriteMode">Indicates whether or not the package is in read/write mode. False for read only mode.</param>
internal void OpenCore(string path, bool readWriteMode)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (readWriteMode)
{
this._accessMode = FileAccess.ReadWrite;
}
else
{
this._accessMode = FileAccess.Read;
}
this._metroPackage = Package.Open(path, (this._accessMode == FileAccess.Read) ? FileMode.Open : FileMode.OpenOrCreate, this._accessMode, (this._accessMode == FileAccess.Read) ? FileShare.Read : FileShare.None);
this.Load();
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackage class using the supplied file.
/// </summary>
/// <param name="path">The path and file name of the target package for the OpenXmlPackage.</param>
internal void CreateCore(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
this._accessMode = FileAccess.ReadWrite;
//this._accessMode = FileAccess.Write;
// below line will exception by Package. Packaging API bug?
// this._metroPackage = Package.Open(path, FileMode.Create, packageAccess, FileShare.None);
this._metroPackage = Package.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
}
/// <summary>
/// Loads the package. This method must be called in the constructor of a derived class.
/// </summary>
private void Load()
{
Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPackage_Load_In);
try
{
Dictionary<Uri, OpenXmlPart> loadedParts = new Dictionary<Uri, OpenXmlPart>();
bool hasMainPart = false;
RelationshipCollection relationshipCollection = new PackageRelationshipPropertyCollection(this._metroPackage);
// relationCollection.StrictTranslation is true when this collection contains Transitional relationships converted from Strict.
this.StrictTranslation = relationshipCollection.StrictTranslation;
// AutoSave must be false when opening ISO Strict doc as editable.
// (Attention: #2545529. Now we disable this code until we finally decide to go with this. Instead, we take an alternative approach that is added in the SavePartContents() method
// which we ignore AutoSave when this.StrictTranslation is true to keep consistency in the document.)
//if (this.StrictTranslation && (this._accessMode == FileAccess.ReadWrite || this._accessMode == FileAccess.Write) && !this.AutoSave)
//{
// OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.StrictEditNeedsAutoSave);
// throw exception;
//}
// auto detect document type (main part type for Transitional)
foreach (RelationshipProperty relationship in relationshipCollection)
{
if (relationship.RelationshipType == this.MainPartRelationshipType)
{
hasMainPart = true;
Uri uriTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
PackagePart metroPart = this.Package.GetPart(uriTarget);
if (!this.IsValidMainPartContentType(metroPart.ContentType))
{
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.InvalidPackageType);
throw exception;
}
this.MainPartContentType = metroPart.ContentType;
break;
}
}
if (!hasMainPart)
{
// throw exception is the package do not have the main part (MainDocument / Workbook / Presentation part)
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.NoMainPart);
throw exception;
}
this.LoadReferencedPartsAndRelationships(this, null, relationshipCollection, loadedParts);
}
catch (OpenXmlPackageException)
{
// invalid part ( content type is not expected )
this.Close();
throw;
}
catch (System.UriFormatException)
{
// UriFormatException is replaced here with OpenXmlPackageException. <O15:#322821>
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.InvalidUriFormat);
this.Close();
throw exception;
}
catch (Exception)
{
this.Close();
throw;
}
Profiler.CommentMarkProfile(Profiler.MarkId.OpenXmlPackage_Load_Out);
}
#endregion
#region public properties
/// <summary>
/// Gets the package of the document.
/// </summary>
public Package Package
{
get
{
this.ThrowIfObjectDisposed();
return _metroPackage;
}
}
/// <summary>
/// Gets the FileAccess setting for the document.
/// The current I/O access settings are: Read, Write, or ReadWrite.
/// </summary>
public FileAccess FileOpenAccess
{
get { return this._metroPackage.FileOpenAccess; }
}
/// <summary>
/// Gets or sets the compression level for the content of the new part.
/// </summary>
public CompressionOption CompressionOption
{
get { return this._compressionOption; }
set { this._compressionOption = value; }
}
/// <summary>
/// Gets the core package properties of the Open XML document.
/// </summary>
public PackageProperties PackageProperties
{
get
{
this.ThrowIfObjectDisposed();
return this.Package.PackageProperties;
}
}
/// <summary>
/// Gets a PartExtensionProvider part which provides a mapping from ContentType to part extension.
/// </summary>
public PartExtensionProvider PartExtensionProvider
{
get
{
this.ThrowIfObjectDisposed();
return this._partExtensionProvider;
}
}
/// <summary>
/// Gets or sets a value that indicates the maximum allowable number of characters in an Open XML part. A zero (0) value indicates that there are no limits on the size of the part. A non-zero value specifies the maximum size, in characters.
/// </summary>
/// <remarks>
/// This property allows you to mitigate denial of service attacks where the attacker submits a package with an extremely large Open XML part. By limiting the size of a part, you can detect the attack and recover reliably.
/// </remarks>
public long MaxCharactersInPart
{
get;
internal set;
}
/// <summary>
/// Enumerates all the <see cref="DataPart"/> parts in the document package.
/// </summary>
public IEnumerable<DataPart> DataParts
{
get
{
return this._dataPartList;
}
}
#endregion
#region public methods
/// <summary>
/// Adds the specified part to the document.
/// Use the returned part to operate on the part added to the document.
/// </summary>
/// <typeparam name="T">A class that is derived from the OpenXmlPart class.</typeparam>
/// <param name="part">The part to add to the document.</param>
/// <returns>The added part in the document. Differs from the part that was passed as an argument.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the part is not allowed to be added.</exception>
/// <exception cref="OpenXmlPackageException">Thrown when the part type already exists and multiple instances of the part type is not allowed.</exception>
public override T AddPart<T>(T part)
{
this.ThrowIfObjectDisposed();
if (part == null)
{
throw new ArgumentNullException(nameof(part));
}
if (part.RelationshipType == this.MainPartRelationshipType &&
part.ContentType != this.MainPartContentType)
{
throw new ArgumentOutOfRangeException(ExceptionMessages.MainPartIsDifferent);
}
return (T)AddPartFrom(part, null);
}
/// <summary>
/// Deletes all the parts with the specified part type from the package recursively.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public void DeletePartsRecursivelyOfType<T>() where T : OpenXmlPart
{
this.ThrowIfObjectDisposed();
DeletePartsRecursivelyOfTypeBase<T>();
}
// Remove this method due to bug #18394
// User can call doc.Package.Flush( ) as a workaround.
///// <summary>
///// Saves the contents of all parts and relationships that are contained in the OpenXml package.
///// </summary>
//public void Save()
//{
// this.ThrowIfObjectDisposed();
// this.Package.Flush();
//}
/// <summary>
/// Saves and closes the OpenXml package and all underlying part streams.
/// </summary>
public void Close()
{
this.ThrowIfObjectDisposed();
Dispose();
}
#region methods to operate DataPart
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="contentType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="contentType"/> is a null reference.</exception>
public MediaDataPart CreateMediaDataPart(string contentType)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, contentType, null);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="contentType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <param name="extension">The part name extension (.dat, etc.) of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="contentType"/> is a null reference.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="extension"/> is a null reference.</exception>
public MediaDataPart CreateMediaDataPart(string contentType, string extension)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
if (extension == null)
{
throw new ArgumentNullException(nameof(extension));
}
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, contentType, extension);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Creates a new <see cref="MediaDataPart"/> part in the document package.
/// </summary>
/// <param name="mediaDataPartType">The content type of the new <see cref="MediaDataPart"/> part.</param>
/// <returns>The added <see cref="MediaDataPart"/> part.</returns>
public MediaDataPart CreateMediaDataPart(MediaDataPartType mediaDataPartType)
{
ThrowIfObjectDisposed();
MediaDataPart mediaDataPart = new MediaDataPart();
mediaDataPart.CreateInternal(this.InternalOpenXmlPackage, mediaDataPartType);
this._dataPartList.AddLast(mediaDataPart);
return mediaDataPart;
}
/// <summary>
/// Deletes the specified <see cref="DataPart"/> from the document package.
/// </summary>
/// <param name="dataPart">The <see cref="DataPart"/> to be deleted.</param>
/// <returns>Returns true if the part is successfully removed; otherwise returns false. This method also returns false if the part was not found or the parameter is null.</returns>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="dataPart"/> is referenced by another part in the document package.</exception>
public bool DeletePart(DataPart dataPart)
{
ThrowIfObjectDisposed();
if (dataPart == null)
{
throw new ArgumentNullException(nameof(dataPart));
}
if (dataPart.OpenXmlPackage != this)
{
throw new InvalidOperationException(ExceptionMessages.ForeignDataPart);
}
if (IsOrphanDataPart(dataPart))
{
// delete the part from the package
dataPart.Destroy();
return this._dataPartList.Remove(dataPart);
}
else
{
throw new InvalidOperationException(ExceptionMessages.DataPartIsInUse);
}
}
#endregion
#endregion
#region public virtual methods
/// <summary>
/// Validates the package. This method does not validate the XML content in each part.
/// </summary>
/// <param name="validationSettings">The OpenXmlPackageValidationSettings for validation events.</param>
/// <remarks>If validationSettings is null or no EventHandler is set, the default behavior is to throw an OpenXmlPackageException on the validation error. </remarks>
[Obsolete(ObsoleteAttributeMessages.ObsoleteV1ValidationFunctionality, false)]
public void Validate(OpenXmlPackageValidationSettings validationSettings)
{
this.ThrowIfObjectDisposed();
OpenXmlPackageValidationSettings actualValidationSettings;
if (validationSettings != null && validationSettings.GetEventHandler() != null)
{
actualValidationSettings = validationSettings;
}
else
{
// use default DefaultValidationEventHandler( ) which throw an exception
actualValidationSettings = new OpenXmlPackageValidationSettings();
actualValidationSettings.EventHandler += new EventHandler<OpenXmlPackageValidationEventArgs>(DefaultValidationEventHandler);
}
// TODO: what's expected behavior?
actualValidationSettings.FileFormat = FileFormatVersions.Office2007;
// for cycle defense
Dictionary<OpenXmlPart, bool> processedParts = new Dictionary<OpenXmlPart, bool>();
ValidateInternal(actualValidationSettings, processedParts);
}
#pragma warning disable 0618 // CS0618: A class member was marked with the Obsolete attribute, such that a warning will be issued when the class member is referenced.
/// <summary>
/// Validates the package. This method does not validate the XML content in each part.
/// </summary>
/// <param name="validationSettings">The OpenXmlPackageValidationSettings for validation events.</param>
/// <param name="fileFormatVersion">The target file format version.</param>
/// <remarks>If validationSettings is null or no EventHandler is set, the default behavior is to throw an OpenXmlPackageException on the validation error. </remarks>
internal void Validate(OpenXmlPackageValidationSettings validationSettings, FileFormatVersions fileFormatVersion)
{
this.ThrowIfObjectDisposed();
Debug.Assert(validationSettings != null);
Debug.Assert(fileFormatVersion == FileFormatVersions.Office2007 || fileFormatVersion == FileFormatVersions.Office2010 || fileFormatVersion == FileFormatVersions.Office2013);
validationSettings.FileFormat = fileFormatVersion;
// for cycle defense
Dictionary<OpenXmlPart, bool> processedParts = new Dictionary<OpenXmlPart, bool>();
ValidateInternal(validationSettings, processedParts);
}
#endregion
#region virtual methods / properties
#endregion
#region internal methods
/// <summary>
/// Reserves the URI of the loaded part.
/// </summary>
/// <param name="contentType"></param>
/// <param name="partUri"></param>
internal void ReserveUri(string contentType, Uri partUri)
{
this.ThrowIfObjectDisposed();
this._partUriHelper.ReserveUri(contentType, partUri);
}
/// <summary>
/// Gets a unique part URI for the newly created part.
/// </summary>
/// <param name="contentType">The content type of the part.</param>
/// <param name="parentUri">The URI of the parent part.</param>
/// <param name="targetPath"></param>
/// <param name="targetName"></param>
/// <param name="targetExt"></param>
/// <returns></returns>
internal Uri GetUniquePartUri(string contentType, Uri parentUri, string targetPath, string targetName, string targetExt)
{
this.ThrowIfObjectDisposed();
Uri partUri = null;
// fix bug #241492
// check to avoid name conflict with orphan parts in the packages.
do
{
partUri = this._partUriHelper.GetUniquePartUri(contentType, parentUri, targetPath, targetName, targetExt);
} while (this._metroPackage.PartExists(partUri));
return partUri;
}
/// <summary>
/// Gets a unique part URI for the newly created part.
/// </summary>
/// <param name="contentType">The content type of the part.</param>
/// <param name="parentUri">The URI of the parent part.</param>
/// <param name="targetUri"></param>
/// <returns></returns>
internal Uri GetUniquePartUri(string contentType, Uri parentUri, Uri targetUri)
{
this.ThrowIfObjectDisposed();
Uri partUri = null;
// fix bug #241492
// check to avoid name conflict with orphan parts in the packages.
do
{
partUri = this._partUriHelper.GetUniquePartUri(contentType, parentUri, targetUri);
} while (this._metroPackage.PartExists(partUri));
return partUri;
}
#endregion
#region dispose related methods
/// <summary>
/// Thrown if an object is disposed.
/// </summary>
protected override void ThrowIfObjectDisposed()
{
if (this._disposed)
{
throw new ObjectDisposedException(base.GetType().Name);
}
}
/// <summary>
/// Flushes and saves the content, closes the document, and releases all resources.
/// </summary>
/// <param name="disposing">Specify true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Try to save contents of every part in the package
SavePartContents();
DeleteUnusedDataPartOnClose();
// TODO: Close resources
this._metroPackage.Close();
this._metroPackage = null;
this.PartDictionary = null;
this.ReferenceRelationshipList.Clear();
this._partUriHelper = null;
}
this._disposed = true;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Flushes and saves the content, closes the document, and releases all resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region MC Staffs
/// <summary>
/// Gets the markup compatibility settings applied at loading time.
/// </summary>
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (OpenSettings.MarkupCompatibilityProcessSettings == null)
return new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.NoProcess, FileFormatVersions.Office2007);
else
return OpenSettings.MarkupCompatibilityProcessSettings;
}
}
//internal FileFormatVersions MCTargetFormat
//{
// get
// {
// if (MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.NoProcess)
// return (FileFormatVersions.Office2007 | FileFormatVersions.Office2010);
// else
// {
// return MarkupCompatibilityProcessSettings.TargetFileFormatVersions;
// }
// }
//}
//internal bool ProcessMCInWholePackage
//{
// get
// {
// return MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.ProcessAllParts;
// }
//}
#endregion
#region Auto-Save functions
/// <summary>
/// Gets a flag that indicates whether the parts should be saved when disposed.
/// </summary>
public bool AutoSave
{
get
{
return OpenSettings.AutoSave;
}
}
private void SavePartContents()
{
OpenXmlPackagePartIterator iterator;
bool isAnyPartChanged;
if (this.FileOpenAccess == FileAccess.Read)
{
return; // do nothing if the package is open in read-only mode.
}
// When this.StrictTranslation is true, we ignore AutoSave to do the translation if isAnyPartChanged is true. That's the way to keep consistency.
if (!this.AutoSave && !this.StrictTranslation)
{
return; // do nothing if AutoSave is false.
}
// Traversal the whole package and save changed contents.
iterator = new OpenXmlPackagePartIterator(this);
isAnyPartChanged = false;
// If a part is in the state of 'loaded', something in the part should've been changed.
// When all the part is not loaded yet, we can skip saving all parts' contents and updating Package relationship types.
foreach (var part in iterator)
{
if (part.IsRootElementLoaded)
{
isAnyPartChanged = true;
break;
}
}
// We update parts and relationship types only when any one of the parts was changed (i.e. loaded).
if (isAnyPartChanged)
{
foreach (var part in iterator)
{
TrySavePartContent(part);
}
if (this.StrictTranslation)
{
RelationshipCollection relationshipCollection;
// For Package: Invoking UpdateRelationshipTypesInPackage() changes the relationship types in the package.
// We need to new PackageRelationshipPropertyCollection to read through the package contents right here
// because some operation may have updated the package before we get here.
relationshipCollection = new PackageRelationshipPropertyCollection(this._metroPackage);
relationshipCollection.UpdateRelationshipTypesInPackage();
}
}
}
// Check if the part content changed and save it if yes.
private static void TrySavePartContent(OpenXmlPart part)
{
Debug.Assert(part != null);
Debug.Assert(part.OpenXmlPackage != null);
// If StrictTranslation is true, we need to update the part anyway.
if (part.OpenXmlPackage.StrictTranslation)
{
RelationshipCollection relationshipCollection;
// For PackagePart: Invoking UpdateRelationshipTypesInPackage() changes the relationship types in the package part.
// We need to new PackageRelationshipPropertyCollection to read through the package part contents right here
// because some operation may have updated the package part before we get here.
relationshipCollection = new PackagePartRelationshipPropertyCollection(part.PackagePart);
relationshipCollection.UpdateRelationshipTypesInPackage();
// For ISO Strict documents, we read and save the part anyway to translate the contents. The contents are translated when PartRootElement is being loaded.
if (part.PartRootElement != null)
{
SavePartContent(part);
}
}
else
{
// For Transitional documents, we only save the 'changed' part.
if (IsPartContentChanged(part))
{
SavePartContent(part);
}
}
}
// Check if the content of a part is changed.
private static bool IsPartContentChanged(OpenXmlPart part)
{
Debug.Assert(part != null);
// If the root element of the part is loaded,
// consider the part changed and should be saved.
Debug.Assert(part.OpenXmlPackage != null);
if (!part.IsRootElementLoaded &&
part.OpenXmlPackage.MarkupCompatibilityProcessSettings.ProcessMode == MarkupCompatibilityProcessMode.ProcessAllParts)
{
if (part.PartRootElement != null)
{
return true;
}
}
return part.IsRootElementLoaded;
}
// Save the content of a part to its stream.
private static void SavePartContent(OpenXmlPart part)
{
Debug.Assert(part != null);
Debug.Assert(part.IsRootElementLoaded);
// Save PartRootElement to the part stream.
part.PartRootElement.Save();
}
#endregion
#region internal methods related main part
/// <summary>
/// Gets the relationship type of the main part.
/// </summary>
internal abstract string MainPartRelationshipType { get; }
/// <summary>
/// Gets or sets the content type of the main part of the package.
/// </summary>
internal string MainPartContentType
{
get
{
return _mainPartContentType;
}
set
{
if (this.IsValidMainPartContentType(value))
{
this._mainPartContentType = value;
}
else
{
throw new ArgumentOutOfRangeException(ExceptionMessages.InvalidMainPartContentType);
}
}
}
/// <summary>
/// Gets the list of valid content types for the main part.
/// </summary>
internal abstract ICollection<string> ValidMainPartContentTypes { get; }
/// <summary>
/// Determines whether the content type is valid for the main part of the package.
/// </summary>
/// <param name="contentType">The content type.</param>
/// <returns>Returns true if the content type is valid.</returns>
internal bool IsValidMainPartContentType(string contentType)
{
return ValidMainPartContentTypes.Contains(contentType);
}
/// <summary>
/// Changes the type of the document.
/// </summary>
/// <typeparam name="T">The type of the document's main part.</typeparam>
/// <remarks>The MainDocumentPart will be changed.</remarks>
internal void ChangeDocumentTypeInternal<T>() where T : OpenXmlPart
{
ThrowIfObjectDisposed();
T mainPart = this.GetSubPartOfType<T>();
MemoryStream memoryStream = null;
ExtendedPart tempPart = null;
Dictionary<string, OpenXmlPart> childParts = new Dictionary<string, OpenXmlPart>();
ReferenceRelationship[] referenceRelationships;
try
{
// read the content to local string
using (Stream mainPartStream = mainPart.GetStream())
{
if (mainPartStream.Length > Int32.MaxValue)
{
throw new OpenXmlPackageException(ExceptionMessages.DocumentTooBig);
}
memoryStream = new MemoryStream(Convert.ToInt32(mainPartStream.Length));
OpenXmlPart.CopyStream(mainPartStream, memoryStream);
}
//
tempPart = this.AddExtendedPart(@"http://temp", this.MainPartContentType, @".xml");
foreach (KeyValuePair<string, OpenXmlPart> idPartPair in mainPart.ChildrenParts)
{
childParts.Add(idPartPair.Key, idPartPair.Value);
}
referenceRelationships = mainPart.ReferenceRelationshipList.ToArray();
}
catch (OpenXmlPackageException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#if FEATURE_SYSTEMEXCEPTION
catch (SystemException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#endif
try
{
Uri uri = mainPart.Uri;
string id = this.GetIdOfPart(mainPart);
// remove the old part
this.ChildrenParts.Remove(id);
this.DeleteRelationship(id);
mainPart.Destroy();
// create new part
T newMainPart = CreateInstance<T>();
// do not call this.InitPart( ). copy the code here
newMainPart.CreateInternal2(this, null, this.MainPartContentType, uri);
// add it and get the id
string relationshipId = this.AttachChild(newMainPart, id);
this.ChildrenParts.Add(relationshipId, newMainPart);
// copy the stream back
memoryStream.Position = 0;
newMainPart.FeedData(memoryStream);
// add back all relationships
foreach (KeyValuePair<string, OpenXmlPart> idPartPair in childParts)
{
// just call AttachChild( ) is OK. No need to call AddPart( ... )
newMainPart.AttachChild(idPartPair.Value, idPartPair.Key);
newMainPart.ChildrenParts.Add(idPartPair);
}
foreach (ExternalRelationship externalRel in referenceRelationships.OfType<ExternalRelationship>())
{
newMainPart.AddExternalRelationship(externalRel.RelationshipType, externalRel.Uri, externalRel.Id);
}
foreach (HyperlinkRelationship hyperlinkRel in referenceRelationships.OfType<HyperlinkRelationship>())
{
newMainPart.AddHyperlinkRelationship(hyperlinkRel.Uri, hyperlinkRel.IsExternal, hyperlinkRel.Id);
}
foreach (DataPartReferenceRelationship dataPartReference in referenceRelationships.OfType<DataPartReferenceRelationship>())
{
newMainPart.AddDataPartReferenceRelationship(dataPartReference);
}
// delete the temp part
id = this.GetIdOfPart(tempPart);
this.ChildrenParts.Remove(id);
this.DeleteRelationship(id);
tempPart.Destroy();
}
catch (OpenXmlPackageException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentType, e);
}
#if FEATURE_SYSTEMEXCEPTION
catch (SystemException e)
{
throw new OpenXmlPackageException(ExceptionMessages.CannotChangeDocumentTypeSerious, e);
}
#endif
}
#endregion
#region internal methods
// internal abstract IExtensionPartFactory ExtensionPartFactory { get; }
// cannot use generic, at it will emit error
// Compiler Error CS0310
// The type 'typename' must have a public parameter less constructor in order to use it as parameter 'parameter' in the generic type or method 'generic'
internal sealed override OpenXmlPart NewPart(string relationshipType, string contentType)
{
ThrowIfObjectDisposed();
if (contentType == null)
{
throw new ArgumentNullException(nameof(contentType));
}
PartConstraintRule partConstraintRule;
if (GetPartConstraint().TryGetValue(relationshipType, out partConstraintRule))
{
if (!partConstraintRule.MaxOccursGreatThanOne)
{
if (this.GetSubPart(relationshipType) != null)
{
// already have one, cannot add new one.
throw new InvalidOperationException();
}
}
OpenXmlPart child = CreateOpenXmlPart(relationshipType);
child.CreateInternal(this, null, contentType, null);
// add it and get the id
string relationshipId = this.AttachChild(child);
this.ChildrenParts.Add(relationshipId, child);
return child;
}
throw new ArgumentOutOfRangeException(nameof(relationshipType));
}
internal sealed override OpenXmlPackage InternalOpenXmlPackage
{
get { return this; }
}
internal sealed override OpenXmlPart ThisOpenXmlPart
{
get { return null; }
}
// find all reachable parts from the package root, the dictionary also used for cycle reference defense
internal sealed override void FindAllReachableParts(IDictionary<OpenXmlPart, bool> reachableParts)
{
ThrowIfObjectDisposed();
if (reachableParts == null)
{
throw new ArgumentNullException(nameof(reachableParts));
}
foreach (OpenXmlPart part in this.ChildrenParts.Values)
{
if (!reachableParts.ContainsKey(part))
{
part.FindAllReachableParts(reachableParts);
}
}
}
internal sealed override void DeleteRelationship(string id)
{
ThrowIfObjectDisposed();
this.Package.DeleteRelationship(id);
}
internal sealed override PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType)
{
ThrowIfObjectDisposed();
return this.Package.CreateRelationship(targetUri, targetMode, relationshipType);
}
internal sealed override PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
ThrowIfObjectDisposed();
return this.Package.CreateRelationship(targetUri, targetMode, relationshipType, id);
}
// create the metro part in the package with the CompressionOption
internal PackagePart CreateMetroPart(Uri partUri, string contentType)
{
return this.Package.CreatePart(partUri, contentType, this.CompressionOption);
}
// default package validation event handler
static void DefaultValidationEventHandler(Object sender, OpenXmlPackageValidationEventArgs e)
{
OpenXmlPackageException exception = new OpenXmlPackageException(ExceptionMessages.ValidationException);
exception.Data.Add("OpenXmlPackageValidationEventArgs", e);
throw exception;
}
#endregion
#region methods on DataPart
private static bool IsOrphanDataPart(DataPart dataPart)
{
return !dataPart.GetDataPartReferenceRelationships().Any();
}
/// <summary>
/// Deletes all DataParts that are not referenced by any media, audio, or video reference relationships.
/// </summary>
private void DeleteUnusedDataPartOnClose()
{
if (this._dataPartList.Count > 0)
{
HashSet<DataPart> dataPartSet = new HashSet<DataPart>();
foreach (var dataPart in this.DataParts)
{
dataPartSet.Add(dataPart);
}
// first, see if there are any reference in package level.
foreach (var dataPartReferenceRelationship in this.DataPartReferenceRelationships)
{
dataPartSet.Remove(dataPartReferenceRelationship.DataPart);
if (dataPartSet.Count == 0)
{
// No more DataPart in the set. All DataParts are referenced somewhere.
return;
}
}
// for each part in the package, check the DataPartReferenceRelationships.
OpenXmlPackagePartIterator partIterator = new OpenXmlPackagePartIterator(this);
foreach (var openXmlPart in partIterator)
{
foreach (var dataPartReferenceRelationship in openXmlPart.DataPartReferenceRelationships)
{
dataPartSet.Remove(dataPartReferenceRelationship.DataPart);
if (dataPartSet.Count == 0)
{
// No more DataPart in the set. All DataParts are referenced somethwherr.
return;
}
}
}
//
foreach (var dataPart in dataPartSet)
{
// delete the part from the package
dataPart.Destroy();
this._dataPartList.Remove(dataPart);
}
}
}
/// <summary>
/// Finds the DataPart that has the specified part URI.
/// </summary>
/// <param name="partUri">The part URI.</param>
/// <returns>Returns null if there is no DataPart with the specified URI.</returns>
internal DataPart FindDataPart(Uri partUri)
{
foreach (var dataPart in this.DataParts)
{
if (dataPart.Uri == partUri)
{
return dataPart;
}
}
return null;
}
internal DataPart AddDataPartToList(DataPart dataPart)
{
this._dataPartList.AddLast(dataPart);
return dataPart;
}
#endregion
internal class PartUriHelper
{
private Dictionary<string, int> _sequenceNumbers = new Dictionary<string, int>(20);
private Dictionary<string, int> _reservedUri = new Dictionary<string, int>();
public PartUriHelper()
{
}
private bool IsReservedUri(Uri uri)
{
string uriString = uri.OriginalString.ToUpperInvariant();
return this._reservedUri.ContainsKey(uriString);
}
internal void AddToReserveUri(Uri partUri)
{
string uriString = partUri.OriginalString.ToUpperInvariant();
this._reservedUri.Add(uriString, 0);
}
internal void ReserveUri(string contentType, Uri partUri)
{
GetNextSequenceNumber(contentType);
this.AddToReserveUri(PackUriHelper.GetNormalizedPartUri(partUri));
}
internal Uri GetUniquePartUri(string contentType, Uri parentUri, string targetPath, string targetName, string targetExt)
{
Uri partUri;
do
{
string sequenceNumber = this.GetNextSequenceNumber(contentType);
string path = Path.Combine(targetPath, targetName + sequenceNumber + targetExt);
Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);
partUri = PackUriHelper.ResolvePartUri(parentUri, uri);
// partUri = PackUriHelper.GetNormalizedPartUri(PackUriHelper.CreatePartUri(uri));
} while (this.IsReservedUri(partUri));
this.AddToReserveUri(partUri);
// do not need to add to the _existedNames
return partUri;
}
internal Uri GetUniquePartUri(string contentType, Uri parentUri, Uri targetUri)
{
Uri partUri;
partUri = PackUriHelper.ResolvePartUri(parentUri, targetUri);
if (this.IsReservedUri(partUri))
{
// already have one, create new
string targetPath = ".";
string targetName = Path.GetFileNameWithoutExtension(targetUri.OriginalString);
string targetExt = Path.GetExtension(targetUri.OriginalString);
partUri = GetUniquePartUri(contentType, partUri, targetPath, targetName, targetExt);
}
else
{
// not used, can use it.
this.AddToReserveUri(partUri);
}
return partUri;
}
private string GetNextSequenceNumber(string contentType)
{
if (this._sequenceNumbers.ContainsKey(contentType))
{
this._sequenceNumbers[contentType] += 1;
// use the default read-only NumberFormatInfo that is culture-independent (invariant).
// return this._sequenceNumbers[contentType].ToString(NumberFormatInfo.InvariantInfo);
// Let's use the number string in hex
return Convert.ToString(this._sequenceNumbers[contentType], 16);
}
else
{
this._sequenceNumbers.Add(contentType, 1);
return "";
}
}
}
#region saving and cloning
#region saving
private readonly object _saveAndCloneLock = new object();
/// <summary>
/// Saves the contents of all parts and relationships that are contained
/// in the OpenXml package, if FileOpenAccess is ReadWrite.
/// </summary>
public void Save()
{
ThrowIfObjectDisposed();
if (FileOpenAccess == FileAccess.ReadWrite)
{
lock (_saveAndCloneLock)
{
SavePartContents();
// TODO: Revisit.
// Package.Flush();
}
}
}
/// <summary>
/// Saves the contents of all parts and relationships that are contained
/// in the OpenXml package to the specified file. Opens the saved document
/// using the same settings that were used to open this OpenXml package.
/// </summary>
/// <remarks>
/// Calling SaveAs(string) is exactly equivalent to calling Clone(string).
/// This method is essentially provided for convenience.
/// </remarks>
/// <param name="path">The path and file name of the target document.</param>
/// <returns>The cloned OpenXml package</returns>
public OpenXmlPackage SaveAs(string path)
{
return Clone(path);
}
#endregion saving
#region Default clone method
/// <summary>
/// Creates an editable clone of this OpenXml package, opened on a
/// <see cref="MemoryStream"/> with expandable capacity and using
/// default OpenSettings.
/// </summary>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone()
{
return Clone(new MemoryStream(), true, new OpenSettings());
}
#endregion Default clone method
#region Stream-based cloning
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// The cloned OpenXml package is opened with the same settings, i.e.,
/// FileOpenAccess and OpenSettings, as this OpenXml package.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream)
{
return Clone(stream, FileOpenAccess == FileAccess.ReadWrite, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// The cloned OpenXml package is opened with the same OpenSettings as
/// this OpenXml package.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream, bool isEditable)
{
return Clone(stream, isEditable, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the given stream.
/// </summary>
/// <param name="stream">The IO stream on which to open the OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Stream stream, bool isEditable, OpenSettings openSettings)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create new OpenXmlPackage backed by stream. Next, copy all document
// parts (AddPart will copy the parts and their children in a recursive
// fashion) and close/dispose the document (by leaving the scope of the
// using statement). Finally, reopen the clone from the MemoryStream.
// This way, writing the stream to a file, for example, directly after
// returning from this method will not lead to issues with corrupt files
// and a FileFormatException ("Compressed part has inconsistent data length")
// thrown within OpenXmlPackage.OpenCore(string, bool) by the
// this._metroPackage = Package.Open(path, ...);
// assignment.
using (OpenXmlPackage clone = CreateClone(stream))
{
foreach (var part in this.Parts)
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
return OpenClone(stream, isEditable, openSettings);
}
}
/// <summary>
/// Creates a new OpenXmlPackage on the given stream.
/// </summary>
/// <param name="stream">The stream on which the concrete OpenXml package will be created.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(Stream stream);
/// <summary>
/// Opens the cloned OpenXml package on the given stream.
/// </summary>
/// <param name="stream">The stream on which the cloned OpenXml package will be opened.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage OpenClone(Stream stream, bool isEditable, OpenSettings openSettings);
#endregion Stream-based cloning
#region File-based cloning
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file
/// (which will be created by cloning this OpenXml package).
/// The cloned OpenXml package is opened with the same settings, i.e.,
/// FileOpenAccess and OpenSettings, as this OpenXml package.
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path)
{
return Clone(path, FileOpenAccess == FileAccess.ReadWrite, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file
/// (which will be created by cloning this OpenXml package).
/// The cloned OpenXml package is opened with the same OpenSettings as
/// this OpenXml package.
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path, bool isEditable)
{
return Clone(path, isEditable, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package opened from the given file (which
/// will be created by cloning this OpenXml package).
/// </summary>
/// <param name="path">The path and file name of the target document.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned document.</returns>
public OpenXmlPackage Clone(string path, bool isEditable, OpenSettings openSettings)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Use the same approach as for the streams-based cloning, i.e., close
// and reopen the document.
using (OpenXmlPackage clone = CreateClone(path))
{
foreach (var part in this.Parts)
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
return OpenClone(path, isEditable, openSettings);
}
}
/// <summary>
/// Creates a new OpenXml package on the given file.
/// </summary>
/// <param name="path">The path and file name of the target OpenXml package.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(string path);
/// <summary>
/// Opens the cloned OpenXml package on the given file.
/// </summary>
/// <param name="path">The path and file name of the target OpenXml package.</param>
/// <param name="isEditable">In ReadWrite mode. False for Read only mode.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage OpenClone(string path, bool isEditable, OpenSettings openSettings);
#endregion File-based cloning
#region Package-based cloning
/// <summary>
/// Creates a clone of this OpenXml package, opened on the specified instance
/// of Package. The clone will be opened with the same OpenSettings as this
/// OpenXml package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Package package)
{
return Clone(package, OpenSettings);
}
/// <summary>
/// Creates a clone of this OpenXml package, opened on the specified instance
/// of Package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <param name="openSettings">The advanced settings for opening a document.</param>
/// <returns>The cloned OpenXml package.</returns>
public OpenXmlPackage Clone(Package package, OpenSettings openSettings)
{
if (package == null)
throw new ArgumentNullException(nameof(package));
// Use this OpenXml package's OpenSettings if none are provided.
// This is more in line with cloning than providing the default
// OpenSettings, i.e., unless the caller explicitly specifies
// something, we'll later open the clone with this OpenXml
// package's OpenSettings.
if (openSettings == null)
openSettings = OpenSettings;
lock (_saveAndCloneLock)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we clone a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create a new OpenXml package, copy this package's parts, and flush.
// This is different from the stream and file-based cloning, because
// we don't close the package here (whereas it will be closed in
// stream and file-based cloning to make sure the underlying stream
// or file can be read without any corruption issues directly after
// having cloned the OpenXml package).
OpenXmlPackage clone = CreateClone(package);
foreach (var part in this.Parts)
{
clone.AddPart(part.OpenXmlPart, part.RelationshipId);
}
// TODO: Revisit.
// package.Flush();
// Configure OpenSettings.
clone.OpenSettings.AutoSave = openSettings.AutoSave;
clone.OpenSettings.MarkupCompatibilityProcessSettings.ProcessMode = openSettings.MarkupCompatibilityProcessSettings.ProcessMode;
clone.OpenSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions = openSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions;
clone.MaxCharactersInPart = openSettings.MaxCharactersInPart;
return clone;
}
}
/// <summary>
/// Creates a new instance of OpenXmlPackage on the specified instance
/// of Package.
/// </summary>
/// <param name="package">The specified instance of Package.</param>
/// <returns>A new instance of OpenXmlPackage.</returns>
protected abstract OpenXmlPackage CreateClone(Package package);
#endregion Package-based cloning
#endregion saving and cloning
#region Flat OPC
private static readonly XNamespace pkg = "http://schemas.microsoft.com/office/2006/xmlPackage";
private static readonly XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
/// <summary>
/// Converts an OpenXml package in OPC format to string in Flat OPC format.
/// </summary>
/// <returns>The OpenXml package in Flat OPC format.</returns>
public string ToFlatOpcString()
{
return ToFlatOpcDocument().ToString();
}
/// <summary>
/// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
/// in Flat OPC format.
/// </summary>
/// <returns>The OpenXml package in Flat OPC format.</returns>
public abstract XDocument ToFlatOpcDocument();
/// <summary>
/// Converts an OpenXml package in OPC format to an <see cref="XDocument"/>
/// in Flat OPC format.
/// </summary>
/// <param name="instruction">The processing instruction.</param>
/// <returns>The OpenXml package in Flat OPC format.</returns>
protected XDocument ToFlatOpcDocument(XProcessingInstruction instruction)
{
// Save the contents of all parts and relationships that are contained
// in the OpenXml package to make sure we convert a consistent state.
// This will also invoke ThrowIfObjectDisposed(), so we don't need
// to call it here.
Save();
// Create an XML document with a standalone declaration, processing
// instruction (if not null), and a package root element with a
// namespace declaration and one child element for each part.
return new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
instruction,
new XElement(
pkg + "package",
new XAttribute(XNamespace.Xmlns + "pkg", pkg.ToString()),
Package.GetParts().Select(part => GetContentsAsXml(part))));
}
/// <summary>
/// Gets the <see cref="PackagePart"/>'s contents as an <see cref="XElement"/>.
/// </summary>
/// <param name="part">The package part.</param>
/// <returns>The corresponding <see cref="XElement"/>.</returns>
private static XElement GetContentsAsXml(PackagePart part)
{
if (part.ContentType.EndsWith("xml"))
{
using (Stream stream = part.GetStream())
using (StreamReader streamReader = new StreamReader(stream))
using (XmlReader xmlReader = XmlReader.Create(streamReader))
return new XElement(pkg + "part",
new XAttribute(pkg + "name", part.Uri),
new XAttribute(pkg + "contentType", part.ContentType),
new XElement(pkg + "xmlData", XElement.Load(xmlReader)));
}
else
{
using (Stream stream = part.GetStream())
using (BinaryReader binaryReader = new BinaryReader(stream))
{
int len = (int)binaryReader.BaseStream.Length;
byte[] byteArray = binaryReader.ReadBytes(len);
// The following expression creates the base64String, then chunks
// it to lines of 76 characters long.
string base64String = System.Convert.ToBase64String(byteArray)
.Select((c, i) => new { Character = c, Chunk = i / 76 })
.GroupBy(c => c.Chunk)
.Aggregate(
new StringBuilder(),
(s, i) =>
s.Append(
i.Aggregate(
new StringBuilder(),
(seed, it) => seed.Append(it.Character),
sb => sb.ToString())).Append(Environment.NewLine),
s => s.ToString());
return new XElement(pkg + "part",
new XAttribute(pkg + "name", part.Uri),
new XAttribute(pkg + "contentType", part.ContentType),
new XAttribute(pkg + "compression", "store"),
new XElement(pkg + "binaryData", base64String));
}
}
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored on a <see cref="Stream"/>.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="stream">The <see cref="Stream"/> on which to store the OpenXml package.</param>
/// <returns>The <see cref="Stream"/> containing the OpenXml package.</returns>
protected static Stream FromFlatOpcDocumentCore(XDocument document, Stream stream)
{
using (Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
{
FromFlatOpcDocumentCore(document, package);
}
return stream;
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored in a file.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="path">The path and file name of the file in which to store the OpenXml package.</param>
/// <returns>The path and file name of the file containing the OpenXml package.</returns>
protected static string FromFlatOpcDocumentCore(XDocument document, string path)
{
using (Package package = Package.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
FromFlatOpcDocumentCore(document, package);
}
return path;
}
/// <summary>
/// Converts an <see cref="XDocument"/> in Flat OPC format to an OpenXml package
/// stored in a <see cref="Package"/>.
/// </summary>
/// <param name="document">The document in Flat OPC format.</param>
/// <param name="package">The <see cref="Package"/> in which to store the OpenXml package.</param>
/// <returns>The <see cref="Package"/> containing the OpenXml package.</returns>
protected static Package FromFlatOpcDocumentCore(XDocument document, Package package)
{
// Add all parts (but not relationships).
foreach (var xmlPart in document.Root
.Elements()
.Where(p =>
(string)p.Attribute(pkg + "contentType") !=
"application/vnd.openxmlformats-package.relationships+xml"))
{
string name = (string)xmlPart.Attribute(pkg + "name");
string contentType = (string)xmlPart.Attribute(pkg + "contentType");
if (contentType.EndsWith("xml"))
{
Uri uri = new Uri(name, UriKind.Relative);
PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
using (Stream stream = part.GetStream(FileMode.Create))
using (XmlWriter xmlWriter = XmlWriter.Create(stream))
xmlPart.Element(pkg + "xmlData")
.Elements()
.First()
.WriteTo(xmlWriter);
}
else
{
Uri uri = new Uri(name, UriKind.Relative);
PackagePart part = package.CreatePart(uri, contentType, CompressionOption.SuperFast);
using (Stream stream = part.GetStream(FileMode.Create))
using (BinaryWriter binaryWriter = new BinaryWriter(stream))
{
string base64StringInChunks = (string)xmlPart.Element(pkg + "binaryData");
char[] base64CharArray = base64StringInChunks
.Where(c => c != '\r' && c != '\n').ToArray();
byte[] byteArray =
System.Convert.FromBase64CharArray(
base64CharArray, 0, base64CharArray.Length);
binaryWriter.Write(byteArray);
}
}
}
foreach (var xmlPart in document.Root.Elements())
{
string name = (string)xmlPart.Attribute(pkg + "name");
string contentType = (string)xmlPart.Attribute(pkg + "contentType");
if (contentType == "application/vnd.openxmlformats-package.relationships+xml")
{
if (name == "/_rels/.rels")
{
// Add the package level relationships.
foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
{
string id = (string)xmlRel.Attribute("Id");
string type = (string)xmlRel.Attribute("Type");
string target = (string)xmlRel.Attribute("Target");
string targetMode = (string)xmlRel.Attribute("TargetMode");
if (targetMode == "External")
package.CreateRelationship(
new Uri(target, UriKind.Absolute),
TargetMode.External, type, id);
else
package.CreateRelationship(
new Uri(target, UriKind.Relative),
TargetMode.Internal, type, id);
}
}
else
{
// Add part level relationships.
string directory = name.Substring(0, name.IndexOf("/_rels"));
string relsFilename = name.Substring(name.LastIndexOf('/'));
string filename = relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
PackagePart fromPart = package.GetPart(new Uri(directory + filename, UriKind.Relative));
foreach (XElement xmlRel in xmlPart.Descendants(rel + "Relationship"))
{
string id = (string)xmlRel.Attribute("Id");
string type = (string)xmlRel.Attribute("Type");
string target = (string)xmlRel.Attribute("Target");
string targetMode = (string)xmlRel.Attribute("TargetMode");
if (targetMode == "External")
fromPart.CreateRelationship(
new Uri(target, UriKind.Absolute),
TargetMode.External, type, id);
else
fromPart.CreateRelationship(
new Uri(target, UriKind.Relative),
TargetMode.Internal, type, id);
}
}
}
}
// Save contents of all parts and relationships contained in package.
package.Flush();
return package;
}
#endregion Flat OPC
}
/// <summary>
/// Specifies event handlers that will handle OpenXmlPackage validation events and the OpenXmlPackageValidationEventArgs.
/// </summary>
// Building on Travis CI failed, saying that ObsoleteAttributeMessages does not contain a definition
// for 'ObsoleteV1ValidationFunctionality'. Thus, we've replaced the member with its value.
[Obsolete("This functionality is obsolete and will be removed from future version release. Please see OpenXmlValidator class for supported validation functionality.", false)]
public class OpenXmlPackageValidationSettings
{
private EventHandler<OpenXmlPackageValidationEventArgs> valEventHandler;
/// <summary>
/// Gets the event handler.
/// </summary>
/// <returns></returns>
internal EventHandler<OpenXmlPackageValidationEventArgs> GetEventHandler()
{
return this.valEventHandler;
}
/// <summary>
/// Represents the callback method that will handle OpenXmlPackage validation events and the OpenXmlPackageValidationEventArgs.
/// </summary>
public event EventHandler<OpenXmlPackageValidationEventArgs> EventHandler
{
add
{
this.valEventHandler = (EventHandler<OpenXmlPackageValidationEventArgs>)Delegate.Combine(this.valEventHandler, value);
}
remove
{
this.valEventHandler = (EventHandler<OpenXmlPackageValidationEventArgs>)Delegate.Remove(this.valEventHandler, value);
}
}
/// <summary>
/// Gets or sets the file format version that the validation is targeting.
/// </summary>
internal FileFormatVersions FileFormat
{
get;
set;
}
}
/// <summary>
/// Represents the Open XML package validation events.
/// </summary>
[SerializableAttribute]
[Obsolete(ObsoleteAttributeMessages.ObsoleteV1ValidationFunctionality, false)]
public sealed class OpenXmlPackageValidationEventArgs : EventArgs
{
private string _message;
private string _partClassName;
[NonSerializedAttribute]
private OpenXmlPart _childPart;
[NonSerializedAttribute]
private OpenXmlPart _parentPart;
internal OpenXmlPackageValidationEventArgs()
{
}
/// <summary>
/// Gets the message string of the event.
/// </summary>
public string Message
{
get
{
if (this._message == null && this.MessageId != null)
{
return ExceptionMessages.ResourceManager.GetString(this.MessageId);
}
else
{
return this._message;
}
}
set
{
this._message = value;
}
}
/// <summary>
/// Gets the class name of the part.
/// </summary>
public string PartClassName
{
get { return _partClassName; }
internal set { _partClassName = value; }
}
/// <summary>
/// Gets the part that caused the event.
/// </summary>
public OpenXmlPart SubPart
{
get { return _childPart; }
internal set { _childPart = value; }
}
/// <summary>
/// Gets the part in which to process the validation.
/// </summary>
public OpenXmlPart Part
{
get { return _parentPart; }
internal set { _parentPart = value; }
}
internal string MessageId
{
get;
set;
}
/// <summary>
/// The DataPartReferenceRelationship that caused the event.
/// </summary>
internal DataPartReferenceRelationship DataPartReferenceRelationship
{
get;
set;
}
}
/// <summary>
/// Represents an Open XML package exception class for errors.
/// </summary>
[SerializableAttribute]
public sealed class OpenXmlPackageException : Exception
{
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class.
/// </summary>
public OpenXmlPackageException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied error message.
/// </summary>
/// <param name="message">The message that describes the error. </param>
public OpenXmlPackageException(string message)
: base(message)
{
}
#if FEATURE_SERIALIZATION
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied serialized data.
/// </summary>
/// <param name="info">The serialized object data about the exception being thrown.</param>
/// <param name="context">The contextual information about the source or destination.</param>
private OpenXmlPackageException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initializes a new instance of the OpenXmlPackageException class using the supplied error message and a reference to the inner exception that caused the current exception.
/// </summary>
/// <param name="message">The error message that indicates the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public OpenXmlPackageException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Represents the settings when opening a document.
/// </summary>
public class OpenSettings
{
bool? autoSave;
MarkupCompatibilityProcessSettings _mcSettings;
/// <summary>
/// Gets or sets a value that indicates whether or not to auto save document modifications.
/// The default value is true.
/// </summary>
public bool AutoSave
{
get
{
if (autoSave == null)
{
return true;
}
return (bool)autoSave;
}
set
{
autoSave = value;
}
}
/// <summary>
/// Gets or sets the value of the markup compatibility processing mode.
/// </summary>
public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
get
{
if (_mcSettings == null)
_mcSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.NoProcess, FileFormatVersions.Office2007);
return _mcSettings;
}
set
{
_mcSettings = value;
}
}
/// <summary>
/// Gets or sets a value that indicates the maximum number of allowable characters in an Open XML part. A zero (0) value indicates that there are no limits on the size of the part. A non-zero value specifies the maximum size, in characters.
/// </summary>
/// <remarks>
/// This property allows you to mitigate denial of service attacks where the attacker submits a package with an extremely large Open XML part. By limiting the size of the part, you can detect the attack and recover reliably.
/// </remarks>
public long MaxCharactersInPart { get; set; }
}
/// <summary>
/// Represents markup compatibility processing settings.
/// </summary>
public class MarkupCompatibilityProcessSettings
{
/// <summary>
/// Gets the markup compatibility process mode.
/// </summary>
public MarkupCompatibilityProcessMode ProcessMode { get; internal set; }
/// <summary>
/// Gets the target file format versions.
/// </summary>
public FileFormatVersions TargetFileFormatVersions { get; internal set; }
/// <summary>
/// Creates a MarkupCompatibilityProcessSettings object using the supplied process mode and file format versions.
/// </summary>
/// <param name="processMode">The process mode.</param>
/// <param name="targetFileFormatVersions">The file format versions. This parameter is ignored if the value is NoProcess.</param>
public MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode processMode, FileFormatVersions targetFileFormatVersions)
{
ProcessMode = processMode;
TargetFileFormatVersions = targetFileFormatVersions;
}
private MarkupCompatibilityProcessSettings()
{
ProcessMode = MarkupCompatibilityProcessMode.NoProcess;
TargetFileFormatVersions = FileFormatVersions.Office2007;
}
}
/// <summary>
/// Specifies the mode in which to process the markup compatibility tags in the document.
/// </summary>
public enum MarkupCompatibilityProcessMode
{
/// <summary>
/// Do not process MarkupCompatibility tags.
/// </summary>
NoProcess = 0,
/// <summary>
/// Process the loaded parts.
/// </summary>
ProcessLoadedPartsOnly,
/// <summary>
/// Process all the parts in the package.
/// </summary>
ProcessAllParts,
}
/// <summary>
/// Traversal parts in the <see cref="OpenXmlPackage"/> by breadth-first.
/// </summary>
internal class OpenXmlPackagePartIterator : IEnumerable<OpenXmlPart>
{
private OpenXmlPackage _package;
#region Constructor
/// <summary>
/// Initializes a new instance of the OpenXmlPackagePartIterator class using the supplied OpenXmlPackage class.
/// </summary>
/// <param name="package">The OpenXmlPackage to use to enumerate parts.</param>
public OpenXmlPackagePartIterator(OpenXmlPackage package)
{
Debug.Assert(package != null);
this._package = package;
}
#endregion
#region IEnumerable<OpenXmlPart> Members
/// <summary>
/// Gets an enumerator for parts in the whole package.
/// </summary>
/// <returns></returns>
public IEnumerator<OpenXmlPart> GetEnumerator()
{
return GetPartsByBreadthFirstTraversal();
}
// Traverses the parts graph by breath-first
private IEnumerator<OpenXmlPart> GetPartsByBreadthFirstTraversal()
{
Debug.Assert(_package != null);
var returnedParts = new List<OpenXmlPart>();
Queue<OpenXmlPart> tmpQueue = new Queue<OpenXmlPart>();
// Enqueue child parts of the package.
foreach (var idPartPair in _package.Parts)
{
tmpQueue.Enqueue(idPartPair.OpenXmlPart);
}
while (tmpQueue.Count > 0)
{
var part = tmpQueue.Dequeue();
returnedParts.Add(part);
foreach (var subIdPartPair in part.Parts)
{
if (!tmpQueue.Contains(subIdPartPair.OpenXmlPart)
&& !returnedParts.Contains(subIdPartPair.OpenXmlPart))
{
tmpQueue.Enqueue(subIdPartPair.OpenXmlPart);
}
}
}
return returnedParts.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Gets an enumerator for parts in the whole package.
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| tarunchopra/Open-XML-SDK | DocumentFormat.OpenXml/src/Framework/OpenXmlPackage.cs | C# | apache-2.0 | 95,907 |
/**************************************************************************
* Mask.java is part of Touch4j 4.0. Copyright 2012 Emitrom LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
**************************************************************************/
package com.emitrom.touch4j.client.ui;
import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.config.Attribute;
import com.emitrom.touch4j.client.core.config.Event;
import com.emitrom.touch4j.client.core.config.XType;
import com.emitrom.touch4j.client.core.handlers.CallbackRegistration;
import com.emitrom.touch4j.client.core.handlers.mask.MaskTapHandler;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A simple class used to mask any Container. This should rarely be used
* directly, instead look at the Container.mask configuration.
*
* @see <a href=http://docs.sencha.com/touch/2-0/#!/api/Ext.Mask>Ext.Mask</a>
*/
public class Mask extends Component {
@Override
protected native void init()/*-{
var c = new $wnd.Ext.Mask();
[email protected]::configPrototype = c.initialConfig;
}-*/;
@Override
public String getXType() {
return XType.MASK.getValue();
}
@Override
protected native JavaScriptObject create(JavaScriptObject config) /*-{
return new $wnd.Ext.Mask(config);
}-*/;
public Mask() {
}
protected Mask(JavaScriptObject jso) {
super(jso);
}
/**
* True to make this mask transparent.
*
* Defaults to: false
*
* @param value
*/
public void setTransparent(String value) {
setAttribute(Attribute.TRANSPARENT.getValue(), value, true);
}
/**
* A tap event fired when a user taps on this mask
*
* @param handler
*/
public CallbackRegistration addTapHandler(MaskTapHandler handler) {
return this.addWidgetListener(Event.TAP.getValue(), handler.getJsoPeer());
}
}
| paulvi/touch4j | src/com/emitrom/touch4j/client/ui/Mask.java | Java | apache-2.0 | 2,495 |
// lightbox_plus.js
// == written by Takuya Otani <[email protected]> ===
// == Copyright (C) 2006 SimpleBoxes/SerendipityNZ Ltd. ==
/*
Copyright (C) 2006 Takuya Otani/SimpleBoxes - http://serennz.cool.ne.jp/sb/
Copyright (C) 2006 SerendipityNZ - http://serennz.cool.ne.jp/snz/
This script is licensed under the Creative Commons Attribution 2.5 License
http://creativecommons.org/licenses/by/2.5/
basically, do anything you want, just leave my name and link.
*/
/*
Original script : Lightbox JS : Fullsize Image Overlays
Copyright (C) 2005 Lokesh Dhakar - http://www.huddletogether.com
For more information on this script, visit:
http://huddletogether.com/projects/lightbox/
*/
// ver. 20061027 - fixed a bug ( not work at xhml documents on Netscape7 )
// ver. 20061026 - fixed bugs
// ver. 20061010 - implemented image set feature
// ver. 20060921 - fixed a bug / added overall view
// ver. 20060920 - added flag to prevent mouse wheel event
// ver. 20060919 - fixed a bug
// ver. 20060918 - implemented functionality of wheel zoom & drag'n drop
// ver. 20060131 - fixed a bug to work correctly on Internet Explorer for Windows
// ver. 20060128 - implemented functionality of echoic word
// ver. 20060120 - implemented functionality of caption and close button
function WindowSize()
{ // window size object
this.w = 0;
this.h = 0;
return this.update();
}
WindowSize.prototype.update = function()
{
var d = document;
this.w =
(window.innerWidth) ? window.innerWidth
: (d.documentElement && d.documentElement.clientWidth) ? d.documentElement.clientWidth
: d.body.clientWidth;
this.h =
(window.innerHeight) ? window.innerHeight
: (d.documentElement && d.documentElement.clientHeight) ? d.documentElement.clientHeight
: d.body.clientHeight;
return this;
};
function PageSize()
{ // page size object
this.win = new WindowSize();
this.w = 0;
this.h = 0;
return this.update();
}
PageSize.prototype.update = function()
{
var d = document;
this.w =
(window.innerWidth && window.scrollMaxX) ? window.innerWidth + window.scrollMaxX
: (d.body.scrollWidth > d.body.offsetWidth) ? d.body.scrollWidth
: d.body.offsetWidt;
this.h =
(window.innerHeight && window.scrollMaxY) ? window.innerHeight + window.scrollMaxY
: (d.body.scrollHeight > d.body.offsetHeight) ? d.body.scrollHeight
: d.body.offsetHeight;
this.win.update();
if (this.w < this.win.w) this.w = this.win.w;
if (this.h < this.win.h) this.h = this.win.h;
return this;
};
function PagePos()
{ // page position object
this.x = 0;
this.y = 0;
return this.update();
}
PagePos.prototype.update = function()
{
var d = document;
this.x =
(window.pageXOffset) ? window.pageXOffset
: (d.documentElement && d.documentElement.scrollLeft) ? d.documentElement.scrollLeft
: (d.body) ? d.body.scrollLeft
: 0;
this.y =
(window.pageYOffset) ? window.pageYOffset
: (d.documentElement && d.documentElement.scrollTop) ? d.documentElement.scrollTop
: (d.body) ? d.body.scrollTop
: 0;
return this;
};
function LightBox(option)
{
var self = this;
self._imgs = [];
self._sets = [];
self._wrap = null;
self._box = null;
self._img = null;
self._open = -1;
self._page = new PageSize();
self._pos = new PagePos();
self._zoomimg = null;
self._expandable = false;
self._expanded = false;
self._funcs = {'move':null,'up':null,'drag':null,'wheel':null,'dbl':null};
self._level = 1;
self._curpos = {x:0,y:0};
self._imgpos = {x:0,y:0};
self._minpos = {x:0,y:0};
self._expand = option.expandimg;
self._shrink = option.shrinkimg;
self._resizable = option.resizable;
self._timer = null;
self._indicator = null;
self._overall = null;
self._openedset = null;
self._prev = null;
self._next = null;
self._hiding = [];
self._first = false;
return self._init(option);
}
LightBox.prototype = {
_init : function(option)
{
var self = this;
var d = document;
if (!d.getElementsByTagName) return;
if (Browser.isMacIE) return self;
var links = d.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var anchor = links[i];
var num = self._imgs.length;
var rel = String(anchor.getAttribute("rel")).toLowerCase();
if (!anchor.getAttribute("href") || !rel.match('lightbox')) continue;
// initialize item
self._imgs[num] = {
src:anchor.getAttribute("href"),
w:-1,
h:-1,
title:'',
cls:anchor.className,
set:rel
};
if (anchor.getAttribute("title"))
self._imgs[num].title = anchor.getAttribute("title");
else if (anchor.firstChild
&& anchor.firstChild.getAttribute
&& anchor.firstChild.getAttribute("title"))
self._imgs[num].title = anchor.firstChild.getAttribute("title");
anchor.onclick = self._genOpener(num);
// set closure to onclick event
if (rel != 'lightbox')
{
if (!self._sets[rel]) self._sets[rel] = [];
self._sets[rel].push(num);
}
}
var body = d.getElementsByTagName("body")[0];
self._wrap = self._createWrapOn(body, option.loadingimg);
self._box = self._createBoxOn(body, option);
self._img = self._box.firstChild;
self._zoomimg = d.getElementById('actionImage');
return self;
},
_genOpener : function(num)
{
var self = this;
return function() {
self._show(num);
return false;
}
},
_createWrapOn : function(obj, imagePath)
{
var self = this;
if (!obj) return null;
// create wrapper object, translucent background
var wrap = document.createElement('div');
obj.appendChild(wrap);
wrap.id = 'overlay';
wrap.style.display = 'none';
wrap.style.position = 'fixed';
wrap.style.top = '0px';
wrap.style.left = '0px';
wrap.style.zIndex = '50';
wrap.style.width = '100%';
wrap.style.height = '100%';
if (Browser.isWinIE) wrap.style.position = 'absolute';
Event.register(wrap, "click", function(evt) {
self._close(evt);
});
// create loading image, animated image
var imag = new Image;
imag.onload = function() {
var spin = document.createElement('img');
wrap.appendChild(spin);
spin.id = 'loadingImage';
spin.src = imag.src;
spin.style.position = 'relative';
self._set_cursor(spin);
Event.register(spin, 'click', function(evt) {
self._close(evt);
});
imag.onload = function() {
};
};
if (imagePath != '') imag.src = imagePath;
return wrap;
},
_createBoxOn : function(obj, option)
{
var self = this;
if (!obj) return null;
// create lightbox object, frame rectangle
var box = document.createElement('div');
obj.appendChild(box);
box.id = 'lightbox';
box.style.display = 'none';
box.style.position = 'absolute';
box.style.zIndex = '60';
// create image object to display a target image
var img = document.createElement('img');
box.appendChild(img);
img.id = 'lightboxImage';
self._set_cursor(img);
Event.register(img, 'mouseover', function() {
self._show_action();
});
Event.register(img, 'mouseout', function() {
self._hide_action();
});
Event.register(img, 'click', function(evt) {
self._close(evt);
});
// create hover navi - prev
if (option.previmg)
{
var prevLink = document.createElement('img');
box.appendChild(prevLink);
prevLink.id = 'prevLink';
prevLink.style.display = 'none';
prevLink.style.position = 'absolute';
prevLink.style.left = '9px';
prevLink.style.zIndex = '70';
prevLink.src = option.previmg;
self._prev = prevLink;
Event.register(prevLink, 'mouseover', function() {
self._show_action();
});
Event.register(prevLink, 'click', function() {
self._show_next(-1);
});
}
// create hover navi - next
if (option.nextimg)
{
var nextLink = document.createElement('img');
box.appendChild(nextLink);
nextLink.id = 'nextLink';
nextLink.style.display = 'none';
nextLink.style.position = 'absolute';
nextLink.style.right = '9px';
nextLink.style.zIndex = '70';
nextLink.src = option.nextimg;
self._next = nextLink;
Event.register(nextLink, 'mouseover', function() {
self._show_action();
});
Event.register(nextLink, 'click', function() {
self._show_next(+1);
});
}
// create zoom indicator
var zoom = document.createElement('img');
box.appendChild(zoom);
zoom.id = 'actionImage';
zoom.style.display = 'none';
zoom.style.position = 'absolute';
zoom.style.top = '15px';
zoom.style.left = '15px';
zoom.style.zIndex = '70';
self._set_cursor(zoom);
zoom.src = self._expand;
Event.register(zoom, 'mouseover', function() {
self._show_action();
});
Event.register(zoom, 'click', function() {
self._zoom();
});
Event.register(window, 'resize', function() {
self._set_size(true);
});
// create close button
if (option.closeimg)
{
var btn = document.createElement('img');
box.appendChild(btn);
btn.id = 'closeButton';
btn.style.display = 'inline';
btn.style.position = 'absolute';
btn.style.right = '9px';
btn.style.top = '10px';
btn.style.zIndex = '80';
btn.src = option.closeimg;
self._set_cursor(btn);
Event.register(btn, 'click', function(evt) {
self._close(evt);
});
}
// caption text
var caption = document.createElement('span');
box.appendChild(caption);
caption.id = 'lightboxCaption';
caption.style.display = 'none';
caption.style.position = 'absolute';
caption.style.zIndex = '80';
// create effect image
/* if (!option.effectpos)
option.effectpos = {x:0,y:0};
else
{
if (option.effectpos.x == '') option.effectpos.x = 0;
if (option.effectpos.y == '') option.effectpos.y = 0;
}
var effect = new Image;
effect.onload = function()
{
var effectImg = document.createElement('img');
box.appendChild(effectImg);
effectImg.id = 'effectImage';
effectImg.src = effect.src;
if (option.effectclass) effectImg.className = option.effectclass;
effectImg.style.position = 'absolute';
effectImg.style.display = 'none';
effectImg.style.left = [option.effectpos.x,'px'].join('');;
effectImg.style.top = [option.effectpos.y,'px'].join('');
effectImg.style.zIndex = '90';
self._set_cursor(effectImg);
Event.register(effectImg,'click',function() { effectImg.style.display = 'none'; });
};
if (option.effectimg != '') effect.src = option.effectimg;*/
if (self._resizable)
{
var overall = document.createElement('div');
obj.appendChild(overall);
overall.id = 'lightboxOverallView';
overall.style.display = 'none';
overall.style.position = 'absolute';
overall.style.zIndex = '70';
self._overall = overall;
var indicator = document.createElement('div');
obj.appendChild(indicator);
indicator.id = 'lightboxIndicator';
indicator.style.display = 'none';
indicator.style.position = 'absolute';
indicator.style.zIndex = '80';
self._indicator = indicator;
}
return box;
},
_set_photo_size : function()
{
var self = this;
if (self._open == -1) return;
var targ = { w:self._page.win.w - 30, h:self._page.win.h - 30 };
var zoom = { x:15, y:15 };
var navi = { p:9, n:9, y:0 };
if (!self._expanded)
{ // shrink image with the same aspect
var orig = { w:self._imgs[self._open].w, h:self._imgs[self._open].h };
var ratio = 1.0;
if ((orig.w >= targ.w || orig.h >= targ.h) && orig.h && orig.w)
ratio = ((targ.w / orig.w) < (targ.h / orig.h)) ? targ.w / orig.w : targ.h / orig.h;
self._img.width = Math.floor(orig.w * ratio);
self._img.height = Math.floor(orig.h * ratio);
self._expandable = (ratio < 1.0) ? true : false;
if (self._resizable) self._expandable = true;
if (Browser.isWinIE) self._box.style.display = "block";
self._imgpos.x = self._pos.x + (targ.w - self._img.width) / 2;
self._imgpos.y = self._pos.y + (targ.h - self._img.height) / 2;
navi.y = Math.floor(self._img.height / 2) - 10;
self._show_caption(true);
self._show_overall(false);
}
else
{ // zoomed or actual sized image
var width = parseInt(self._imgs[self._open].w * self._level);
var height = parseInt(self._imgs[self._open].h * self._level);
self._minpos.x = self._pos.x + targ.w - width;
self._minpos.y = self._pos.y + targ.h - height;
if (width <= targ.w)
self._imgpos.x = self._pos.x + (targ.w - width) / 2;
else
{
if (self._imgpos.x > self._pos.x) self._imgpos.x = self._pos.x;
else if (self._imgpos.x < self._minpos.x) self._imgpos.x = self._minpos.x;
zoom.x = 15 + self._pos.x - self._imgpos.x;
navi.p = self._pos.x - self._imgpos.x - 5;
navi.n = width - self._page.win.w + self._imgpos.x + 25;
if (Browser.isWinIE) navi.n -= 10;
}
if (height <= targ.h)
{
self._imgpos.y = self._pos.y + (targ.h - height) / 2;
navi.y = Math.floor(self._img.height / 2) - 10;
}
else
{
if (self._imgpos.y > self._pos.y) self._imgpos.y = self._pos.y;
else if (self._imgpos.y < self._minpos.y) self._imgpos.y = self._minpos.y;
zoom.y = 15 + self._pos.y - self._imgpos.y;
navi.y = Math.floor(targ.h / 2) - 10 + self._pos.y - self._imgpos.y;
}
self._img.width = width;
self._img.height = height;
self._show_caption(false);
self._show_overall(true);
}
self._box.style.left = [self._imgpos.x,'px'].join('');
self._box.style.top = [self._imgpos.y,'px'].join('');
self._zoomimg.style.left = [zoom.x,'px'].join('');
self._zoomimg.style.top = [zoom.y,'px'].join('');
self._wrap.style.left = self._pos.x;
if (self._prev && self._next)
{
self._prev.style.left = [navi.p,'px'].join('');
self._next.style.right = [navi.n,'px'].join('');
self._prev.style.top = self._next.style.top = [navi.y,'px'].join('');
}
},
_show_overall : function(visible)
{
var self = this;
if (self._overall == null) return;
if (visible)
{
if (self._open == -1) return;
var base = 100;
var outer = { w:0, h:0, x:0, y:0 };
var inner = { w:0, h:0, x:0, y:0 };
var orig = { w:self._img.width , h:self._img.height };
var targ = { w:self._page.win.w - 30, h:self._page.win.h - 30 };
var max = orig.w;
if (max < orig.h) max = orig.h;
if (max < targ.w) max = targ.w;
if (max < targ.h) max = targ.h;
if (max < 1) return;
outer.w = parseInt(orig.w / max * base);
outer.h = parseInt(orig.h / max * base);
inner.w = parseInt(targ.w / max * base);
inner.h = parseInt(targ.h / max * base);
outer.x = self._pos.x + targ.w - base - 20;
outer.y = self._pos.y + targ.h - base - 20;
inner.x = outer.x - parseInt((self._imgpos.x - self._pos.x) / max * base);
inner.y = outer.y - parseInt((self._imgpos.y - self._pos.y) / max * base);
self._overall.style.left = [outer.x,'px'].join('');
self._overall.style.top = [outer.y,'px'].join('');
self._overall.style.width = [outer.w,'px'].join('');
self._overall.style.height = [outer.h,'px'].join('');
self._indicator.style.left = [inner.x,'px'].join('');
self._indicator.style.top = [inner.y,'px'].join('');
self._indicator.style.width = [inner.w,'px'].join('');
self._indicator.style.height = [inner.h,'px'].join('');
self._overall.style.display = 'block'
self._indicator.style.display = 'block';
}
else
{
self._overall.style.display = 'none';
self._indicator.style.display = 'none';
}
},
_set_size : function(onResize)
{
var self = this;
if (self._open == -1) return;
self._page.update();
self._pos.update();
var spin = self._wrap.firstChild;
if (spin)
{
var top = (self._page.win.h - spin.height) / 2;
if (self._wrap.style.position == 'absolute') top += self._pos.y;
spin.style.top = [top,'px'].join('');
spin.style.left = [(self._page.win.w - spin.width - 30) / 2,'px'].join('');
}
if (Browser.isWinIE)
{
self._wrap.style.width = [self._page.win.w,'px'].join('');
self._wrap.style.height = [self._page.win.h,'px'].join('');
self._wrap.style.top = [self._pos.y,'px'].join('');
}
if (onResize) self._set_photo_size();
},
_set_cursor : function(obj)
{
var self = this;
if (Browser.isWinIE && !Browser.isNewIE) return;
obj.style.cursor = 'pointer';
},
_current_setindex : function()
{
var self = this;
if (!self._openedset) return -1;
var list = self._sets[self._openedset];
for (var i = 0,n = list.length; i < n; i++)
{
if (list[i] == self._open) return i;
}
return -1;
},
_get_setlength : function()
{
var self = this;
if (!self._openedset) return -1;
return self._sets[self._openedset].length;
},
_show_action : function()
{
var self = this;
if (self._open == -1 || !self._expandable) return;
if (!self._zoomimg) return;
self._zoomimg.src = (self._expanded) ? self._shrink : self._expand;
self._zoomimg.style.display = 'inline';
var check = self._current_setindex();
if (check > -1)
{
if (check > 0) self._prev.style.display = 'inline';
if (check < self._get_setlength() - 1) self._next.style.display = 'inline';
}
},
_hide_action : function()
{
var self = this;
if (self._zoomimg) self._zoomimg.style.display = 'none';
if (self._open > -1 && self._expanded) self._dragstop(null);
if (self._prev) self._prev.style.display = 'none';
if (self._next) self._next.style.display = 'none';
},
_zoom : function()
{
var self = this;
var closeBtn = document.getElementById('closeButton');
if (self._expanded)
{
self._reset_func();
self._expanded = false;
if (closeBtn) closeBtn.style.display = 'inline';
}
else if (self._open > -1)
{
self._level = 1;
self._imgpos.x = self._pos.x;
self._imgpos.y = self._pos.y;
self._expanded = true;
self._funcs.drag = function(evt) {
self._dragstart(evt)
};
self._funcs.dbl = function(evt) {
self._close(null)
};
if (self._resizable)
{
self._funcs.wheel = function(evt) {
self._onwheel(evt)
};
Event.register(self._box, 'mousewheel', self._funcs.wheel);
}
Event.register(self._img, 'mousedown', self._funcs.drag);
Event.register(self._img, 'dblclick', self._funcs.dbl);
if (closeBtn) closeBtn.style.display = 'none';
}
self._set_photo_size();
self._show_action();
},
_reset_func : function()
{
var self = this;
if (self._funcs.wheel != null) Event.deregister(self._box, 'mousewheel', self._funcs.wheel);
if (self._funcs.move != null) Event.deregister(self._img, 'mousemove', self._funcs.move);
if (self._funcs.up != null) Event.deregister(self._img, 'mouseup', self._funcs.up);
if (self._funcs.drag != null) Event.deregister(self._img, 'mousedown', self._funcs.drag);
if (self._funcs.dbl != null) Event.deregister(self._img, 'dblclick', self._funcs.dbl);
self._funcs = {'move':null,'up':null,'drag':null,'wheel':null,'dbl':null};
},
_onwheel : function(evt)
{
var self = this;
var delta = 0;
evt = Event.getEvent(evt);
if (evt.wheelDelta) delta = event.wheelDelta / -120;
else if (evt.detail) delta = evt.detail / 3;
if (Browser.isOpera) delta = - delta;
var step =
(self._level < 1) ? 0.1
: (self._level < 2) ? 0.25
: (self._level < 4) ? 0.5
: 1;
self._level = (delta > 0) ? self._level + step : self._level - step;
if (self._level > 8) self._level = 8;
else if (self._level < 0.5) self._level = 0.5;
self._set_photo_size();
return Event.stop(evt);
},
_dragstart : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
self._curpos.x = evt.screenX;
self._curpos.y = evt.screenY;
self._funcs.move = function(evnt) {
self._dragging(evnt);
};
self._funcs.up = function(evnt) {
self._dragstop(evnt);
};
Event.register(self._img, 'mousemove', self._funcs.move);
Event.register(self._img, 'mouseup', self._funcs.up);
return Event.stop(evt);
},
_dragging : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
self._imgpos.x += evt.screenX - self._curpos.x;
self._imgpos.y += evt.screenY - self._curpos.y;
self._curpos.x = evt.screenX;
self._curpos.y = evt.screenY;
self._set_photo_size();
return Event.stop(evt);
},
_dragstop : function(evt)
{
var self = this;
evt = Event.getEvent(evt);
if (self._funcs.move != null) Event.deregister(self._img, 'mousemove', self._funcs.move);
if (self._funcs.up != null) Event.deregister(self._img, 'mouseup', self._funcs.up);
self._funcs.move = null;
self._funcs.up = null;
self._set_photo_size();
return (evt) ? Event.stop(evt) : false;
},
_show_caption : function(enable)
{
var self = this;
var caption = document.getElementById('lightboxCaption');
if (!caption) return;
if (caption.innerHTML.length == 0 || !enable)
{
caption.style.display = 'none';
}
else
{ // now display caption
caption.style.top = [self._img.height + 10,'px'].join('');
// 10 is top margin of lightbox
caption.style.left = '0px';
caption.style.width = [self._img.width + 20,'px'].join('');
// 20 is total side margin of lightbox
caption.style.display = 'block';
}
},
_toggle_wrap : function(flag)
{
var self = this;
self._wrap.style.display = flag ? "block" : "none";
if (self._hiding.length == 0 && !self._first)
{ // some objects may overlap on overlay, so we hide them temporarily.
var tags = ['select','embed','object'];
for (var i = 0,n = tags.length; i < n; i++)
{
var elem = document.getElementsByTagName(tags[i]);
for (var j = 0,m = elem.length; j < m; j++)
{ // check the original value at first. when alredy hidden, dont touch them
var check = elem[j].style.visibility;
if (!check)
{
if (elem[j].currentStyle)
check = elem[j].currentStyle['visibility'];
else if (document.defaultView)
check = document.defaultView.getComputedStyle(elem[j], '').getPropertyValue('visibility');
}
if (check == 'hidden') continue;
self._hiding.push(elem[j]);
}
}
self._first = true;
}
for (var i = 0,n = self._hiding.length; i < n; i++)
self._hiding[i].style.visibility = flag ? "hidden" : "visible";
},
_show : function(num)
{
var self = this;
var imag = new Image;
if (num < 0 || num >= self._imgs.length) return;
var loading = document.getElementById('loadingImage');
var caption = document.getElementById('lightboxCaption');
// var effect = document.getElementById('effectImage');
self._open = num;
// set opened image number
self._set_size(false);
// calc and set wrapper size
self._toggle_wrap(true);
if (loading) loading.style.display = 'inline';
imag.onload = function() {
if (self._imgs[self._open].w == -1)
{ // store original image width and height
self._imgs[self._open].w = imag.width;
self._imgs[self._open].h = imag.height;
}
/* if (effect)
{
effect.style.display = (!effect.className || self._imgs[self._open].cls == effect.className)
? 'block' : 'none';
}*/
if (caption)
try {
caption.innerHTML = self._imgs[self._open].title;
} catch(e) {
}
self._set_photo_size();
// calc and set lightbox size
self._hide_action();
self._box.style.display = "block";
self._img.src = imag.src;
self._img.setAttribute('title', self._imgs[self._open].title);
self._timer = window.setInterval(function() {
self._set_size(true)
}, 100);
if (loading) loading.style.display = 'none';
if (self._imgs[self._open].set != 'lightbox')
{
var set = self._imgs[self._open].set;
if (self._sets[set].length > 1) self._openedset = set;
if (!self._prev || !self._next) self._openedset = null;
}
};
self._expandable = false;
self._expanded = false;
imag.src = self._imgs[self._open].src;
},
_close_box : function()
{
var self = this;
self._open = -1;
self._openedset = null;
self._hide_action();
self._hide_action();
self._reset_func();
self._show_overall(false);
self._box.style.display = "none";
if (self._timer != null)
{
window.clearInterval(self._timer);
self._timer = null;
}
},
_show_next : function(direction)
{
var self = this;
if (!self._openedset) return self._close(null);
var index = self._current_setindex() + direction;
var targ = self._sets[self._openedset][index];
self._close_box();
self._show(targ);
},
_close : function(evt)
{
var self = this;
if (evt != null)
{
evt = Event.getEvent(evt);
var targ = evt.target || evt.srcElement;
if (targ && targ.getAttribute('id') == 'lightboxImage' && self._expanded) return;
}
self._close_box();
self._toggle_wrap(false);
}
};
Event.register(window, "load", function() {
var lightbox = new LightBox({
loadingimg:'lightbox/loading.gif',
expandimg:'lightbox/expand.gif',
shrinkimg:'lightbox/shrink.gif',
previmg:'lightbox/prev.gif',
nextimg:'lightbox/next.gif',
/* effectpos:{x:-40,y:-20},
effectclass:'effectable',*/
closeimg:'lightbox/close.gif',
resizable:true
});
});
| yusuke/samurai | site/lightbox/lightbox_plus.js | JavaScript | apache-2.0 | 29,978 |
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util.trace.uploader.launcher;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.env.BuckClasspath;
import com.facebook.buck.util.trace.uploader.types.CompressionType;
import com.google.common.base.Strings;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
/** Utility to upload chrome trace in background. */
public class UploaderLauncher {
private static final Logger LOG = Logger.get(UploaderLauncher.class);
/** Upload chrome trace in background process which runs even after current process dies. */
public static void uploadInBackground(
BuildId buildId,
Path traceFilePath,
String traceFileKind,
URI traceUploadUri,
Path logFile,
CompressionType compressionType) {
LOG.debug("Uploading build trace in the background. Upload will log to %s", logFile);
String buckClasspath = BuckClasspath.getBuckClasspathFromEnvVarOrNull();
if (Strings.isNullOrEmpty(buckClasspath)) {
LOG.error(
BuckClasspath.ENV_VAR_NAME + " env var is not set. Will not upload the trace file.");
return;
}
try {
String[] args = {
"java",
"-cp",
buckClasspath,
"com.facebook.buck.util.trace.uploader.Main",
"--buildId",
buildId.toString(),
"--traceFilePath",
traceFilePath.toString(),
"--traceFileKind",
traceFileKind,
"--baseUrl",
traceUploadUri.toString(),
"--log",
logFile.toString(),
"--compressionType",
compressionType.name(),
};
Runtime.getRuntime().exec(args);
} catch (IOException e) {
LOG.error(e, e.getMessage());
}
}
}
| LegNeato/buck | src/com/facebook/buck/util/trace/uploader/launcher/UploaderLauncher.java | Java | apache-2.0 | 2,379 |
/*
* Copyright 2013, Google 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 Google 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 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.
*/
package org.jf.dexlib2.builder;
import org.jf.dexlib2.*;
import org.jf.dexlib2.builder.instruction.*;
import org.jf.dexlib2.iface.instruction.*;
import java.util.*;
import javax.annotation.*;
public abstract class BuilderSwitchPayload extends BuilderInstruction implements SwitchPayload {
@Nullable
MethodLocation referrer;
protected BuilderSwitchPayload(@Nonnull Opcode opcode) {
super(opcode);
}
@Nonnull
public MethodLocation getReferrer() {
if (referrer == null) {
throw new IllegalStateException("The referrer has not been set yet");
}
return referrer;
}
@Nonnull
@Override
public abstract List<? extends BuilderSwitchElement> getSwitchElements();
}
| nao20010128nao/show-java | app/src/main/java/org/jf/dexlib2/builder/BuilderSwitchPayload.java | Java | apache-2.0 | 2,310 |
fraggle-sample
==============
A demonstration of Fraggle capabilities. [Fraggle](http://fraggle.sefford.com/) is a wrapper to Android's FragmentManager that encapsulates
common logic used over the applications.
This project is just a sample project demonstration of its capabilities
Usage
-----
Clone the repo and execute `mvn clean install`. It requires internet connection to download its
dependencies, Fraggle itself.
You can install it to an emulator or phone via `mvn android:deploy android:run`. It requires an
Android device with API 15 or superior.
Fraggle-Sample will not require any specific permissions
Explanation
-----------
Once you open the Sample you will be presented with an Activity that shows a Fragment. The Fragment
number will be incremental from the current Fragment. The name and the strip of the bottom serves
as identification of different Fragments.
Clicking on the button will create and add a new Fragment configurable via some options.
You are presented every time with four selectable options:
- Selecting `Make it return to First` will create a fragment whose onBackTarget returns the Fragment #1 to showcase the custom flow return.
- If `Is Single Instance` is selected will create a `Fragment #1` instance and will force Fraggle to pop back to the initial Fragment.
- `Show a Toast on Back` will open a Fragment that first will show a Toast, then go back to demonstrate the feature of custom actions on backPressed.
- If `Is Entry Fragment` a Fragment will create a Fragment that will trigger Fraggle to reach an Activity `finish()` termination by pressing the back buttons.
For more information about the concepts discussed, visit [Fraggle page](http://fraggle.sefford.com/)
License
-------
Copyright 2014 Sefford.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Sefford/fraggle-sample | README.md | Markdown | apache-2.0 | 2,329 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Google Chrome Cache files event formatter."""
import unittest
from plaso.formatters import chrome_cache
from tests.formatters import test_lib
class ChromeCacheEntryEventFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Chrome Cache entry event formatter."""
def testInitialization(self):
"""Tests the initialization."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
self.assertIsNotNone(event_formatter)
def testGetFormatStringAttributeNames(self):
"""Tests the GetFormatStringAttributeNames function."""
event_formatter = chrome_cache.ChromeCacheEntryEventFormatter()
expected_attribute_names = [u'original_url']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ == '__main__':
unittest.main()
| dc3-plaso/plaso | tests/formatters/chrome_cache.py | Python | apache-2.0 | 925 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:25 EEST 2014 -->
<title>Uses of Interface net.sf.jasperreports.engine.export.oasis.GenericElementOdtHandler (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<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="Uses of Interface net.sf.jasperreports.engine.export.oasis.GenericElementOdtHandler (JasperReports 5.6.0 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><a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sf/jasperreports/engine/export/oasis/class-use/GenericElementOdtHandler.html" target="_top">Frames</a></li>
<li><a href="GenericElementOdtHandler.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface net.sf.jasperreports.engine.export.oasis.GenericElementOdtHandler" class="title">Uses of Interface<br>net.sf.jasperreports.engine.export.oasis.GenericElementOdtHandler</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">GenericElementOdtHandler</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.iconlabel">net.sf.jasperreports.components.iconlabel</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in Icon Label component.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.map">net.sf.jasperreports.components.map</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in Google Map component.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sf.jasperreports.components.iconlabel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">GenericElementOdtHandler</a> in <a href="../../../../../../../net/sf/jasperreports/components/iconlabel/package-summary.html">net.sf.jasperreports.components.iconlabel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../net/sf/jasperreports/components/iconlabel/package-summary.html">net.sf.jasperreports.components.iconlabel</a> that implement <a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">GenericElementOdtHandler</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../net/sf/jasperreports/components/iconlabel/IconLabelElementOdtHandler.html" title="class in net.sf.jasperreports.components.iconlabel">IconLabelElementOdtHandler</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.components.map">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">GenericElementOdtHandler</a> in <a href="../../../../../../../net/sf/jasperreports/components/map/package-summary.html">net.sf.jasperreports.components.map</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../net/sf/jasperreports/components/map/package-summary.html">net.sf.jasperreports.components.map</a> that implement <a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">GenericElementOdtHandler</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../net/sf/jasperreports/components/map/MapElementOdtHandler.html" title="class in net.sf.jasperreports.components.map">MapElementOdtHandler</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= 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><a href="../../../../../../../net/sf/jasperreports/engine/export/oasis/GenericElementOdtHandler.html" title="interface in net.sf.jasperreports.engine.export.oasis">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?net/sf/jasperreports/engine/export/oasis/class-use/GenericElementOdtHandler.html" target="_top">Frames</a></li>
<li><a href="GenericElementOdtHandler.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| phurtado1112/cnaemvc | lib/JasperReport__5.6/docs/api/net/sf/jasperreports/engine/export/oasis/class-use/GenericElementOdtHandler.html | HTML | apache-2.0 | 8,874 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:18 EEST 2014 -->
<title>DeduplicableRegistry.DeduplicableWrapper (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<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="DeduplicableRegistry.DeduplicableWrapper (JasperReports 5.6.0 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="class-use/DeduplicableRegistry.DeduplicableWrapper.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableMap.html" title="class in net.sf.jasperreports.engine.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../net/sf/jasperreports/engine/util/DeepPrintElementCounter.html" title="class in net.sf.jasperreports.engine.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html" target="_top">Frames</a></li>
<li><a href="DeduplicableRegistry.DeduplicableWrapper.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>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">net.sf.jasperreports.engine.util</div>
<h2 title="Class DeduplicableRegistry.DeduplicableWrapper" class="title">Class DeduplicableRegistry.DeduplicableWrapper<T extends <a href="../../../../../net/sf/jasperreports/engine/Deduplicable.html" title="interface in net.sf.jasperreports.engine">Deduplicable</a>></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>net.sf.jasperreports.engine.util.DeduplicableRegistry.DeduplicableWrapper<T></li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.html" title="class in net.sf.jasperreports.engine.util">DeduplicableRegistry</a></dd>
</dl>
<hr>
<br>
<pre>protected static class <span class="strong">DeduplicableRegistry.DeduplicableWrapper<T extends <a href="../../../../../net/sf/jasperreports/engine/Deduplicable.html" title="interface in net.sf.jasperreports.engine">Deduplicable</a>></span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== 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="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html#DeduplicableRegistry.DeduplicableWrapper(T)">DeduplicableRegistry.DeduplicableWrapper</a></strong>(<a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html" title="type parameter in DeduplicableRegistry.DeduplicableWrapper">T</a> object)</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="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="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object other)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html#hashCode()">hashCode</a></strong>()</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, 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">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="DeduplicableRegistry.DeduplicableWrapper(net.sf.jasperreports.engine.Deduplicable)">
<!-- -->
</a><a name="DeduplicableRegistry.DeduplicableWrapper(T)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>DeduplicableRegistry.DeduplicableWrapper</h4>
<pre>public DeduplicableRegistry.DeduplicableWrapper(<a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html" title="type parameter in DeduplicableRegistry.DeduplicableWrapper">T</a> object)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<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>hashCode</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="equals(java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object other)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>equals</code> in class <code>java.lang.Object</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="class-use/DeduplicableRegistry.DeduplicableWrapper.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableMap.html" title="class in net.sf.jasperreports.engine.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../net/sf/jasperreports/engine/util/DeepPrintElementCounter.html" title="class in net.sf.jasperreports.engine.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html" target="_top">Frames</a></li>
<li><a href="DeduplicableRegistry.DeduplicableWrapper.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>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 ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| phurtado1112/cnaemvc | lib/JasperReport__5.6/docs/api/net/sf/jasperreports/engine/util/DeduplicableRegistry.DeduplicableWrapper.html | HTML | apache-2.0 | 11,093 |
<HTML>
<HEAD>
<TITLE>VectotToDoubleArray</TITLE>
</HEAD>
<BODY TEXT="#000000" LINK="#ff00ff" VLINK="#800080" BGCOLOR="#fdf5e6" alink="#FF0000">
<H1 ALIGN="CENTER">VectToDoubleArray</H1>
<P ALIGN="CENTER">
<LARGE><B>Author : Ian Wang</B>
</P>
<P ALIGN="CENTER">
<LARGE><B>Version : VERSION <BR>
<BR>
Input Types : <A HREF="C:\triana\help/JavaDoc/triana/types/VectorType.html">VectorType</A><BR>
Output Types : double[]<BR>
Date : 16 Jun 2003</LARGE>
</P>
</B><H2><A NAME="contents"></A>Contents</H2>
<UL>
<LI><A HREF="#description">Description of VectToDoubleArray</A></LI>
<LI><A HREF="#using">Using VectotToDoubleArray</A></LI>
</UL>
<P>
<HR WIDTH="15%" SIZE=4>
</P>
<H2><A NAME="description"></A>Description of VectToDoubleArray</H2>
<P>Converts a vector type into two double arrays</P>
<P>The unit called VectToDoubleArray ...... <BR>
</P>
<H2><A NAME="using"></A>Using VectToDoubleArray</H2>
<P>VectToDoubleArray's parameter window (double-click on the unit while holding down the Control key) is used to
.... </P>
<P>
<HR WIDTH="15%" SIZE=4>
</P></BODY>
</HTML>
| CSCSI/Triana | triana-toolboxes/signalproc/help/converters/VectToDoubleArray.html | HTML | apache-2.0 | 1,143 |
package nodeAST.relational;
import java.util.Map;
import nodeAST.BinaryExpr;
import nodeAST.Expression;
import nodeAST.Ident;
import nodeAST.literals.Literal;
import types.BoolType;
import types.Type;
import visitor.ASTVisitor;
import visitor.IdentifiersTypeMatcher;
public class NEq extends BinaryExpr {
public NEq(Expression leftHandOperand, Expression rightHandOperand) {
super(leftHandOperand,rightHandOperand);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this, this.leftHandOperand, this.rightHandOperand);
}
@Override
public String toString() {
return this.leftHandOperand.toString() + "!=" + this.rightHandOperand.toString();
}
@Override
public Type getType(IdentifiersTypeMatcher typeMatcher) {
return new BoolType();
}
@Override
public boolean areOperandsTypeValid(IdentifiersTypeMatcher typeMatcher) {
Type t1=this.leftHandOperand.getType(typeMatcher);
Type t2=this.rightHandOperand.getType(typeMatcher);
return t1.isCompatibleWith(t2) &&
(t1.isArithmetic() || t1.isBoolean() || t1.isRelational() || t1.isString() );
}
@Override
public Literal compute(Map<Ident, Expression> identifiers) {
return this.leftHandOperand.compute(identifiers).neq(
this.rightHandOperand.compute(identifiers)
);
}
}
| software-engineering-amsterdam/poly-ql | GeorgePachitariu/ANTLR-First/src/nodeAST/relational/NEq.java | Java | apache-2.0 | 1,336 |
package edu.ptu.javatest._60_dsa;
import org.junit.Test;
import java.util.TreeMap;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldBool;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldObj;
public class _35_TreeMapTest {
@Test
public void testPrintTreeMap() {
TreeMap hashMapTest = new TreeMap<>();
for (int i = 0; i < 6; i++) {
hashMapTest.put(new TMHashObj(1,i*2 ), i*2 );
}
Object table = getRefFieldObj(hashMapTest, hashMapTest.getClass(), "root");
printTreeMapNode(table);
hashMapTest.put(new TMHashObj(1,9), 9);
printTreeMapNode(table);
System.out.println();
}
public static int getTreeDepth(Object rootNode) {
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return 0;
return rootNode == null ? 0 : (1 + Math.max(getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "left")), getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "right"))));
}
public static void printTreeMapNode(Object rootNode) {//转化为堆
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return;
int treeDepth = getTreeDepth(rootNode);
Object[] objects = new Object[(int) (Math.pow(2, treeDepth) - 1)];
objects[0] = rootNode;
// objects[0]=rootNode;
// objects[1]=getRefFieldObj(objects,objects.getClass(),"left");
// objects[2]=getRefFieldObj(objects,objects.getClass(),"right");
//
// objects[3]=getRefFieldObj(objects[1],objects[1].getClass(),"left");
// objects[4]=getRefFieldObj(objects[1],objects[1].getClass(),"right");
// objects[5]=getRefFieldObj(objects[2],objects[3].getClass(),"left");
// objects[6]=getRefFieldObj(objects[2],objects[4].getClass(),"right");
for (int i = 1; i < objects.length; i++) {//数组打印
int index = (i - 1) / 2;//parent
if (objects[index] != null) {
if (i % 2 == 1)
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "left");
else
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "right");
}
}
StringBuilder sb = new StringBuilder();
StringBuilder outSb = new StringBuilder();
String space = " ";
for (int i = 0; i < treeDepth + 1; i++) {
sb.append(space);
}
int nextlineIndex = 0;
for (int i = 0; i < objects.length; i++) {//new line: 0,1 ,3,7
//print space
//print value
if (nextlineIndex == i) {
outSb.append("\n\n");
if (sb.length() >= space.length()) {
sb.delete(0, space.length());
}
nextlineIndex = i * 2 + 1;
}
outSb.append(sb.toString());
if (objects[i] != null) {
Object value = getRefFieldObj(objects[i], objects[i].getClass(), "value");
boolean red = !getRefFieldBool(objects[i], objects[i].getClass(), "color");// BLACK = true;
String result = "" + value + "(" + (red ? "r" : "b") + ")";
outSb.append(result);
} else {
outSb.append("nil");
}
}
System.out.println(outSb.toString());
}
public static class TMHashObj implements Comparable{
int hash;
int value;
TMHashObj(int hash, int value) {
this.hash = hash;
this.value = value;
}
@Override
public int hashCode() {
return hash;
}
@Override
public int compareTo(Object o) {
if (o instanceof TMHashObj){
return this.value-((TMHashObj) o).value;
}
return value-o.hashCode();
}
}
}
| rickgit/Test | JavaTest/src/main/java/edu/ptu/javatest/_60_dsa/_35_TreeMapTest.java | Java | apache-2.0 | 4,084 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_22) on Tue Nov 16 12:39:11 CET 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
GenericService (RESThub framework 1.0 API)
</TITLE>
<META NAME="date" CONTENT="2010-11-16">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="GenericService (RESThub framework 1.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/GenericService.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/resthub/core/service/GenericResourceServiceImpl.html" title="class in org.resthub.core.service"><B>PREV CLASS</B></A>
<A HREF="../../../../org/resthub/core/service/GenericServiceImpl.html" title="class in org.resthub.core.service"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/resthub/core/service/GenericService.html" target="_top"><B>FRAMES</B></A>
<A HREF="GenericService.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.resthub.core.service</FONT>
<BR>
Interface GenericService<T,ID extends java.io.Serializable></H2>
<DL>
<DT><DT><B>Type Parameters:</B><DD><CODE>T</CODE> - Domain model class managed, must be an Entity<DD><CODE>PK</CODE> - Primary key class of T</DL>
<DL>
<DT><B>All Known Subinterfaces:</B> <DD><A HREF="../../../../org/resthub/oauth2/provider/service/AuthorizationService.html" title="interface in org.resthub.oauth2.provider.service">AuthorizationService</A>, <A HREF="../../../../org/resthub/core/service/GenericResourceService.html" title="interface in org.resthub.core.service">GenericResourceService</A><T></DD>
</DL>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../org/resthub/oauth2/provider/service/AuthorizationServiceImpl.html" title="class in org.resthub.oauth2.provider.service">AuthorizationServiceImpl</A>, <A HREF="../../../../org/resthub/core/service/GenericResourceServiceImpl.html" title="class in org.resthub.core.service">GenericResourceServiceImpl</A>, <A HREF="../../../../org/resthub/core/service/GenericServiceImpl.html" title="class in org.resthub.core.service">GenericServiceImpl</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>GenericService<T,ID extends java.io.Serializable></B></DL>
</PRE>
<P>
Generic Service interface.
<P>
<P>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.Long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#count()">count</A></B>()</CODE>
<BR>
Count all resources.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#create(T)">create</A></B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</CODE>
<BR>
Create new resource.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#delete(ID)">delete</A></B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">ID</A> id)</CODE>
<BR>
Delete existing resource.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#delete(T)">delete</A></B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</CODE>
<BR>
Delete existing resource.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#findAll()">findAll</A></B>()</CODE>
<BR>
Find all resources.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#findAll(java.lang.Integer, java.lang.Integer)">findAll</A></B>(java.lang.Integer offset,
java.lang.Integer limit)</CODE>
<BR>
Find all resources.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> org.synyx.hades.domain.Page<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#findAll(org.synyx.hades.domain.Pageable)">findAll</A></B>(org.synyx.hades.domain.Pageable pageRequest)</CODE>
<BR>
Find all resources (pageable).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#findById(ID)">findById</A></B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">ID</A> id)</CODE>
<BR>
Find resource by id.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/resthub/core/service/GenericService.html#update(T)">update</A></B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</CODE>
<BR>
Update existing resource.</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="create(java.lang.Object)"><!-- --></A><A NAME="create(T)"><!-- --></A><H3>
create</H3>
<PRE>
<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> <B>create</B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</PRE>
<DL>
<DD>Create new resource.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>resource</CODE> - Resource to create
<DT><B>Returns:</B><DD>new resource</DL>
</DD>
</DL>
<HR>
<A NAME="update(java.lang.Object)"><!-- --></A><A NAME="update(T)"><!-- --></A><H3>
update</H3>
<PRE>
<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> <B>update</B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</PRE>
<DL>
<DD>Update existing resource.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>resource</CODE> - Resource to update
<DT><B>Returns:</B><DD>resource updated</DL>
</DD>
</DL>
<HR>
<A NAME="delete(java.lang.Object)"><!-- --></A><A NAME="delete(T)"><!-- --></A><H3>
delete</H3>
<PRE>
void <B>delete</B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> resource)</PRE>
<DL>
<DD>Delete existing resource.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>resource</CODE> - Resource to delete</DL>
</DD>
</DL>
<HR>
<A NAME="delete(java.io.Serializable)"><!-- --></A><A NAME="delete(ID)"><!-- --></A><H3>
delete</H3>
<PRE>
void <B>delete</B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">ID</A> id)</PRE>
<DL>
<DD>Delete existing resource.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>id</CODE> - Resource id</DL>
</DD>
</DL>
<HR>
<A NAME="findById(java.io.Serializable)"><!-- --></A><A NAME="findById(ID)"><!-- --></A><H3>
findById</H3>
<PRE>
<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A> <B>findById</B>(<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">ID</A> id)</PRE>
<DL>
<DD>Find resource by id.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>id</CODE> - Resource id
<DT><B>Returns:</B><DD>resource</DL>
</DD>
</DL>
<HR>
<A NAME="findAll(java.lang.Integer, java.lang.Integer)"><!-- --></A><H3>
findAll</H3>
<PRE>
java.util.List<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>> <B>findAll</B>(java.lang.Integer offset,
java.lang.Integer limit)</PRE>
<DL>
<DD>Find all resources.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>offset</CODE> - offset (default 0)<DD><CODE>limit</CODE> - limit (default 100)
<DT><B>Returns:</B><DD>resources.</DL>
</DD>
</DL>
<HR>
<A NAME="findAll()"><!-- --></A><H3>
findAll</H3>
<PRE>
java.util.List<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>> <B>findAll</B>()</PRE>
<DL>
<DD>Find all resources.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>a list of all resources.</DL>
</DD>
</DL>
<HR>
<A NAME="findAll(org.synyx.hades.domain.Pageable)"><!-- --></A><H3>
findAll</H3>
<PRE>
org.synyx.hades.domain.Page<<A HREF="../../../../org/resthub/core/service/GenericService.html" title="type parameter in GenericService">T</A>> <B>findAll</B>(org.synyx.hades.domain.Pageable pageRequest)</PRE>
<DL>
<DD>Find all resources (pageable).
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>pageRequest</CODE> - page request
<DT><B>Returns:</B><DD>resources</DL>
</DD>
</DL>
<HR>
<A NAME="count()"><!-- --></A><H3>
count</H3>
<PRE>
java.lang.Long <B>count</B>()</PRE>
<DL>
<DD>Count all resources.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>number of resources</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/GenericService.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/resthub/core/service/GenericResourceServiceImpl.html" title="class in org.resthub.core.service"><B>PREV CLASS</B></A>
<A HREF="../../../../org/resthub/core/service/GenericServiceImpl.html" title="class in org.resthub.core.service"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/resthub/core/service/GenericService.html" target="_top"><B>FRAMES</B></A>
<A HREF="GenericService.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009-2010. All Rights Reserved.
</BODY>
</HTML>
| resthub/resthub.github.io | apidocs/spring/1.0/org/resthub/core/service/GenericService.html | HTML | apache-2.0 | 17,578 |
using System;
using System.Html;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Widgets {
[Imported]
[IgnoreNamespace]
[Serializable]
public sealed class DialogResizeStartEvent {
public object OriginalPosition {
get; set;
}
public object OriginalSize {
get; set;
}
public object Position {
get; set;
}
public object Size {
get; set;
}
}
}
| Saltarelle/SaltarelleJQueryUI | jQuery.UI/Generated/Widgets/Dialog/DialogResizeStartEvent.cs | C# | apache-2.0 | 492 |
---
layout: default
modal-id: 7
date: 2013-01-31
img: themis.png
alt: UOCD
project-date: Spring 2013
client: Olin
title: User-Oriented Collaborative Design
size: 5
tags: [Design, Project]
description: "As part of Olin’s User-Oriented Collaborative Design course, I worked for a semester with parents of visually impaired children to understand their experiences and design a product based on their challenges and values.
<br/>
<br/> After interviews with dozens of parents, children, educators and community advocates, my team realized that getting people to challenge visually impaired children is a difficulty for many parents. They’re trying to raise their children, while teachers, family members and even other children often go out of their way to make sure visually impaired children aren’t challenged or disadvantaged. These people, while meaning well, are making it so visually impaired children are not prepared to handle the real world. Many parents spoke about being exhausted from simply trying to get teacher to challenge their students.
<br/>
<br/> Our solution: Themis, a VR headset giving anyone the experience of being a visually impaired person with the tools and experience necessary to thrive. Themis totally simulates the sight, hearing, and some of the tactile sensations experienced by a visually impaired person completing a variety of tasks. It allows users to walk through these experiences first on their own, with the sense of a visually impaired person, and then with expert guidance to help them understand the actual experience of a visually impaired person, who has tools to navigate the world.
<br/>
<br/>
During this project, we encountered a variety of design challenges, but the most prominent was the fact that parents wanted us to design for their children, not them. In interviews, every idea we co-designed with was changed into a product for the children. Essentially, in their eyes, we should focus on designing for their children, not them. The course guideline was quite clear; we were designing for the parents. To help overcome this challenge we changed our co-design approach and introduced our ideas as tools focused on the child that the parent could use. With this approach, we narrowed in on Themis as the idea that parents found the most valuable.
"
---
| Skinc/skinc.github.io | _posts/2013-01-31-User-Oriented-Collaborative-Design.markdown | Markdown | apache-2.0 | 2,329 |
package com.cisco.axl.api._8;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LPhoneSecurityProfile complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LPhoneSecurityProfile">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="phoneType" type="{http://www.cisco.com/AXL/API/8.0}XModel" minOccurs="0"/>
* <element name="protocol" type="{http://www.cisco.com/AXL/API/8.0}XDeviceProtocol" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="deviceSecurityMode" type="{http://www.cisco.com/AXL/API/8.0}XDeviceSecurityMode" minOccurs="0"/>
* <element name="authenticationMode" type="{http://www.cisco.com/AXL/API/8.0}XAuthenticationMode" minOccurs="0"/>
* <element name="keySize" type="{http://www.cisco.com/AXL/API/8.0}XKeySize" minOccurs="0"/>
* <element name="tftpEncryptedConfig" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="nonceValidityTime" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="transportType" type="{http://www.cisco.com/AXL/API/8.0}XTransport" minOccurs="0"/>
* <element name="sipPhonePort" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="enableDigestAuthentication" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="excludeDigestCredentials" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* </sequence>
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LPhoneSecurityProfile", propOrder = {
"phoneType",
"protocol",
"name",
"description",
"deviceSecurityMode",
"authenticationMode",
"keySize",
"tftpEncryptedConfig",
"nonceValidityTime",
"transportType",
"sipPhonePort",
"enableDigestAuthentication",
"excludeDigestCredentials"
})
public class LPhoneSecurityProfile {
protected String phoneType;
protected String protocol;
protected String name;
protected String description;
protected String deviceSecurityMode;
protected String authenticationMode;
protected String keySize;
protected String tftpEncryptedConfig;
protected String nonceValidityTime;
protected String transportType;
protected String sipPhonePort;
protected String enableDigestAuthentication;
protected String excludeDigestCredentials;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the phoneType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhoneType() {
return phoneType;
}
/**
* Sets the value of the phoneType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhoneType(String value) {
this.phoneType = value;
}
/**
* Gets the value of the protocol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocol() {
return protocol;
}
/**
* Sets the value of the protocol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocol(String value) {
this.protocol = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the deviceSecurityMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDeviceSecurityMode() {
return deviceSecurityMode;
}
/**
* Sets the value of the deviceSecurityMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeviceSecurityMode(String value) {
this.deviceSecurityMode = value;
}
/**
* Gets the value of the authenticationMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationMode() {
return authenticationMode;
}
/**
* Sets the value of the authenticationMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationMode(String value) {
this.authenticationMode = value;
}
/**
* Gets the value of the keySize property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeySize() {
return keySize;
}
/**
* Sets the value of the keySize property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeySize(String value) {
this.keySize = value;
}
/**
* Gets the value of the tftpEncryptedConfig property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTftpEncryptedConfig() {
return tftpEncryptedConfig;
}
/**
* Sets the value of the tftpEncryptedConfig property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTftpEncryptedConfig(String value) {
this.tftpEncryptedConfig = value;
}
/**
* Gets the value of the nonceValidityTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNonceValidityTime() {
return nonceValidityTime;
}
/**
* Sets the value of the nonceValidityTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNonceValidityTime(String value) {
this.nonceValidityTime = value;
}
/**
* Gets the value of the transportType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportType() {
return transportType;
}
/**
* Sets the value of the transportType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportType(String value) {
this.transportType = value;
}
/**
* Gets the value of the sipPhonePort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSipPhonePort() {
return sipPhonePort;
}
/**
* Sets the value of the sipPhonePort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSipPhonePort(String value) {
this.sipPhonePort = value;
}
/**
* Gets the value of the enableDigestAuthentication property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEnableDigestAuthentication() {
return enableDigestAuthentication;
}
/**
* Sets the value of the enableDigestAuthentication property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEnableDigestAuthentication(String value) {
this.enableDigestAuthentication = value;
}
/**
* Gets the value of the excludeDigestCredentials property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExcludeDigestCredentials() {
return excludeDigestCredentials;
}
/**
* Sets the value of the excludeDigestCredentials property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExcludeDigestCredentials(String value) {
this.excludeDigestCredentials = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/LPhoneSecurityProfile.java | Java | apache-2.0 | 10,171 |
package pokemon.vue;
import pokemon.launcher.PokemonCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.*;
public class MyActor extends Actor {
public Texture s=new Texture(Gdx.files.internal("crosshair.png"));
SpriteBatch b=new SpriteBatch();
float x,y;
public MyActor (float x, float y) {
this.x=x;
this.y=y;
System.out.print(PokemonCore.m.getCities().get(0).getX());
this.setBounds(x+PokemonCore.m.getCities().get(0).getX(),y+PokemonCore.m.getCities().get(0).getY(),s.getWidth(),s.getHeight());
/* RepeatAction action = new RepeatAction();
action.setCount(RepeatAction.FOREVER);
action.setAction(Actions.fadeOut(2f));*/
this.addAction(Actions.repeat(RepeatAction.FOREVER,Actions.sequence(Actions.fadeOut(1f),Actions.fadeIn(1f))));
//posx=this.getX();
//posy=this.getY();
//this.addAction(action);
//this.addAction(Actions.sequence(Actions.alpha(0),Actions.fadeIn(2f)));
System.out.println("Actor constructed");
b.getProjectionMatrix().setToOrtho2D(0, 0,640,360);
}
@Override
public void draw (Batch batch, float parentAlpha) {
b.begin();
Color color = getColor();
b.setColor(color.r, color.g, color.b, color.a * parentAlpha);
b.draw(s,this.getX()-15,this.getY()-15,30,30);
b.setColor(color);
b.end();
//System.out.println("Called");
//batch.draw(t,this.getX(),this.getY(),t.getWidth(),t.getHeight());
//batch.draw(s,this.getX()+Minimap.BourgPalette.getX(),this.getY()+Minimap.BourgPalette.getY(),30,30);
}
public void setPosition(float x, float y){
this.setX(x+this.x);
this.setY(y+this.y);
}
}
| yongaro/Pokemon | Pokemon-core/src/main/java/pokemon/vue/MyActor.java | Java | apache-2.0 | 2,197 |
# Cookbook Name:: postgresql
# Attributes:: postgresql
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default['postgresql']['enable_pgdg_apt'] = false
default['postgresql']['server']['config_change_notify'] = :restart
default['postgresql']['assign_postgres_password'] = true
# Establish default database name
default['postgresql']['database_name'] = 'template1'
case node['platform']
when "debian"
case
when node['platform_version'].to_f < 6.0 # All 5.X
default['postgresql']['version'] = "8.3"
when node['platform_version'].to_f < 7.0 # All 6.X
default['postgresql']['version'] = "8.4"
when node['platform_version'].to_f < 8.0 # All 7.X
default['postgresql']['version'] = "9.1"
else
default['postgresql']['version'] = "9.4"
end
default['postgresql']['dir'] = "/etc/postgresql/#{node['postgresql']['version']}/main"
case
when node['platform_version'].to_f < 6.0 # All 5.X
default['postgresql']['server']['service_name'] = "postgresql-#{node['postgresql']['version']}"
else
default['postgresql']['server']['service_name'] = "postgresql"
end
default['postgresql']['client']['packages'] = ["postgresql-client-#{node['postgresql']['version']}","libpq-dev"]
default['postgresql']['server']['packages'] = ["postgresql-#{node['postgresql']['version']}"]
default['postgresql']['contrib']['packages'] = ["postgresql-contrib-#{node['postgresql']['version']}"]
when "ubuntu"
case
when node['platform_version'].to_f <= 9.04
default['postgresql']['version'] = "8.3"
when node['platform_version'].to_f <= 11.04
default['postgresql']['version'] = "8.4"
when node['platform_version'].to_f <= 13.10
default['postgresql']['version'] = "9.1"
else
default['postgresql']['version'] = "9.3"
end
default['postgresql']['dir'] = "/etc/postgresql/#{node['postgresql']['version']}/main"
case
when (node['platform_version'].to_f <= 10.04) && (! node['postgresql']['enable_pgdg_apt'])
default['postgresql']['server']['service_name'] = "postgresql-#{node['postgresql']['version']}"
else
default['postgresql']['server']['service_name'] = "postgresql"
end
default['postgresql']['client']['packages'] = ["postgresql-client-#{node['postgresql']['version']}","libpq-dev"]
default['postgresql']['server']['packages'] = ["postgresql-#{node['postgresql']['version']}"]
default['postgresql']['contrib']['packages'] = ["postgresql-contrib-#{node['postgresql']['version']}"]
when "fedora"
if node['platform_version'].to_f <= 12
default['postgresql']['version'] = "8.3"
else
default['postgresql']['version'] = "8.4"
end
default['postgresql']['dir'] = "/var/lib/pgsql/data"
default['postgresql']['client']['packages'] = %w{postgresql93-devel postgresql93}
default['postgresql']['server']['packages'] = %w{postgresql93-server}
default['postgresql']['contrib']['packages'] = %w{postgresql93-contrib}
default['postgresql']['server']['service_name'] = 'postgresql'
when "amazon"
if node['platform_version'].to_f >= 2012.03
default['postgresql']['version'] = "9.0"
default['postgresql']['dir'] = "/var/lib/pgsql9/data"
else
default['postgresql']['version'] = "8.4"
default['postgresql']['dir'] = "/var/lib/pgsql/data"
end
default['postgresql']['client']['packages'] = %w{postgresql-devel}
default['postgresql']['server']['packages'] = %w{postgresql-server}
default['postgresql']['contrib']['packages'] = %w{postgresql-contrib}
default['postgresql']['server']['service_name'] = "postgresql"
when "redhat", "centos", "scientific", "oracle"
default['postgresql']['version'] = "8.4"
default['postgresql']['dir'] = "/var/lib/pgsql/data"
if node['platform_version'].to_f >= 6.0 && node['postgresql']['version'] == '8.4'
default['postgresql']['client']['packages'] = %w{postgresql-devel}
default['postgresql']['server']['packages'] = %w{postgresql-server}
default['postgresql']['contrib']['packages'] = %w{postgresql-contrib}
else
default['postgresql']['client']['packages'] = ["postgresql#{node['postgresql']['version'].split('.').join}-devel"]
default['postgresql']['server']['packages'] = ["postgresql#{node['postgresql']['version'].split('.').join}-server"]
default['postgresql']['contrib']['packages'] = ["postgresql#{node['postgresql']['version'].split('.').join}-contrib"]
end
if node['platform_version'].to_f >= 6.0 && node['postgresql']['version'] != '8.4'
default['postgresql']['dir'] = "/var/lib/pgsql/#{node['postgresql']['version']}/data"
default['postgresql']['server']['service_name'] = "postgresql-#{node['postgresql']['version']}"
else
default['postgresql']['dir'] = "/var/lib/pgsql/data"
default['postgresql']['server']['service_name'] = "postgresql"
end
when "suse"
if node['platform_version'].to_f <= 11.1
default['postgresql']['version'] = "8.3"
default['postgresql']['client']['packages'] = ['postgresql', 'rubygem-pg']
default['postgresql']['server']['packages'] = ['postgresql-server']
default['postgresql']['contrib']['packages'] = ['postgresql-contrib']
else
default['postgresql']['version'] = "9.1"
default['postgresql']['client']['packages'] = ['postgresql91', 'rubygem-pg']
default['postgresql']['server']['packages'] = ['postgresql91-server']
default['postgresql']['contrib']['packages'] = ['postgresql91-contrib']
end
default['postgresql']['dir'] = "/var/lib/pgsql/data"
default['postgresql']['server']['service_name'] = "postgresql"
else
default['postgresql']['version'] = "8.4"
default['postgresql']['dir'] = "/etc/postgresql/#{node['postgresql']['version']}/main"
default['postgresql']['client']['packages'] = ["postgresql"]
default['postgresql']['server']['packages'] = ["postgresql"]
default['postgresql']['contrib']['packages'] = ["postgresql"]
default['postgresql']['server']['service_name'] = "postgresql"
end
# These defaults have disparity between which postgresql configuration
# settings are used because they were extracted from the original
# configuration files that are now removed in favor of dynamic
# generation.
#
# While the configuration ends up being the same as the default
# in previous versions of the cookbook, the content of the rendered
# template will change, and this will result in service notification
# if you upgrade the cookbook on existing systems.
#
# The ssl config attribute is generated in the recipe to avoid awkward
# merge/precedence order during the Chef run.
case node['platform_family']
when 'debian'
default['postgresql']['config']['data_directory'] = "/var/lib/postgresql/#{node['postgresql']['version']}/main"
default['postgresql']['config']['hba_file'] = "/etc/postgresql/#{node['postgresql']['version']}/main/pg_hba.conf"
default['postgresql']['config']['ident_file'] = "/etc/postgresql/#{node['postgresql']['version']}/main/pg_ident.conf"
default['postgresql']['config']['external_pid_file'] = "/var/run/postgresql/#{node['postgresql']['version']}-main.pid"
default['postgresql']['config']['listen_addresses'] = 'localhost'
default['postgresql']['config']['port'] = 5432
default['postgresql']['config']['max_connections'] = 100
default['postgresql']['config']['unix_socket_directory'] = '/var/run/postgresql' if node['postgresql']['version'].to_f < 9.3
default['postgresql']['config']['unix_socket_directories'] = '/var/run/postgresql' if node['postgresql']['version'].to_f >= 9.3
default['postgresql']['config']['shared_buffers'] = '24MB'
default['postgresql']['config']['max_fsm_pages'] = 153600 if node['postgresql']['version'].to_f < 8.4
default['postgresql']['config']['log_line_prefix'] = '%t '
default['postgresql']['config']['datestyle'] = 'iso, mdy'
default['postgresql']['config']['default_text_search_config'] = 'pg_catalog.english'
default['postgresql']['config']['ssl'] = true
default['postgresql']['config']['ssl_cert_file'] = '/etc/ssl/certs/ssl-cert-snakeoil.pem' if node['postgresql']['version'].to_f >= 9.2
default['postgresql']['config']['ssl_key_file'] = '/etc/ssl/private/ssl-cert-snakeoil.key'if node['postgresql']['version'].to_f >= 9.2
when 'rhel', 'fedora', 'suse'
default['postgresql']['config']['data_directory'] = node['postgresql']['dir']
default['postgresql']['config']['listen_addresses'] = 'localhost'
default['postgresql']['config']['port'] = 5432
default['postgresql']['config']['max_connections'] = 100
default['postgresql']['config']['shared_buffers'] = '32MB'
default['postgresql']['config']['logging_collector'] = true
default['postgresql']['config']['log_directory'] = 'pg_log'
default['postgresql']['config']['log_filename'] = 'postgresql-%a.log'
default['postgresql']['config']['log_truncate_on_rotation'] = true
default['postgresql']['config']['log_rotation_age'] = '1d'
default['postgresql']['config']['log_rotation_size'] = 0
default['postgresql']['config']['datestyle'] = 'iso, mdy'
default['postgresql']['config']['lc_messages'] = 'en_US.UTF-8'
default['postgresql']['config']['lc_monetary'] = 'en_US.UTF-8'
default['postgresql']['config']['lc_numeric'] = 'en_US.UTF-8'
default['postgresql']['config']['lc_time'] = 'en_US.UTF-8'
default['postgresql']['config']['default_text_search_config'] = 'pg_catalog.english'
end
default['postgresql']['config']['hot_standby'] = 'off'
default['postgresql']['config']['max_standby_archive_delay'] = '30s'
default['postgresql']['config']['max_standby_streaming_delay'] = '30s'
default['postgresql']['config']['wal_receiver_status_interval'] = '10s'
default['postgresql']['config']['hot_standby_feedback'] = 'off'
default['postgresql']['config']['wal_level'] = 'archive'
default['postgresql']['config']['archive_mode'] = 'off'
default['postgresql']['config']['archive_command'] = ''
default['postgresql']['config']['max_wal_senders'] = '2'
default['postgresql']['config']['wal_keep_segments'] = '4'
# attributes for recovery.conf
default['postgresql']['recovery']['standby_mode'] = 'off'
default['postgresql']['recovery']['restore_command'] = ''
default['postgresql']['recovery']['archive_cleanup_command'] = ''
default['postgresql']['recovery']['recovery_end_command'] = ''
default['postgresql']['recovery']['primary_conninfo'] = ''
default['postgresql']['recovery']['trigger_file'] = ''
# replica user creation
default['postgresql']['recovery_user'] = ''
default['postgresql']['recovery_user_pass'] = ''
default['postgresql']['master_ip'] = ''
default['postgresql']['pg_hba'] = [
{:type => 'local', :db => 'all', :user => 'postgres', :addr => nil, :method => 'ident'},
{:type => 'local', :db => 'all', :user => 'all', :addr => nil, :method => 'ident'},
{:type => 'host', :db => 'all', :user => 'all', :addr => '127.0.0.1/32', :method => 'md5'},
{:type => 'host', :db => 'all', :user => 'all', :addr => '::1/128', :method => 'md5'}
]
default['postgresql']['password'] = Hash.new
case node['platform_family']
when 'debian'
default['postgresql']['pgdg']['release_apt_codename'] = node['lsb']['codename']
end
default['postgresql']['enable_pgdg_yum'] = false
default['postgresql']['initdb_locale'] = nil
# The PostgreSQL RPM Building Project built repository RPMs for easy
# access to the PGDG yum repositories. Links to RPMs for installation
# on the supported version/platform combinations are listed at
# http://yum.postgresql.org/repopackages.php, and the links for
# PostgreSQL 8.4, 9.0, 9.1, 9.2 and 9.3 are captured below.
#
# The correct RPM for installing /etc/yum.repos.d is based on:
# * the attribute configuring the desired Postgres Software:
# node['postgresql']['version'] e.g., "9.1"
# * the chef ohai description of the target Operating System:
# node['platform'] e.g., "centos"
# node['platform_version'] e.g., "5.7", truncated as "5"
# node['kernel']['machine'] e.g., "i386" or "x86_64"
default['postgresql']['pgdg']['repo_rpm_url'] = {
"9.4" => {
"amazon" => {
"2014" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
},
"2013" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
}
},
"centos" => {
"7" => {
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-centos94-9.4-1.noarch.rpm"
},
"6" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-centos94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-5-i386/pgdg-centos94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/pgdg-centos94-9.4-1.noarch.rpm"
}
},
"redhat" => {
"7" => {
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
},
"6" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-5-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
}
},
"oracle" => {
"7" => {
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-7-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
},
"6" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-5-i386/pgdg-redhat94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/pgdg-redhat94-9.4-1.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-6-i386/pgdg-sl94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-sl94-9.4-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.4/redhat/rhel-5-i386/pgdg-sl94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/redhat/rhel-5-x86_64/pgdg-sl94-9.4-1.noarch.rpm"
}
},
"fedora" => {
"21" => {
"i386" => "http://yum.postgresql.org/9.4/fedora/fedora-21-i686/pgdg-fedora94-9.4-2.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/fedora/fedora-21-x86_64/pgdg-fedora94-9.4-2.noarch.rpm"
},
"20" => {
"i386" => "http://yum.postgresql.org/9.4/fedora/fedora-20-i686/pgdg-fedora94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/fedora/fedora-20-x86_64/pgdg-fedora94-9.4-1.noarch.rpm"
},
"19" => {
"i386" => "http://yum.postgresql.org/9.4/fedora/fedora-19-i686/pgdg-fedora94-9.4-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.4/fedora/fedora-19-x86_64/pgdg-fedora94-9.4-1.noarch.rpm"
},
}
},
"9.3" => {
"amazon" => {
"2015" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
},
"2014" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
},
"2013" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
}
},
"centos" => {
"7" => {
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-7-x86_64/pgdg-centos93-9.3-1.noarch.rpm"
},
"6" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-centos93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-centos93-9.3-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-5-i386/pgdg-centos93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-5-x86_64/pgdg-centos93-9.3-1.noarch.rpm"
}
},
"redhat" => {
"7" => {
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-7-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
},
"6" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-5-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-5-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
}
},
"oracle" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-5-i386/pgdg-redhat93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-5-x86_64/pgdg-redhat93-9.3-1.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-6-i386/pgdg-sl93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-sl93-9.3-1.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.3/redhat/rhel-5-i386/pgdg-sl93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/redhat/rhel-5-x86_64/pgdg-sl93-9.3-1.noarch.rpm"
}
},
"fedora" => {
"20" => {
"x86_64" => "http://yum.postgresql.org/9.3/fedora/fedora-20-x86_64/pgdg-fedora93-9.3-1.noarch.rpm"
},
"19" => {
"x86_64" => "http://yum.postgresql.org/9.3/fedora/fedora-19-x86_64/pgdg-fedora93-9.3-1.noarch.rpm"
},
"18" => {
"i386" => "http://yum.postgresql.org/9.3/fedora/fedora-18-i386/pgdg-fedora93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/fedora/fedora-18-x86_64/pgdg-fedora93-9.3-1.noarch.rpm"
},
"17" => {
"i386" => "http://yum.postgresql.org/9.3/fedora/fedora-17-i386/pgdg-fedora93-9.3-1.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.3/fedora/fedora-17-x86_64/pgdg-fedora93-9.3-1.noarch.rpm"
}
}
},
"9.2" => {
"centos" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-6-i386/pgdg-centos92-9.2-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-6-x86_64/pgdg-centos92-9.2-6.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-5-i386/pgdg-centos92-9.2-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-5-x86_64/pgdg-centos92-9.2-6.noarch.rpm"
}
},
"redhat" => {
"6" => {
# # encoding: utf-8
# encoding: utf-8
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-6-i386/pgdg-redhat92-9.2-7.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-6-x86_64/pgdg-redhat92-9.2-7.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-5-i386/pgdg-redhat92-9.2-7.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-5-x86_64/pgdg-redhat92-9.2-7.noarch.rpm"
}
},
"oracle" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-6-i386/pgdg-redhat92-9.2-7.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-6-x86_64/pgdg-redhat92-9.2-7.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-5-i386/pgdg-redhat92-9.2-7.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-5-x86_64/pgdg-redhat92-9.2-7.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-6-i386/pgdg-sl92-9.2-8.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-6-x86_64/pgdg-sl92-9.2-8.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.2/redhat/rhel-5-i386/pgdg-sl92-9.2-8.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/redhat/rhel-5-x86_64/pgdg-sl92-9.2-8.noarch.rpm"
}
},
"fedora" => {
"19" => {
"i386" => "http://yum.postgresql.org/9.2/fedora/fedora-19-i386/pgdg-fedora92-9.2-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/fedora/fedora-19-x86_64/pgdg-fedora92-9.2-6.noarch.rpm"
},
"18" => {
"i386" => "http://yum.postgresql.org/9.2/fedora/fedora-18-i386/pgdg-fedora92-9.2-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/fedora/fedora-18-x86_64/pgdg-fedora92-9.2-6.noarch.rpm"
},
"17" => {
"i386" => "http://yum.postgresql.org/9.2/fedora/fedora-17-i386/pgdg-fedora92-9.2-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/fedora/fedora-17-x86_64/pgdg-fedora92-9.2-5.noarch.rpm"
},
"16" => {
"i386" => "http://yum.postgresql.org/9.2/fedora/fedora-16-i386/pgdg-fedora92-9.2-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.2/fedora/fedora-16-x86_64/pgdg-fedora92-9.2-5.noarch.rpm"
}
}
},
"9.1" => {
"centos" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-6-i386/pgdg-centos91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-5-x86_64/pgdg-centos91-9.1-4.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-5-i386/pgdg-centos91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-5-x86_64/pgdg-centos91-9.1-4.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-4-i386/pgdg-centos91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-4-x86_64/pgdg-centos91-9.1-4.noarch.rpm"
}
},
"redhat" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-6-i386/pgdg-redhat91-9.1-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-6-x86_64/pgdg-redhat91-9.1-5.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-5-i386/pgdg-redhat91-9.1-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-5-x86_64/pgdg-redhat91-9.1-5.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-4-i386/pgdg-redhat-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-4-x86_64/pgdg-redhat-9.1-4.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-6-i386/pgdg-sl91-9.1-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-6-x86_64/pgdg-sl91-9.1-6.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.1/redhat/rhel-5-i386/pgdg-sl91-9.1-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/redhat/rhel-5-x86_64/pgdg-sl91-9.1-6.noarch.rpm"
}
},
"fedora" => {
"16" => {
"i386" => "http://yum.postgresql.org/9.1/fedora/fedora-16-i386/pgdg-fedora91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/fedora/fedora-16-x86_64/pgdg-fedora91-9.1-4.noarch.rpm"
},
"15" => {
"i386" => "http://yum.postgresql.org/9.1/fedora/fedora-15-i386/pgdg-fedora91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/fedora/fedora-15-x86_64/pgdg-fedora91-9.1-4.noarch.rpm"
},
"14" => {
"i386" => "http://yum.postgresql.org/9.1/fedora/fedora-14-i386/pgdg-fedora91-9.1-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.1/fedora/fedora-14-x86_64/pgdg-fedora-9.1-2.noarch.rpm"
}
}
},
"9.0" => {
"centos" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-6-i386/pgdg-centos90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-6-x86_64/pgdg-centos90-9.0-5.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-5-i386/pgdg-centos90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-5-x86_64/pgdg-centos90-9.0-5.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-4-i386/pgdg-centos90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-4-x86_64/pgdg-centos90-9.0-5.noarch.rpm"
}
},
"redhat" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-6-i386/pgdg-redhat90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-6-x86_64/pgdg-redhat90-9.0-5.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-5-i386/pgdg-redhat90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-5-x86_64/pgdg-redhat90-9.0-5.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-4-i386/pgdg-redhat90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-4-x86_64/pgdg-redhat90-9.0-5.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-6-i386/pgdg-sl90-9.0-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-6-x86_64/pgdg-sl90-9.0-6.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/9.0/redhat/rhel-5-i386/pgdg-sl90-9.0-6.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/redhat/rhel-5-x86_64/pgdg-sl90-9.0-6.noarch.rpm"
}
},
"fedora" => {
"15" => {
"i386" => "http://yum.postgresql.org/9.0/fedora/fedora-15-i386/pgdg-fedora90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/fedora/fedora-15-x86_64/pgdg-fedora90-9.0-5.noarch.rpm"
},
"14" => {
"i386" => "http://yum.postgresql.org/9.0/fedora/fedora-14-i386/pgdg-fedora90-9.0-5.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/9.0/fedora/fedora-14-x86_64/pgdg-fedora90-9.0-5.noarch.rpm"
}
}
},
"8.4" => {
"centos" => {
"6" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-6-i386/pgdg-centos-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-6-x86_64/pgdg-centos-8.4-3.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-5-i386/pgdg-centos-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-5-x86_64/pgdg-centos-8.4-3.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-4-i386/pgdg-centos-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-4-x86_64/pgdg-centos-8.4-3.noarch.rpm"
}
},
"redhat" => {
"6" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-6-i386/pgdg-redhat-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-6-x86_64/pgdg-redhat-8.4-3.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-5-i386/pgdg-redhat-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-5-x86_64/pgdg-redhat-8.4-3.noarch.rpm"
},
"4" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-4-i386/pgdg-redhat-8.4-3.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-4-x86_64/pgdg-redhat-8.4-3.noarch.rpm"
}
},
"scientific" => {
"6" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-6-i386/pgdg-sl84-8.4-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-6-x86_64/pgdg-sl84-8.4-4.noarch.rpm"
},
"5" => {
"i386" => "http://yum.postgresql.org/8.4/redhat/rhel-5-i386/pgdg-sl-8.4-4.noarch.rpm",
"x86_64" => "http://yum.postgresql.org/8.4/redhat/rhel-5-x86_64/pgdg-sl-8.4-4.noarch.rpm"
}
},
"fedora" => {
"14" => {
"i386" => "http://yum.postgresql.org/8.4/fedora/fedora-14-i386/",
"x86_64" => "http://yum.postgresql.org/8.4/fedora/fedora-14-x86_64/"
},
"13" => {
"i386" => "http://yum.postgresql.org/8.4/fedora/fedora-13-i386/",
"x86_64" => "http://yum.postgresql.org/8.4/fedora/fedora-13-x86_64/"
},
"12" => {
"i386" => "http://yum.postgresql.org/8.4/fedora/fedora-12-i386/",
"x86_64" => "http://yum.postgresql.org/8.4/fedora/fedora-12-x86_64/"
},
"8" => {
"i386" => "http://yum.postgresql.org/8.4/fedora/fedora-8-i386/",
"x86_64" => "http://yum.postgresql.org/8.4/fedora/fedora-8-x86_64/"
},
"7" => {
"i386" => "http://yum.postgresql.org/8.4/fedora/fedora-7-i386/",
"x86_64" => "http://yum.postgresql.org/8.4/fedora/fedora-7-x86_64/"
}
}
},
};
| pronix/postgresql | attributes/default.rb | Ruby | apache-2.0 | 30,398 |
package org.tiltedwindmills.fantasy.mfl.services;
import org.tiltedwindmills.fantasy.mfl.model.LoginResponse;
/**
* Interface defining operations required for logging into an MFL league.
*/
public interface LoginService {
/**
* Login.
*
* @param leagueId the league id
* @param serverId the server id
* @param year the year
* @param franchiseId the franchise id
* @param password the password
* @return the login response
*/
LoginResponse login(int leagueId, int serverId, int year, String franchiseId, String password);
}
| tiltedwindmills/mfl-api | src/main/java/org/tiltedwindmills/fantasy/mfl/services/LoginService.java | Java | apache-2.0 | 571 |
# wc [option] command
# -l, --lines : 打印行数
# -L, --max-line-length : 打印最长行的长度
# -w, --words : 打印单词数
# -m, --chars : 打印字符数
# -c, --bytes : 打印字节数
# 文件信息,包括行数,单词数,字节数
wc dstFile
cat dstFile | wc
# 文件行数与文件名
wc -l dstFile
# 文件行数
cat dstFile | wc -l
# 单词数与文件名
wc -w dstFile
# 单词数
cat dstFile | wc -w
# 字节数及文件名
wc -c dstFile
# 字节数
cat dstFile | wc -c
# 打印字符数与文件名
wc -m dstFile
# 字符数
cat dstFile | wc -m
# 用来统计当前目录下的文件数
# 数量中包含当前目录
ls -l | wc -l
# line counts
wc -l
# word counts
wc -w
# char counts
wc -m
# bytes
wc -c
# 打印最长行的长度
wc -L
# 计某文件夹下文件的个数
ls -l |grep "^-"| wc -l
# 统计某文件夹下目录的个数
ls -l |grep "^d"| wc -l
# 统计文件夹下文件的个数,包括子文件夹里的
ls -lR|grep "^-"| wc -l
# 如统计目录(包含子目录)下的所有js文件
ls -lR dir | grep .js | wc -l
ls -l "dir" | grep ".js" | wc -l
# 统计文件夹下目录的个数,包括子文件夹里的
ls -lR|grep "^d"|wc -l
# 长列表输出该目录下文件信息(R代表子目录注意这里的文件,不同于一般的文件,可能是目录、链接、设备文件等)
ls -lR
# 这里将长列表输出信息过滤一部分,只保留一般文件,如果只保留目录就是 ^d
grep "^-"
# 统计输出信息的行数
wc -l
# 如果只查看文件夹, 只能显示一个
ls -d
# 可以看到子文件夹
find -type d
# 只看当前目录下的文件夹,不包括往下的文件夹
ls -lF |grep /
ls -l |grep '^d' | WeAreChampion/notes | shell/common/wc.sh | Shell | apache-2.0 | 1,709 |
<?php
/* TwigBundle:Exception:exception.rdf.twig */
class __TwigTemplate_70e8b249c1428c255435d8a44ef7c09891fdf8c23551b886c441d0a716433b6a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a->enter($__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:exception.rdf.twig"));
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7->enter($__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "TwigBundle:Exception:exception.rdf.twig"));
// line 1
$this->loadTemplate("@Twig/Exception/exception.xml.twig", "TwigBundle:Exception:exception.rdf.twig", 1)->display(array_merge($context, array("exception" => (isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")))));
$__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a->leave($__internal_526d7a805785be4fb721c754b2cee69154d58ade11c606da9590ba90d330241a_prof);
$__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7->leave($__internal_eec35cd5a10ba99b284e27c6831565132f96b0a120b58f10f2e9b54513d0d1f7_prof);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception.rdf.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 25 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% include '@Twig/Exception/exception.xml.twig' with { 'exception': exception } %}
", "TwigBundle:Exception:exception.rdf.twig", "C:\\wamp64\\www\\Symfony\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle/Resources/views/Exception/exception.rdf.twig");
}
}
| messaoudiDEV/citypocketBackoffice | Symfony/var/cache/dev/twig/43/43468dad29714cf35fffa471cafcb8fedae808ea624963fc40a0b533af7edd3e.php | PHP | apache-2.0 | 2,965 |
<!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_20) on Tue Dec 23 13:29:41 PST 2014 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Deprecated List (jcuda-windows64 6.5 API)</title>
<meta name="date" content="2014-12-23">
<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="Deprecated List (jcuda-windows64 6.5 API)";
}
}
catch(err) {
}
//-->
</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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
<ul>
<li><a href="#class">Deprecated Classes</a></li>
<li><a href="#field">Deprecated Fields</a></li>
<li><a href="#method">Deprecated Methods</a></li>
</ul>
</div>
<div class="contentContainer"><a name="class">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Classes table, listing deprecated classes, and an explanation">
<caption><span>Deprecated Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUGLmap_flags.html" title="class in jcuda.driver">jcuda.driver.CUGLmap_flags</a>
<div class="block"><span class="deprecationComment">As of CUDA 3.0</span></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="field">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Fields table, listing deprecated fields, and an explanation">
<caption><span>Deprecated Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER</a>
<div class="block"><span class="deprecationComment">Deprecated, do not use.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_GPU_OVERLAP">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_GPU_OVERLAP</a>
<div class="block"><span class="deprecationComment">Use instead CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT</a>
<div class="block"><span class="deprecationComment">Use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES</a>
<div class="block"><span class="deprecationComment">Use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH</a>
<div class="block"><span class="deprecationComment">Use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK</a>
<div class="block"><span class="deprecationComment">use CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUdevice_attribute.html#CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK">jcuda.driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK</a>
<div class="block"><span class="deprecationComment">use CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/JCudaDriver.html#CU_MEMPEERREGISTER_DEVICEMAP">jcuda.driver.JCudaDriver.CU_MEMPEERREGISTER_DEVICEMAP</a>
<div class="block"><span class="deprecationComment">This value has been added in CUDA 4.0 RC,
and removed in CUDA 4.0 RC2</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/JCudaDriver.html#CU_STREAM_CALLBACK_BLOCKING">jcuda.driver.JCudaDriver.CU_STREAM_CALLBACK_BLOCKING</a>
<div class="block"><span class="deprecationComment">This flag was only present in CUDA 5.0.25 (release candidate)
and may be removed (or added again) in future releases</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/JCudaDriver.html#CU_STREAM_CALLBACK_NONBLOCKING">jcuda.driver.JCudaDriver.CU_STREAM_CALLBACK_NONBLOCKING</a>
<div class="block"><span class="deprecationComment">This flag was only present in CUDA 5.0.25 (release candidate)
and may be removed (or added again) in future releases</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/JCudaDriver.html#CUDA_ARRAY3D_2DARRAY">jcuda.driver.JCudaDriver.CUDA_ARRAY3D_2DARRAY</a>
<div class="block"><span class="deprecationComment">use CUDA_ARRAY3D_LAYERED</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUresult.html#CUDA_ERROR_PEER_MEMORY_ALREADY_REGISTERED">jcuda.driver.CUresult.CUDA_ERROR_PEER_MEMORY_ALREADY_REGISTERED</a>
<div class="block"><span class="deprecationComment">This value has been added in CUDA 4.0 RC,
and removed in CUDA 4.0 RC2</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUresult.html#CUDA_ERROR_PEER_MEMORY_NOT_REGISTERED">jcuda.driver.CUresult.CUDA_ERROR_PEER_MEMORY_NOT_REGISTERED</a>
<div class="block"><span class="deprecationComment">This value has been added in CUDA 4.0 RC,
and removed in CUDA 4.0 RC2</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUresult.html#CUDA_ERROR_PROFILER_ALREADY_STARTED">jcuda.driver.CUresult.CUDA_ERROR_PROFILER_ALREADY_STARTED</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0.
It is no longer an error to call cuProfilerStart() when
profiling is already enabled.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/CUresult.html#CUDA_ERROR_PROFILER_ALREADY_STOPPED">jcuda.driver.CUresult.CUDA_ERROR_PROFILER_ALREADY_STOPPED</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0.
It is no longer an error to call cuProfilerStop() when
profiling is already disabled.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/driver/CUresult.html#CUDA_ERROR_PROFILER_NOT_INITIALIZED">jcuda.driver.CUresult.CUDA_ERROR_PROFILER_NOT_INITIALIZED</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0.
It is no longer an error to attempt to enable/disable the
profiling via ::cuProfilerStart or ::cuProfilerStop without
initialization.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/JCuda.html#cudaDeviceBlockingSync">jcuda.runtime.JCuda.cudaDeviceBlockingSync</a>
<div class="block"><span class="deprecationComment">As of CUDA 4.0 and replaced by cudaDeviceScheduleBlockingSync</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorAddressOfConstant">jcuda.runtime.cudaError.cudaErrorAddressOfConstant</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Variables in constant
memory may now have their address taken by the runtime via
<a href="jcuda/runtime/JCuda.html#cudaGetSymbolAddress-jcuda.Pointer-java.lang.String-"><code>JCuda.cudaGetSymbolAddress(jcuda.Pointer, java.lang.String)</code></a>.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorApiFailureBase">jcuda.runtime.cudaError.cudaErrorApiFailureBase</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 4.1.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorMemoryValueTooLarge">jcuda.runtime.cudaError.cudaErrorMemoryValueTooLarge</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorMixedDeviceExecution">jcuda.runtime.cudaError.cudaErrorMixedDeviceExecution</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorNotYetImplemented">jcuda.runtime.cudaError.cudaErrorNotYetImplemented</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 4.1.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorPriorLaunchFailure">jcuda.runtime.cudaError.cudaErrorPriorLaunchFailure</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorProfilerAlreadyStarted">jcuda.runtime.cudaError.cudaErrorProfilerAlreadyStarted</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0. It is no longer an error
to call <a href="jcuda/runtime/JCuda.html#cudaProfilerStart--"><code>JCuda.cudaProfilerStart()</code></a> when profiling is already enabled.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorProfilerAlreadyStopped">jcuda.runtime.cudaError.cudaErrorProfilerAlreadyStopped</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0. It is no longer an error
to call <a href="jcuda/runtime/JCuda.html#cudaProfilerStop--"><code>JCuda.cudaProfilerStop()</code></a> when profiling is already disabled.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorProfilerNotInitialized">jcuda.runtime.cudaError.cudaErrorProfilerNotInitialized</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 5.0. It is no longer an error
to attempt to enable/disable the profiling via <a href="jcuda/runtime/JCuda.html#cudaProfilerStart--"><code>JCuda.cudaProfilerStart()</code></a> or
<a href="jcuda/runtime/JCuda.html#cudaProfilerStop--"><code>JCuda.cudaProfilerStop()</code></a> without initialization.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorSynchronizationError">jcuda.runtime.cudaError.cudaErrorSynchronizationError</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorTextureFetchFailed">jcuda.runtime.cudaError.cudaErrorTextureFetchFailed</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/cudaError.html#cudaErrorTextureNotBound">jcuda.runtime.cudaError.cudaErrorTextureNotBound</a>
<div class="block"><span class="deprecationComment">This error return is deprecated as of CUDA 3.1. Device emulation mode was
removed with the CUDA 3.1 release.</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="jcuda/runtime/JCuda.html#cudaStreamCallbackBlocking">jcuda.runtime.JCuda.cudaStreamCallbackBlocking</a>
<div class="block"><span class="deprecationComment">This flag was only present in CUDA 5.0.25 (release candidate)
and may be removed (or added again) in future releases</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="jcuda/runtime/JCuda.html#cudaStreamCallbackNonblocking">jcuda.runtime.JCuda.cudaStreamCallbackNonblocking</a>
<div class="block"><span class="deprecationComment">This flag was only present in CUDA 5.0.25 (release candidate)
and may be removed (or added again) in future releases</span></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="method">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Methods table, listing deprecated methods, and an explanation">
<caption><span>Deprecated Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="jcuda/driver/JCudaDriver.html#align-int-int-">jcuda.driver.JCudaDriver.align(int, int)</a>
<div class="block"><span class="deprecationComment">This method was intended for a simpler
kernel parameter setup in earlier CUDA versions,
and should not be required any more. It may be
removed in future releases.</span></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= 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>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014. All Rights Reserved.</small></p>
</body>
</html>
| SkymindIO/jcuda-windows64 | jcuda-windows64/target/apidocs/deprecated-list.html | HTML | apache-2.0 | 17,113 |
# Vermilacinia cerebra Spjut SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Sida, Bot. Misc. 14: 181 (1996)
#### Original name
Vermilacinia cerebra Spjut
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Vermilacinia/Vermilacinia cerebra/README.md | Markdown | apache-2.0 | 208 |
/* Copyright (c) 2015 "Naftoreiclag" https://github.com/Naftoreiclag
*
* Distributed under the Apache License Version 2.0 (http://www.apache.org/licenses/)
* See accompanying file LICENSE
*/
#include "nrsalPrimitives.h"
nrsalPrimitives::nrsalPrimitives()
{
//ctor
}
nrsalPrimitives::~nrsalPrimitives()
{
//dtor
}
| Naftoreiclag/VS7C | src/nrsalPrimitives.cpp | C++ | apache-2.0 | 322 |
#/
# @license Apache-2.0
#
# Copyright (c) 2020 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#/
# VARIABLES #
ifndef VERBOSE
QUIET := @
else
QUIET :=
endif
# Determine the OS ([1][1], [2][2]).
#
# [1]: https://en.wikipedia.org/wiki/Uname#Examples
# [2]: http://stackoverflow.com/a/27776822/2225624
OS ?= $(shell uname)
ifneq (, $(findstring MINGW,$(OS)))
OS := WINNT
else
ifneq (, $(findstring MSYS,$(OS)))
OS := WINNT
else
ifneq (, $(findstring CYGWIN,$(OS)))
OS := WINNT
else
ifneq (, $(findstring Windows_NT,$(OS)))
OS := WINNT
endif
endif
endif
endif
# Define the program used for compiling C source files:
ifdef C_COMPILER
CC := $(C_COMPILER)
else
CC := gcc
endif
# Define the command-line options when compiling C files:
CFLAGS ?= \
-std=c99 \
-O3 \
-Wall \
-pedantic
# Determine whether to generate position independent code ([1][1], [2][2]).
#
# [1]: https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options
# [2]: http://stackoverflow.com/questions/5311515/gcc-fpic-option
ifeq ($(OS), WINNT)
fPIC ?=
else
fPIC ?= -fPIC
endif
# List of source files:
c_src := ../../src/dcopy.c
# List of C targets:
c_targets := benchmark.length.out
# RULES #
#/
# Compiles C source files.
#
# @param {string} [C_COMPILER] - C compiler (e.g., `gcc`)
# @param {string} [CFLAGS] - C compiler options
# @param {(string|void)} [fPIC] - compiler flag indicating whether to generate position independent code (e.g., `-fPIC`)
#
# @example
# make
#
# @example
# make all
#/
all: $(c_targets)
.PHONY: all
#/
# Compiles C source files.
#
# @private
# @param {string} CC - C compiler
# @param {string} CFLAGS - C compiler flags
# @param {(string|void)} fPIC - compiler flag indicating whether to generate position independent code
#/
$(c_targets): %.out: %.c
$(QUIET) $(CC) $(CFLAGS) $(fPIC) -I ../../include -o $@ $(c_src) $< -lm
#/
# Runs compiled benchmarks.
#
# @example
# make run
#/
run: $(c_targets)
$(QUIET) ./$<
.PHONY: run
#/
# Removes generated files.
#
# @example
# make clean
#/
clean:
$(QUIET) -rm -f *.o *.out
.PHONY: clean
| stdlib-js/stdlib | lib/node_modules/@stdlib/blas/base/dcopy/benchmark/c/Makefile | Makefile | apache-2.0 | 2,590 |
<!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_79) on Thu Sep 17 01:48:58 IST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.cloud.ZkTestServer.LimitViolationAction (Solr 5.3.1 API)</title>
<meta name="date" content="2015-09-17">
<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="Uses of Class org.apache.solr.cloud.ZkTestServer.LimitViolationAction (Solr 5.3.1 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><a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/ZkTestServer.LimitViolationAction.html" target="_top">Frames</a></li>
<li><a href="ZkTestServer.LimitViolationAction.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.cloud.ZkTestServer.LimitViolationAction" class="title">Uses of Class<br>org.apache.solr.cloud.ZkTestServer.LimitViolationAction</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.solr.cloud">org.apache.solr.cloud</a></td>
<td class="colLast">
<div class="block">Base classes and utilities for creating and testing <a href="https://wiki.apache.org/solr/SolrCloud">Solr Cloud</a> clusters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.cloud">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a> in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a> that return <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a></code></td>
<td class="colLast"><span class="strong">ZkTestServer.LimitViolationAction.</span><code><strong><a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html#valueOf(java.lang.String)">valueOf</a></strong>(<a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a>[]</code></td>
<td class="colLast"><span class="strong">ZkTestServer.LimitViolationAction.</span><code><strong><a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a> with parameters of type <a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">ZkTestServer.</span><code><strong><a href="../../../../../org/apache/solr/cloud/ZkTestServer.html#setViolationReportAction(org.apache.solr.cloud.ZkTestServer.LimitViolationAction)">setViolationReportAction</a></strong>(<a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">ZkTestServer.LimitViolationAction</a> violationReportAction)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= 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><a href="../../../../../org/apache/solr/cloud/ZkTestServer.LimitViolationAction.html" title="enum in org.apache.solr.cloud">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/ZkTestServer.LimitViolationAction.html" target="_top">Frames</a></li>
<li><a href="ZkTestServer.LimitViolationAction.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| TitasNandi/Summer_Project | solr-5.3.1/docs/solr-test-framework/org/apache/solr/cloud/class-use/ZkTestServer.LimitViolationAction.html | HTML | apache-2.0 | 9,203 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>ObjFormatType - com.ligadata.olep.metadata.ObjFormatType</title>
<meta name="description" content="ObjFormatType - com.ligadata.olep.metadata.ObjFormatType" />
<meta name="keywords" content="ObjFormatType com.ligadata.olep.metadata.ObjFormatType" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript">
if(top === self) {
var url = '../../../../index.html';
var hash = 'com.ligadata.olep.metadata.ObjFormatType$';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="value">
<div id="definition">
<img src="../../../../lib/object_big.png" />
<p id="owner"><a href="../../../package.html" class="extype" name="com">com</a>.<a href="../../package.html" class="extype" name="com.ligadata">ligadata</a>.<a href="../package.html" class="extype" name="com.ligadata.olep">olep</a>.<a href="package.html" class="extype" name="com.ligadata.olep.metadata">metadata</a></p>
<h1>ObjFormatType</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">ObjFormatType</span><span class="result"> extends <span class="extype" name="scala.Enumeration">Enumeration</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.Enumeration">Enumeration</span>, <span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="com.ligadata.olep.metadata.ObjFormatType"><span>ObjFormatType</span></li><li class="in" name="scala.Enumeration"><span>Enumeration</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="types" class="types members">
<h3>Type Members</h3>
<ol><li name="com.ligadata.olep.metadata.ObjFormatType.FormatType" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="FormatType=com.ligadata.olep.metadata.ObjFormatType.Value"></a>
<a id="FormatType:FormatType"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">type</span>
</span>
<span class="symbol">
<span class="name">FormatType</span><span class="result"> = <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
</li><li name="scala.Enumeration.Val" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ValextendsEnumeration.this.ValuewithSerializable"></a>
<a id="Val:Val"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">Val</span><span class="result"> extends <span class="extype" name="scala.Enumeration.Value">Value</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd><dt>Annotations</dt><dd>
<span class="name">@SerialVersionUID</span><span class="args">(<span>
<span class="symbol">-3501153230598116017L</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.Enumeration.Value" visbl="pub" data-isabs="true" fullComment="yes" group="Ungrouped">
<a id="ValueextendsOrdered[Enumeration.this.Value]withSerializable"></a>
<a id="Value:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">abstract </span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">Value</span><span class="result"> extends <span class="extype" name="scala.Ordered">Ordered</span>[<span class="extype" name="scala.Enumeration.Value">Value</span>] with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd><dt>Annotations</dt><dd>
<span class="name">@SerialVersionUID</span><span class="args">(<span>
<span class="symbol">7091335633555234129L</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.Enumeration.ValueSet" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ValueSetextendsAbstractSet[Enumeration.this.Value]withSortedSet[Enumeration.this.Value]withSortedSetLike[Enumeration.this.Value,Enumeration.this.ValueSet]withSerializable"></a>
<a id="ValueSet:ValueSet"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">ValueSet</span><span class="result"> extends <span class="extype" name="scala.collection.AbstractSet">AbstractSet</span>[<span class="extype" name="scala.Enumeration.Value">Value</span>] with <span class="extype" name="scala.collection.immutable.SortedSet">SortedSet</span>[<span class="extype" name="scala.Enumeration.Value">Value</span>] with <span class="extype" name="scala.collection.SortedSetLike">SortedSetLike</span>[<span class="extype" name="scala.Enumeration.Value">Value</span>, <span class="extype" name="scala.Enumeration.ValueSet">ValueSet</span>] with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.Enumeration#Value" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Value(i:Int,name:String):Enumeration.this.Value"></a>
<a id="Value(Int,String):Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">Value</span><span class="params">(<span name="i">i: <span class="extype" name="scala.Int">Int</span></span>, <span name="name">name: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Enumeration#Value" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Value(name:String):Enumeration.this.Value"></a>
<a id="Value(String):Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">Value</span><span class="params">(<span name="name">name: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Enumeration#Value" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Value(i:Int):Enumeration.this.Value"></a>
<a id="Value(Int):Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">Value</span><span class="params">(<span name="i">i: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Enumeration#Value" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Value:Enumeration.this.Value"></a>
<a id="Value:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">Value</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Enumeration#apply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="apply(x:Int):Enumeration.this.Value"></a>
<a id="apply(Int):Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">apply</span><span class="params">(<span name="x">x: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="com.ligadata.olep.metadata.ObjFormatType#asString" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="asString(typ:com.ligadata.olep.metadata.ObjFormatType.FormatType):String"></a>
<a id="asString(FormatType):String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asString</span><span class="params">(<span name="typ">typ: <a href="#FormatType=com.ligadata.olep.metadata.ObjFormatType.Value" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.FormatType">FormatType</a></span>)</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="com.ligadata.olep.metadata.ObjFormatType#fCSV" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="fCSV:com.ligadata.olep.metadata.ObjFormatType.Value"></a>
<a id="fCSV:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">fCSV</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
</li><li name="com.ligadata.olep.metadata.ObjFormatType#fJSON" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="fJSON:com.ligadata.olep.metadata.ObjFormatType.Value"></a>
<a id="fJSON:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">fJSON</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
</li><li name="com.ligadata.olep.metadata.ObjFormatType#fSERIALIZED" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="fSERIALIZED:com.ligadata.olep.metadata.ObjFormatType.Value"></a>
<a id="fSERIALIZED:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">fSERIALIZED</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
</li><li name="com.ligadata.olep.metadata.ObjFormatType#fXML" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="fXML:com.ligadata.olep.metadata.ObjFormatType.Value"></a>
<a id="fXML:Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">fXML</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.Enumeration#maxId" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="maxId:Int"></a>
<a id="maxId:Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">maxId</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Enumeration#nextId" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="nextId:Int"></a>
<a id="nextId:Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">var</span>
</span>
<span class="symbol">
<span class="name">nextId</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.Enumeration#nextName" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="nextName:Iterator[String]"></a>
<a id="nextName:Iterator[String]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">var</span>
</span>
<span class="symbol">
<span class="name">nextName</span><span class="result">: <span class="extype" name="scala.Iterator">Iterator</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Enumeration#readResolve" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="readResolve():AnyRef"></a>
<a id="readResolve():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">readResolve</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Enumeration#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration → AnyRef → Any</dd></dl></div>
</li><li name="scala.Enumeration#values" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="values:Enumeration.this.ValueSet"></a>
<a id="values:ValueSet"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">values</span><span class="result">: <a href="#ValueSetextendsAbstractSet[Enumeration.this.Value]withSortedSet[Enumeration.this.Value]withSortedSetLike[Enumeration.this.Value,Enumeration.this.ValueSet]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.ValueSet">ValueSet</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.Enumeration#withName" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="withName(s:String):Enumeration.this.Value"></a>
<a id="withName(String):Value"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">withName</span><span class="params">(<span name="s">s: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="#ValueextendsOrdered[Enumeration.this.Value]withSerializable" class="extmbr" name="com.ligadata.olep.metadata.ObjFormatType.Value">Value</a></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Enumeration</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Enumeration">
<h3>Inherited from <span class="extype" name="scala.Enumeration">Enumeration</span></h3>
</div><div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
<script defer="defer" type="text/javascript" id="jquery-js" src="../../../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../../../lib/template.js"></script>
</body>
</html> | traytonwhite/Kamanja | trunk/Documentation/KamanjaAPIDocs/com/ligadata/olep/metadata/ObjFormatType$.html | HTML | apache-2.0 | 39,574 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGOD_SCHEDULER_JOB_GUARD_H
#define ARANGOD_SCHEDULER_JOB_GUARD_H 1
#include "Basics/Common.h"
#include "Basics/SameThreadAsserter.h"
#include "Scheduler/EventLoop.h"
#include "Scheduler/Scheduler.h"
namespace arangodb {
namespace rest {
class Scheduler;
}
class JobGuard : public SameThreadAsserter {
public:
JobGuard(JobGuard const&) = delete;
JobGuard& operator=(JobGuard const&) = delete;
explicit JobGuard(EventLoop const& loop) : SameThreadAsserter(), _scheduler(loop._scheduler) {}
explicit JobGuard(rest::Scheduler* scheduler) : SameThreadAsserter(), _scheduler(scheduler) {}
~JobGuard() { release(); }
public:
void work() {
TRI_ASSERT(!_isWorkingFlag);
if (0 == _isWorking) {
_scheduler->workThread();
}
++_isWorking;
_isWorkingFlag = true;
}
void block() {
TRI_ASSERT(!_isBlockedFlag);
if (0 == _isBlocked) {
_scheduler->blockThread();
}
++_isBlocked;
_isBlockedFlag = true;
}
private:
void release() {
if (_isWorkingFlag) {
--_isWorking;
_isWorkingFlag = false;
if (0 == _isWorking) {
_scheduler->unworkThread();
}
}
if (_isBlockedFlag) {
--_isBlocked;
_isBlockedFlag = false;
if (0 == _isBlocked) {
_scheduler->unblockThread();
}
}
}
private:
rest::Scheduler* _scheduler;
bool _isWorkingFlag = false;
bool _isBlockedFlag = false;
static thread_local size_t _isWorking;
static thread_local size_t _isBlocked;
};
}
#endif
| joerg84/arangodb | arangod/Scheduler/JobGuard.h | C | apache-2.0 | 2,425 |
package org.ns.vk.cachegrabber.ui;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import org.ns.func.Callback;
import org.ns.ioc.IoC;
import org.ns.vk.cachegrabber.api.Application;
import org.ns.vk.cachegrabber.api.vk.Audio;
import org.ns.vk.cachegrabber.api.vk.VKApi;
/**
*
* @author stupak
*/
public class TestAction extends AbstractAction {
public TestAction() {
super("Test action");
}
@Override
public void actionPerformed(ActionEvent e) {
VKApi vkApi = IoC.get(Application.class).getVKApi();
String ownerId = "32659923";
String audioId = "259636837";
vkApi.getById(ownerId, audioId, new Callback<Audio>() {
@Override
public void call(Audio audio) {
Logger.getLogger(TestAction.class.getName()).log(Level.INFO, "loaded audio: {0}", audio);
}
});
}
}
| nikolaas/vk-cache-grabber | src/main/java/org/ns/vk/cachegrabber/ui/TestAction.java | Java | apache-2.0 | 994 |
---
layout: event
title: "OSM Bangladesh: Bringing scattered OSM activities under single platform"
theme: Community growth and diversity, outreach
theme_full: Community growth and diversity, outreach, Organisational, legal
category: Community growth and diversity, outreach
audience: "(1a) Data contributors: Community"
audience_full: "(1a) Data contributors: Community, (2c) Data users: Personal, (3b) Core OSM: OSMF working groups (community, licence, data...), (3c) Core OSM: OSMF board (strategy and vision)"
name: Ahasanul Hoque
organization: OpenStreetMap Bangladesh Community
twitter:
osm: aHaSaN
room: Room 1
tags:
- slot14
youtube_recording: nMxSDjKiZ-M
youtube_time: [4,0]
slides: https://speakerdeck.com/sotm2017/day2-1130-osm-bangladesh-bringing-scattered-osm-activities-under-single-platform
---
My session will be based on three discussion topics. Firstly, the uneven journey of OpenStreetMap in Bangladesh and tackling the obstacles. Secondly, the ongoing OSM activities in Bangladesh by different government and non government agencies, chapters and small communities. And lastly, how to integrate the scattered OSM group and activities under a single platform.
| openstreetmap/stateofthemap-2017 | _posts/schedule/0200-01-02-osm-bangladesh-bringing-scattered-osm-activities-under-single-platform.md | Markdown | apache-2.0 | 1,181 |
# Lestibudesia Thouars GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Lestibudesia/README.md | Markdown | apache-2.0 | 168 |
package com.mapswithme.maps.maplayer.traffic;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@MainThread
public enum TrafficManager
{
INSTANCE;
private final static String TAG = TrafficManager.class.getSimpleName();
@NonNull
private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.TRAFFIC);
@NonNull
private final TrafficState.StateChangeListener mStateChangeListener = new TrafficStateListener();
@NonNull
private TrafficState mState = TrafficState.DISABLED;
@NonNull
private final List<TrafficCallback> mCallbacks = new ArrayList<>();
private boolean mInitialized = false;
public void initialize()
{
mLogger.d(TAG, "Initialization of traffic manager and setting the listener for traffic state changes");
TrafficState.nativeSetListener(mStateChangeListener);
mInitialized = true;
}
public void toggle()
{
checkInitialization();
if (isEnabled())
disable();
else
enable();
}
private void enable()
{
mLogger.d(TAG, "Enable traffic");
TrafficState.nativeEnable();
}
private void disable()
{
checkInitialization();
mLogger.d(TAG, "Disable traffic");
TrafficState.nativeDisable();
}
public boolean isEnabled()
{
checkInitialization();
return TrafficState.nativeIsEnabled();
}
public void attach(@NonNull TrafficCallback callback)
{
checkInitialization();
if (mCallbacks.contains(callback))
{
throw new IllegalStateException("A callback '" + callback
+ "' is already attached. Check that the 'detachAll' method was called.");
}
mLogger.d(TAG, "Attach callback '" + callback + "'");
mCallbacks.add(callback);
postPendingState();
}
private void postPendingState()
{
mStateChangeListener.onTrafficStateChanged(mState.ordinal());
}
public void detachAll()
{
checkInitialization();
if (mCallbacks.isEmpty())
{
mLogger.w(TAG, "There are no attached callbacks. Invoke the 'detachAll' method " +
"only when it's really needed!", new Throwable());
return;
}
for (TrafficCallback callback : mCallbacks)
mLogger.d(TAG, "Detach callback '" + callback + "'");
mCallbacks.clear();
}
private void checkInitialization()
{
if (!mInitialized)
throw new AssertionError("Traffic manager is not initialized!");
}
public void setEnabled(boolean enabled)
{
checkInitialization();
if (isEnabled() == enabled)
return;
if (enabled)
enable();
else
disable();
}
private class TrafficStateListener implements TrafficState.StateChangeListener
{
@Override
@MainThread
public void onTrafficStateChanged(int index)
{
TrafficState newTrafficState = TrafficState.values()[index];
mLogger.d(TAG, "onTrafficStateChanged current state = " + mState
+ " new value = " + newTrafficState);
if (mState == newTrafficState)
return;
mState = newTrafficState;
mState.activate(mCallbacks);
}
}
public interface TrafficCallback
{
void onEnabled();
void onDisabled();
void onWaitingData();
void onOutdated();
void onNetworkError();
void onNoData();
void onExpiredData();
void onExpiredApp();
}
}
| rokuz/omim | android/src/com/mapswithme/maps/maplayer/traffic/TrafficManager.java | Java | apache-2.0 | 3,514 |
package brennus.asm;
import static brennus.model.ExistingType.VOID;
import static brennus.model.ExistingType.existing;
import static brennus.model.Protection.PUBLIC;
import static junit.framework.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import brennus.Builder;
import brennus.MethodBuilder;
import brennus.SwitchBuilder;
import brennus.ThenBuilder;
import brennus.asm.TestGeneration.DynamicClassLoader;
import brennus.model.FutureType;
import brennus.printer.TypePrinter;
import org.junit.Test;
public class TestGoto {
abstract public static class FSA {
private List<String> states = new ArrayList<String>();
abstract public void exec();
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
abstract public static class FSA2 {
private List<String> states = new ArrayList<String>();
abstract public void exec(Iterator<Integer> it);
public void state(String p) {
states.add(p);
}
public List<String> getStates() {
return states;
}
}
@Test
public void testGoto() throws Exception {
FutureType testClass = new Builder()
.startClass("brennus.asm.TestGoto$TestClass", existing(FSA.class))
.startMethod(PUBLIC, VOID, "exec")
.label("a")
.exec().callOnThis("state").literal("a").endCall().endExec()
.gotoLabel("c")
.label("b")
.exec().callOnThis("state").literal("b").endCall().endExec()
.gotoLabel("end")
.label("c")
.exec().callOnThis("state").literal("c").endCall().endExec()
.gotoLabel("b")
.label("end")
.endMethod()
.endClass();
// new TypePrinter().print(testClass);
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass");
FSA fsa = (FSA)generated.newInstance();
fsa.exec();
assertEquals(Arrays.asList("a", "c", "b"), fsa.getStates());
}
@Test
public void testFSA() throws Exception {
int[][] fsa = {
{0,1,2,3},
{0,1,2,3},
{0,1,2,3},
{0,1,2,3}
};
MethodBuilder m = new Builder()
.startClass("brennus.asm.TestGoto$TestClass2", existing(FSA2.class))
.startMethod(PUBLIC, VOID, "exec").param(existing(Iterator.class), "it")
.gotoLabel("start")
.label("start");
for (int i = 0; i < fsa.length; i++) {
m = m.label("s_"+i)
.exec().callOnThis("state").literal("s_"+i).endCall().endExec();
SwitchBuilder<ThenBuilder<MethodBuilder>> s = m.ifExp().get("it").callNoParam("hasNext").thenBlock()
.switchOn().get("it").callNoParam("next").switchBlock();
for (int j = 0; j < fsa[i].length; j++) {
int to = fsa[i][j];
s = s.caseBlock(j)
.gotoLabel("s_"+to)
.endCase();
}
m = s.endSwitch()
.elseBlock()
.gotoLabel("end")
.endIf();
}
FutureType testClass = m.label("end").endMethod().endClass();
new TypePrinter().print(testClass);
Logger.getLogger("brennus").setLevel(Level.FINEST);
Logger.getLogger("brennus").addHandler(new Handler() {
public void publish(LogRecord record) {
System.out.println(record.getMessage());
}
public void flush() {
System.out.flush();
}
public void close() throws SecurityException {
System.out.flush();
}
});
DynamicClassLoader cl = new DynamicClassLoader();
cl.define(testClass);
Class<?> generated = (Class<?>)cl.loadClass("brennus.asm.TestGoto$TestClass2");
FSA2 compiledFSA = (FSA2)generated.newInstance();
compiledFSA.exec(Arrays.asList(3,2,1).iterator());
assertEquals(Arrays.asList("s_0", "s_3", "s_2", "s_1"), compiledFSA.getStates());
}
}
| julienledem/brennus | brennus-asm/src/test/java/brennus/asm/TestGoto.java | Java | apache-2.0 | 4,143 |
/*-
* #%L
* Simmetrics - Examples
* %%
* Copyright (C) 2014 - 2021 Simmetrics Authors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.mpkorstanje.simmetrics.example;
import static com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder.with;
import com.github.mpkorstanje.simmetrics.StringDistance;
import com.github.mpkorstanje.simmetrics.builders.StringDistanceBuilder;
import com.github.mpkorstanje.simmetrics.metrics.EuclideanDistance;
import com.github.mpkorstanje.simmetrics.metrics.StringDistances;
import com.github.mpkorstanje.simmetrics.tokenizers.Tokenizers;
/**
* The StringDistances utility class contains a predefined list of well
* known distance metrics for strings.
*/
final class StringDistanceExample {
/**
* Two strings can be compared using a predefined distance metric.
*/
static float example01() {
String str1 = "This is a sentence. It is made of words";
String str2 = "This sentence is similar. It has almost the same words";
StringDistance metric = StringDistances.levenshtein();
return metric.distance(str1, str2); // 30.0000
}
/**
* A tokenizer is included when the metric is a set or list metric. For the
* euclidean distance, it is a whitespace tokenizer.
*
* Note that most predefined metrics are setup with a whitespace tokenizer.
*/
static float example02() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric = StringDistances.euclideanDistance();
return metric.distance(str1, str2); // 2.0000
}
/**
* Using the string distance builder distance metrics can be customized.
* Instead of a whitespace tokenizer a q-gram tokenizer is used.
*
* For more examples see StringDistanceBuilderExample.
*/
static float example03() {
String str1 = "A quirky thing it is. This is a sentence.";
String str2 = "This sentence is similar. A quirky thing it is.";
StringDistance metric =
StringDistanceBuilder.with(new EuclideanDistance<>())
.tokenize(Tokenizers.qGram(3))
.build();
return metric.distance(str1, str2); // 4.8989
}
}
| mpkorstanje/simmetrics | simmetrics-example/src/main/java/com/github/mpkorstanje/simmetrics/example/StringDistanceExample.java | Java | apache-2.0 | 2,695 |
/**
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hdodenhof.androidstatemachine;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
/**
* <p>The state machine defined here is a hierarchical state machine which processes messages
* and can have states arranged hierarchically.</p>
*
* <p>A state is a <code>State</code> object and must implement
* <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
* The enter/exit methods are equivalent to the construction and destruction
* in Object Oriented programming and are used to perform initialization and
* cleanup of the state respectively. The <code>getName</code> method returns the
* name of the state the default implementation returns the class name it may be
* desirable to have this return the name of the state instance name instead.
* In particular if a particular state class has multiple instances.</p>
*
* <p>When a state machine is created <code>addState</code> is used to build the
* hierarchy and <code>setInitialState</code> is used to identify which of these
* is the initial state. After construction the programmer calls <code>start</code>
* which initializes and starts the state machine. The first action the StateMachine
* is to the invoke <code>enter</code> for all of the initial state's hierarchy,
* starting at its eldest parent. The calls to enter will be done in the context
* of the StateMachines Handler not in the context of the call to start and they
* will be invoked before any messages are processed. For example, given the simple
* state machine below mP1.enter will be invoked and then mS1.enter. Finally,
* messages sent to the state machine will be processed by the current state,
* in our simple state machine below that would initially be mS1.processMessage.</p>
<code>
mP1
/ \
mS2 mS1 ----> initial state
</code>
* <p>After the state machine is created and started, messages are sent to a state
* machine using <code>sendMessage</code> and the messages are created using
* <code>obtainMessage</code>. When the state machine receives a message the
* current state's <code>processMessage</code> is invoked. In the above example
* mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
* to change the current state to a new state</p>
*
* <p>Each state in the state machine may have a zero or one parent states and if
* a child state is unable to handle a message it may have the message processed
* by its parent by returning false or NOT_HANDLED. If a message is never processed
* <code>unhandledMessage</code> will be invoked to give one last chance for the state machine
* to process the message.</p>
*
* <p>When all processing is completed a state machine may choose to call
* <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
* returns the state machine will transfer to an internal <code>HaltingState</code>
* and invoke <code>halting</code>. Any message subsequently received by the state
* machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
*
* <p>If it is desirable to completely stop the state machine call <code>quit</code> or
* <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
* call <code>onQuiting</code> and then exit Thread/Loopers.</p>
*
* <p>In addition to <code>processMessage</code> each <code>State</code> has
* an <code>enter</code> method and <code>exit</code> method which may be overridden.</p>
*
* <p>Since the states are arranged in a hierarchy transitioning to a new state
* causes current states to be exited and new states to be entered. To determine
* the list of states to be entered/exited the common parent closest to
* the current state is found. We then exit from the current state and its
* parent's up to but not including the common parent state and then enter all
* of the new states below the common parent down to the destination state.
* If there is no common parent all states are exited and then the new states
* are entered.</p>
*
* <p>Two other methods that states can use are <code>deferMessage</code> and
* <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
* a message but places it on the front of the queue rather than the back. The
* <code>deferMessage</code> causes the message to be saved on a list until a
* transition is made to a new state. At which time all of the deferred messages
* will be put on the front of the state machine queue with the oldest message
* at the front. These will then be processed by the new current state before
* any other messages that are on the queue or might be added later. Both of
* these are protected and may only be invoked from within a state machine.</p>
*
* <p>To illustrate some of these properties we'll use state machine with an 8
* state hierarchy:</p>
<code>
mP0
/ \
mP1 mS0
/ \
mS2 mS1
/ \ \
mS3 mS4 mS5 ---> initial state
</code>
* <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
* So the order of calling processMessage when a message is received is mS5,
* mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
* message by returning false or NOT_HANDLED.</p>
*
* <p>Now assume mS5.processMessage receives a message it can handle, and during
* the handling determines the machine should change states. It could call
* transitionTo(mS4) and return true or HANDLED. Immediately after returning from
* processMessage the state machine runtime will find the common parent,
* which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
* mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
* when the next message is received mS4.processMessage will be invoked.</p>
*
* <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
* It responds with "Hello World" being printed to the log for every message.</p>
<code>
class HelloWorld extends StateMachine {
HelloWorld(String name) {
super(name);
addState(mState1);
setInitialState(mState1);
}
public static HelloWorld makeHelloWorld() {
HelloWorld hw = new HelloWorld("hw");
hw.start();
return hw;
}
class State1 extends State {
@Override public boolean processMessage(Message message) {
log("Hello World");
return HANDLED;
}
}
State1 mState1 = new State1();
}
void testHelloWorld() {
HelloWorld hw = makeHelloWorld();
hw.sendMessage(hw.obtainMessage());
}
</code>
* <p>A more interesting state machine is one with four states
* with two independent parent states.</p>
<code>
mP1 mP2
/ \
mS2 mS1
</code>
* <p>Here is a description of this state machine using pseudo code.</p>
<code>
state mP1 {
enter { log("mP1.enter"); }
exit { log("mP1.exit"); }
on msg {
CMD_2 {
send(CMD_3);
defer(msg);
transitonTo(mS2);
return HANDLED;
}
return NOT_HANDLED;
}
}
INITIAL
state mS1 parent mP1 {
enter { log("mS1.enter"); }
exit { log("mS1.exit"); }
on msg {
CMD_1 {
transitionTo(mS1);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mS2 parent mP1 {
enter { log("mS2.enter"); }
exit { log("mS2.exit"); }
on msg {
CMD_2 {
send(CMD_4);
return HANDLED;
}
CMD_3 {
defer(msg);
transitionTo(mP2);
return HANDLED;
}
return NOT_HANDLED;
}
}
state mP2 {
enter {
log("mP2.enter");
send(CMD_5);
}
exit { log("mP2.exit"); }
on msg {
CMD_3, CMD_4 { return HANDLED; }
CMD_5 {
transitionTo(HaltingState);
return HANDLED;
}
return NOT_HANDLED;
}
}
</code>
* <p>The implementation is below and also in StateMachineTest:</p>
<code>
class Hsm1 extends StateMachine {
public static final int CMD_1 = 1;
public static final int CMD_2 = 2;
public static final int CMD_3 = 3;
public static final int CMD_4 = 4;
public static final int CMD_5 = 5;
public static Hsm1 makeHsm1() {
log("makeHsm1 E");
Hsm1 sm = new Hsm1("hsm1");
sm.start();
log("makeHsm1 X");
return sm;
}
Hsm1(String name) {
super(name);
log("ctor E");
// Add states, use indentation to show hierarchy
addState(mP1);
addState(mS1, mP1);
addState(mS2, mP1);
addState(mP2);
// Set the initial state
setInitialState(mS1);
log("ctor X");
}
class P1 extends State {
@Override public void enter() {
log("mP1.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mP1.processMessage what=" + message.what);
switch(message.what) {
case CMD_2:
// CMD_2 will arrive in mS2 before CMD_3
sendMessage(obtainMessage(CMD_3));
deferMessage(message);
transitionTo(mS2);
retVal = HANDLED;
break;
default:
// Any message we don't understand in this state invokes unhandledMessage
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mP1.exit");
}
}
class S1 extends State {
@Override public void enter() {
log("mS1.enter");
}
@Override public boolean processMessage(Message message) {
log("S1.processMessage what=" + message.what);
if (message.what == CMD_1) {
// Transition to ourself to show that enter/exit is called
transitionTo(mS1);
return HANDLED;
} else {
// Let parent process all other messages
return NOT_HANDLED;
}
}
@Override public void exit() {
log("mS1.exit");
}
}
class S2 extends State {
@Override public void enter() {
log("mS2.enter");
}
@Override public boolean processMessage(Message message) {
boolean retVal;
log("mS2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_2):
sendMessage(obtainMessage(CMD_4));
retVal = HANDLED;
break;
case(CMD_3):
deferMessage(message);
transitionTo(mP2);
retVal = HANDLED;
break;
default:
retVal = NOT_HANDLED;
break;
}
return retVal;
}
@Override public void exit() {
log("mS2.exit");
}
}
class P2 extends State {
@Override public void enter() {
log("mP2.enter");
sendMessage(obtainMessage(CMD_5));
}
@Override public boolean processMessage(Message message) {
log("P2.processMessage what=" + message.what);
switch(message.what) {
case(CMD_3):
break;
case(CMD_4):
break;
case(CMD_5):
transitionToHaltingState();
break;
}
return HANDLED;
}
@Override public void exit() {
log("mP2.exit");
}
}
@Override
void onHalting() {
log("halting");
synchronized (this) {
this.notifyAll();
}
}
P1 mP1 = new P1();
S1 mS1 = new S1();
S2 mS2 = new S2();
P2 mP2 = new P2();
}
</code>
* <p>If this is executed by sending two messages CMD_1 and CMD_2
* (Note the synchronize is only needed because we use hsm.wait())</p>
<code>
Hsm1 hsm = makeHsm1();
synchronize(hsm) {
hsm.sendMessage(obtainMessage(hsm.CMD_1));
hsm.sendMessage(obtainMessage(hsm.CMD_2));
try {
// wait for the messages to be handled
hsm.wait();
} catch (InterruptedException e) {
loge("exception while waiting " + e.getMessage());
}
}
</code>
* <p>The output is:</p>
<code>
D/hsm1 ( 1999): makeHsm1 E
D/hsm1 ( 1999): ctor E
D/hsm1 ( 1999): ctor X
D/hsm1 ( 1999): mP1.enter
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): makeHsm1 X
D/hsm1 ( 1999): mS1.processMessage what=1
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS1.enter
D/hsm1 ( 1999): mS1.processMessage what=2
D/hsm1 ( 1999): mP1.processMessage what=2
D/hsm1 ( 1999): mS1.exit
D/hsm1 ( 1999): mS2.enter
D/hsm1 ( 1999): mS2.processMessage what=2
D/hsm1 ( 1999): mS2.processMessage what=3
D/hsm1 ( 1999): mS2.exit
D/hsm1 ( 1999): mP1.exit
D/hsm1 ( 1999): mP2.enter
D/hsm1 ( 1999): mP2.processMessage what=3
D/hsm1 ( 1999): mP2.processMessage what=4
D/hsm1 ( 1999): mP2.processMessage what=5
D/hsm1 ( 1999): mP2.exit
D/hsm1 ( 1999): halting
</code>
*/
public class StateMachine {
// Name of the state machine and used as logging tag
private String mName;
/** Message.what value when quitting */
private static final int SM_QUIT_CMD = -1;
/** Message.what value when initializing */
private static final int SM_INIT_CMD = -2;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was processed and is not to be
* processed by parent states
*/
public static final boolean HANDLED = true;
/**
* Convenience constant that maybe returned by processMessage
* to indicate the the message was NOT processed and is to be
* processed by parent states
*/
public static final boolean NOT_HANDLED = false;
/**
* StateMachine logging record.
*/
public static class LogRec {
private StateMachine mSm;
private long mTime;
private int mWhat;
private String mInfo;
private IState mState;
private IState mOrgState;
private IState mDstState;
/**
* Constructor
*
* @param msg
* @param state the state which handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*/
LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState transToState) {
update(sm, msg, info, state, orgState, transToState);
}
/**
* Update the information in the record.
* @param state that handled the message
* @param orgState is the first state the received the message
* @param dstState is the state that was the transition target when logging
*/
public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
IState dstState) {
mSm = sm;
mTime = System.currentTimeMillis();
mWhat = (msg != null) ? msg.what : 0;
mInfo = info;
mState = state;
mOrgState = orgState;
mDstState = dstState;
}
/**
* @return time stamp
*/
public long getTime() {
return mTime;
}
/**
* @return msg.what
*/
public long getWhat() {
return mWhat;
}
/**
* @return the command that was executing
*/
public String getInfo() {
return mInfo;
}
/**
* @return the state that handled this message
*/
public IState getState() {
return mState;
}
/**
* @return the state destination state if a transition is occurring or null if none.
*/
public IState getDestState() {
return mDstState;
}
/**
* @return the original state that received the message.
*/
public IState getOriginalState() {
return mOrgState;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("time=");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(mTime);
sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
sb.append(" processed=");
sb.append(mState == null ? "<null>" : mState.getName());
sb.append(" org=");
sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
sb.append(" dest=");
sb.append(mDstState == null ? "<null>" : mDstState.getName());
sb.append(" what=");
String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
if (TextUtils.isEmpty(what)) {
sb.append(mWhat);
sb.append("(0x");
sb.append(Integer.toHexString(mWhat));
sb.append(")");
} else {
sb.append(what);
}
if (!TextUtils.isEmpty(mInfo)) {
sb.append(" ");
sb.append(mInfo);
}
return sb.toString();
}
}
/**
* A list of log records including messages recently processed by the state machine.
*
* The class maintains a list of log records including messages
* recently processed. The list is finite and may be set in the
* constructor or by calling setSize. The public interface also
* includes size which returns the number of recent records,
* count which is the number of records processed since the
* the last setSize, get which returns a record and
* add which adds a record.
*/
private static class LogRecords {
private static final int DEFAULT_SIZE = 20;
private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
private int mMaxSize = DEFAULT_SIZE;
private int mOldestIndex = 0;
private int mCount = 0;
private boolean mLogOnlyTransitions = false;
/**
* private constructor use add
*/
private LogRecords() {
}
/**
* Set size of messages to maintain and clears all current records.
*
* @param maxSize number of records to maintain at anyone time.
*/
synchronized void setSize(int maxSize) {
mMaxSize = maxSize;
mCount = 0;
mLogRecVector.clear();
}
synchronized void setLogOnlyTransitions(boolean enable) {
mLogOnlyTransitions = enable;
}
synchronized boolean logOnlyTransitions() {
return mLogOnlyTransitions;
}
/**
* @return the number of recent records.
*/
synchronized int size() {
return mLogRecVector.size();
}
/**
* @return the total number of records processed since size was set.
*/
synchronized int count() {
return mCount;
}
/**
* Clear the list of records.
*/
synchronized void cleanup() {
mLogRecVector.clear();
}
/**
* @return the information on a particular record. 0 is the oldest
* record and size()-1 is the newest record. If the index is to
* large null is returned.
*/
synchronized LogRec get(int index) {
int nextIndex = mOldestIndex + index;
if (nextIndex >= mMaxSize) {
nextIndex -= mMaxSize;
}
if (nextIndex >= size()) {
return null;
} else {
return mLogRecVector.get(nextIndex);
}
}
/**
* Add a processed message.
*
* @param msg
* @param messageInfo to be stored
* @param state that handled the message
* @param orgState is the first state the received the message but
* did not processes the message.
* @param transToState is the state that was transitioned to after the message was
* processed.
*
*/
synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
IState orgState, IState transToState) {
mCount += 1;
if (mLogRecVector.size() < mMaxSize) {
mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
} else {
LogRec pmi = mLogRecVector.get(mOldestIndex);
mOldestIndex += 1;
if (mOldestIndex >= mMaxSize) {
mOldestIndex = 0;
}
pmi.update(sm, msg, messageInfo, state, orgState, transToState);
}
}
}
private static class SmHandler extends Handler {
/** true if StateMachine has quit */
private boolean mHasQuit = false;
/** The debug flag */
private boolean mDbg = false;
/** The SmHandler object, identifies that message is internal */
private static final Object mSmHandlerObj = new Object();
/** The current message */
private Message mMsg;
/** A list of log records including messages this state machine has processed */
private LogRecords mLogRecords = new LogRecords();
/** true if construction of the state machine has not been completed */
private boolean mIsConstructionCompleted;
/** Stack used to manage the current hierarchy of states */
private StateInfo mStateStack[];
/** Top of mStateStack */
private int mStateStackTopIndex = -1;
/** A temporary stack used to manage the state stack */
private StateInfo mTempStateStack[];
/** The top of the mTempStateStack */
private int mTempStateStackCount;
/** State used when state machine is halted */
private HaltingState mHaltingState = new HaltingState();
/** State used when state machine is quitting */
private QuittingState mQuittingState = new QuittingState();
/** Reference to the StateMachine */
private StateMachine mSm;
/**
* Information about a state.
* Used to maintain the hierarchy.
*/
private class StateInfo {
/** The state */
State state;
/** The parent of this state, null if there is no parent */
StateInfo parentStateInfo;
/** True when the state has been entered and on the stack */
boolean active;
/**
* Convert StateInfo to string
*/
@Override
public String toString() {
return "state=" + state.getName() + ",active=" + active + ",parent="
+ ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
}
}
/** The map of all of the states in the state machine */
private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
/** The initial state that will process the first message */
private State mInitialState;
/** The destination state when transitionTo has been invoked */
private State mDestState;
/** The list of deferred messages */
private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
/**
* State entered when transitionToHaltingState is called.
*/
private class HaltingState extends State {
@Override
public boolean processMessage(Message msg) {
mSm.haltedProcessMessage(msg);
return true;
}
}
/**
* State entered when a valid quit message is handled.
*/
private class QuittingState extends State {
@Override
public boolean processMessage(Message msg) {
return NOT_HANDLED;
}
}
/**
* Handle messages sent to the state machine by calling
* the current state's processMessage. It also handles
* the enter/exit calls and placing any deferred messages
* back onto the queue when transitioning to a new state.
*/
@Override
public final void handleMessage(Message msg) {
if (!mHasQuit) {
if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
/** Save the current message */
mMsg = msg;
/** State that processed the message */
State msgProcessedState = null;
if (mIsConstructionCompleted) {
/** Normal path */
msgProcessedState = processMsg(msg);
} else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
&& (mMsg.obj == mSmHandlerObj)) {
/** Initial one time path. */
mIsConstructionCompleted = true;
invokeEnterMethods(0);
} else {
throw new RuntimeException("StateMachine.handleMessage: "
+ "The start method not called, received msg: " + msg);
}
performTransitions(msgProcessedState, msg);
// We need to check if mSm == null here as we could be quitting.
if (mDbg && mSm != null) mSm.log("handleMessage: X");
}
}
/**
* Do any transitions
* @param msgProcessedState is the state that processed the message
*/
private void performTransitions(State msgProcessedState, Message msg) {
/**
* If transitionTo has been called, exit and then enter
* the appropriate states. We loop on this to allow
* enter and exit methods to use transitionTo.
*/
State orgState = mStateStack[mStateStackTopIndex].state;
/**
* Record whether message needs to be logged before we transition and
* and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
* always set msg.obj to the handler.
*/
boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj);
if (mLogRecords.logOnlyTransitions()) {
/** Record only if there is a transition */
if (mDestState != null) {
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
orgState, mDestState);
}
} else if (recordLogMsg) {
/** Record message */
mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
mDestState);
}
State destState = mDestState;
if (destState != null) {
/**
* Process the transitions including transitions in the enter/exit methods
*/
while (true) {
if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
/**
* Determine the states to exit and enter and return the
* common ancestor state of the enter/exit states. Then
* invoke the exit methods then the enter methods.
*/
StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
invokeExitMethods(commonStateInfo);
int stateStackEnteringIndex = moveTempStateStackToStateStack();
invokeEnterMethods(stateStackEnteringIndex);
/**
* Since we have transitioned to a new state we need to have
* any deferred messages moved to the front of the message queue
* so they will be processed before any other messages in the
* message queue.
*/
moveDeferredMessageAtFrontOfQueue();
if (destState != mDestState) {
// A new mDestState so continue looping
destState = mDestState;
} else {
// No change in mDestState so we're done
break;
}
}
mDestState = null;
}
/**
* After processing all transitions check and
* see if the last transition was to quit or halt.
*/
if (destState != null) {
if (destState == mQuittingState) {
/**
* Call onQuitting to let subclasses cleanup.
*/
mSm.onQuitting();
cleanupAfterQuitting();
} else if (destState == mHaltingState) {
/**
* Call onHalting() if we've transitioned to the halting
* state. All subsequent messages will be processed in
* in the halting state which invokes haltedProcessMessage(msg);
*/
mSm.onHalting();
}
}
}
/**
* Cleanup all the static variables and the looper after the SM has been quit.
*/
private final void cleanupAfterQuitting() {
if (mSm.mSmThread != null) {
// If we made the thread then quit looper which stops the thread.
getLooper().quit();
mSm.mSmThread = null;
}
mSm.mSmHandler = null;
mSm = null;
mMsg = null;
mLogRecords.cleanup();
mStateStack = null;
mTempStateStack = null;
mStateInfo.clear();
mInitialState = null;
mDestState = null;
mDeferredMessages.clear();
mHasQuit = true;
}
/**
* Complete the construction of the state machine.
*/
private final void completeConstruction() {
if (mDbg) mSm.log("completeConstruction: E");
/**
* Determine the maximum depth of the state hierarchy
* so we can allocate the state stacks.
*/
int maxDepth = 0;
for (StateInfo si : mStateInfo.values()) {
int depth = 0;
for (StateInfo i = si; i != null; depth++) {
i = i.parentStateInfo;
}
if (maxDepth < depth) {
maxDepth = depth;
}
}
if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
mStateStack = new StateInfo[maxDepth];
mTempStateStack = new StateInfo[maxDepth];
setupInitialStateStack();
/** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));
if (mDbg) mSm.log("completeConstruction: X");
}
/**
* Process the message. If the current state doesn't handle
* it, call the states parent and so on. If it is never handled then
* call the state machines unhandledMessage method.
* @return the state that processed the message
*/
private final State processMsg(Message msg) {
StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
if (isQuit(msg)) {
transitionTo(mQuittingState);
} else {
while (!curStateInfo.state.processMessage(msg)) {
/**
* Not processed
*/
curStateInfo = curStateInfo.parentStateInfo;
if (curStateInfo == null) {
/**
* No parents left so it's not handled
*/
mSm.unhandledMessage(msg);
break;
}
if (mDbg) {
mSm.log("processMsg: " + curStateInfo.state.getName());
}
}
}
return (curStateInfo != null) ? curStateInfo.state : null;
}
/**
* Call the exit method for each state from the top of stack
* up to the common ancestor state.
*/
private final void invokeExitMethods(StateInfo commonStateInfo) {
while ((mStateStackTopIndex >= 0)
&& (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
State curState = mStateStack[mStateStackTopIndex].state;
if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
curState.exit();
mStateStack[mStateStackTopIndex].active = false;
mStateStackTopIndex -= 1;
}
}
/**
* Invoke the enter method starting at the entering index to top of state stack
*/
private final void invokeEnterMethods(int stateStackEnteringIndex) {
for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
mStateStack[i].state.enter();
mStateStack[i].active = true;
}
}
/**
* Move the deferred message to the front of the message queue.
*/
private final void moveDeferredMessageAtFrontOfQueue() {
/**
* The oldest messages on the deferred list must be at
* the front of the queue so start at the back, which
* as the most resent message and end with the oldest
* messages at the front of the queue.
*/
for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
Message curMsg = mDeferredMessages.get(i);
if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
sendMessageAtFrontOfQueue(curMsg);
}
mDeferredMessages.clear();
}
/**
* Move the contents of the temporary stack to the state stack
* reversing the order of the items on the temporary stack as
* they are moved.
*
* @return index into mStateStack where entering needs to start
*/
private final int moveTempStateStackToStateStack() {
int startingIndex = mStateStackTopIndex + 1;
int i = mTempStateStackCount - 1;
int j = startingIndex;
while (i >= 0) {
if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
mStateStack[j] = mTempStateStack[i];
j += 1;
i -= 1;
}
mStateStackTopIndex = j - 1;
if (mDbg) {
mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
+ ",startingIndex=" + startingIndex + ",Top="
+ mStateStack[mStateStackTopIndex].state.getName());
}
return startingIndex;
}
/**
* Setup the mTempStateStack with the states we are going to enter.
*
* This is found by searching up the destState's ancestors for a
* state that is already active i.e. StateInfo.active == true.
* The destStae and all of its inactive parents will be on the
* TempStateStack as the list of states to enter.
*
* @return StateInfo of the common ancestor for the destState and
* current state or null if there is no common parent.
*/
private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
/**
* Search up the parent list of the destination state for an active
* state. Use a do while() loop as the destState must always be entered
* even if it is active. This can happen if we are exiting/entering
* the current state.
*/
mTempStateStackCount = 0;
StateInfo curStateInfo = mStateInfo.get(destState);
do {
mTempStateStack[mTempStateStackCount++] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
} while ((curStateInfo != null) && !curStateInfo.active);
if (mDbg) {
mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
+ mTempStateStackCount + ",curStateInfo: " + curStateInfo);
}
return curStateInfo;
}
/**
* Initialize StateStack to mInitialState.
*/
private final void setupInitialStateStack() {
if (mDbg) {
mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
}
StateInfo curStateInfo = mStateInfo.get(mInitialState);
for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
mTempStateStack[mTempStateStackCount] = curStateInfo;
curStateInfo = curStateInfo.parentStateInfo;
}
// Empty the StateStack
mStateStackTopIndex = -1;
moveTempStateStackToStateStack();
}
/**
* @return current message
*/
private final Message getCurrentMessage() {
return mMsg;
}
/**
* @return current state
*/
private final IState getCurrentState() {
return mStateStack[mStateStackTopIndex].state;
}
/**
* Add a new state to the state machine. Bottom up addition
* of states is allowed but the same state may only exist
* in one hierarchy.
*
* @param state the state to add
* @param parent the parent of state
* @return stateInfo for this state
*/
private final StateInfo addState(State state, State parent) {
if (mDbg) {
mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
+ ((parent == null) ? "" : parent.getName()));
}
StateInfo parentStateInfo = null;
if (parent != null) {
parentStateInfo = mStateInfo.get(parent);
if (parentStateInfo == null) {
// Recursively add our parent as it's not been added yet.
parentStateInfo = addState(parent, null);
}
}
StateInfo stateInfo = mStateInfo.get(state);
if (stateInfo == null) {
stateInfo = new StateInfo();
mStateInfo.put(state, stateInfo);
}
// Validate that we aren't adding the same state in two different hierarchies.
if ((stateInfo.parentStateInfo != null)
&& (stateInfo.parentStateInfo != parentStateInfo)) {
throw new RuntimeException("state already added");
}
stateInfo.state = state;
stateInfo.parentStateInfo = parentStateInfo;
stateInfo.active = false;
if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
return stateInfo;
}
/**
* Constructor
*
* @param looper for dispatching messages
* @param sm the hierarchical state machine
*/
private SmHandler(Looper looper, StateMachine sm) {
super(looper);
mSm = sm;
addState(mHaltingState, null);
addState(mQuittingState, null);
}
/** @see StateMachine#setInitialState(State) */
private final void setInitialState(State initialState) {
if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
mInitialState = initialState;
}
/** @see StateMachine#transitionTo(IState) */
private final void transitionTo(IState destState) {
mDestState = (State) destState;
if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
}
/** @see StateMachine#deferMessage(Message) */
private final void deferMessage(Message msg) {
if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
/* Copy the "msg" to "newMsg" as "msg" will be recycled */
Message newMsg = obtainMessage();
newMsg.copyFrom(msg);
mDeferredMessages.add(newMsg);
}
/** @see StateMachine#quit() */
private final void quit() {
if (mDbg) mSm.log("quit:");
sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** @see StateMachine#quitNow() */
private final void quitNow() {
if (mDbg) mSm.log("quitNow:");
sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
}
/** Validate that the message was sent by quit or quitNow. */
private final boolean isQuit(Message msg) {
return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj);
}
/** @see StateMachine#isDbg() */
private final boolean isDbg() {
return mDbg;
}
/** @see StateMachine#setDbg(boolean) */
private final void setDbg(boolean dbg) {
mDbg = dbg;
}
}
private SmHandler mSmHandler;
private HandlerThread mSmThread;
/**
* Initialize.
*
* @param looper for this state machine
* @param name of the state machine
*/
private void initStateMachine(String name, Looper looper) {
mName = name;
mSmHandler = new SmHandler(looper, this);
}
/**
* Constructor creates a StateMachine with its own thread.
*
* @param name of the state machine
*/
protected StateMachine(String name) {
mSmThread = new HandlerThread(name);
mSmThread.start();
Looper looper = mSmThread.getLooper();
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the looper.
*
* @param name of the state machine
*/
protected StateMachine(String name, Looper looper) {
initStateMachine(name, looper);
}
/**
* Constructor creates a StateMachine using the handler.
*
* @param name of the state machine
*/
protected StateMachine(String name, Handler handler) {
initStateMachine(name, handler.getLooper());
}
/**
* Add a new state to the state machine
* @param state the state to add
* @param parent the parent of state
*/
protected final void addState(State state, State parent) {
mSmHandler.addState(state, parent);
}
/**
* Add a new state to the state machine, parent will be null
* @param state to add
*/
protected final void addState(State state) {
mSmHandler.addState(state, null);
}
/**
* Set the initial state. This must be invoked before
* and messages are sent to the state machine.
*
* @param initialState is the state which will receive the first message.
*/
protected final void setInitialState(State initialState) {
mSmHandler.setInitialState(initialState);
}
/**
* @return current message
*/
protected final Message getCurrentMessage() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentMessage();
}
/**
* @return current state
*/
protected final IState getCurrentState() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.getCurrentState();
}
/**
* transition to destination state. Upon returning
* from processMessage the current state's exit will
* be executed and upon the next message arriving
* destState.enter will be invoked.
*
* this function can also be called inside the enter function of the
* previous transition target, but the behavior is undefined when it is
* called mid-way through a previous transition (for example, calling this
* in the enter() routine of a intermediate node when the current transition
* target is one of the nodes descendants).
*
* @param destState will be the state that receives the next message.
*/
protected final void transitionTo(IState destState) {
mSmHandler.transitionTo(destState);
}
/**
* transition to halt state. Upon returning
* from processMessage we will exit all current
* states, execute the onHalting() method and then
* for all subsequent messages haltedProcessMessage
* will be called.
*/
protected final void transitionToHaltingState() {
mSmHandler.transitionTo(mSmHandler.mHaltingState);
}
/**
* Defer this message until next state transition.
* Upon transitioning all deferred messages will be
* placed on the queue and reprocessed in the original
* order. (i.e. The next state the oldest messages will
* be processed first)
*
* @param msg is deferred until the next transition.
*/
protected final void deferMessage(Message msg) {
mSmHandler.deferMessage(msg);
}
/**
* Called when message wasn't handled
*
* @param msg that couldn't be handled.
*/
protected void unhandledMessage(Message msg) {
if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
}
/**
* Called for any message that is received after
* transitionToHalting is called.
*/
protected void haltedProcessMessage(Message msg) {
}
/**
* This will be called once after handling a message that called
* transitionToHalting. All subsequent messages will invoke
* {@link StateMachine#haltedProcessMessage(Message)}
*/
protected void onHalting() {
}
/**
* This will be called once after a quit message that was NOT handled by
* the derived StateMachine. The StateMachine will stop and any subsequent messages will be
* ignored. In addition, if this StateMachine created the thread, the thread will
* be stopped after this method returns.
*/
protected void onQuitting() {
}
/**
* @return the name
*/
public final String getName() {
return mName;
}
/**
* Set number of log records to maintain and clears all current records.
*
* @param maxSize number of messages to maintain at anyone time.
*/
public final void setLogRecSize(int maxSize) {
mSmHandler.mLogRecords.setSize(maxSize);
}
/**
* Set to log only messages that cause a state transition
*
* @param enable {@code true} to enable, {@code false} to disable
*/
public final void setLogOnlyTransitions(boolean enable) {
mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
}
/**
* @return number of log records
*/
public final int getLogRecSize() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.size();
}
/**
* @return the total number of records processed
*/
public final int getLogRecCount() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return 0;
return smh.mLogRecords.count();
}
/**
* @return a log record, or null if index is out of range
*/
public final LogRec getLogRec(int index) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return null;
return smh.mLogRecords.get(index);
}
/**
* @return a copy of LogRecs as a collection
*/
public final Collection<LogRec> copyLogRecs() {
Vector<LogRec> vlr = new Vector<LogRec>();
SmHandler smh = mSmHandler;
if (smh != null) {
for (LogRec lr : smh.mLogRecords.mLogRecVector) {
vlr.add(lr);
}
}
return vlr;
}
/**
* Add the string to LogRecords.
*
* @param string
*/
protected void addLogRec(String string) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
}
/**
* @return true if msg should be saved in the log, default is true.
*/
protected boolean recordLogRec(Message msg) {
return true;
}
/**
* Return a string to be logged by LogRec, default
* is an empty string. Override if additional information is desired.
*
* @param msg that was processed
* @return information to be logged as a String
*/
protected String getLogRecString(Message msg) {
return "";
}
/**
* @return the string for msg.what
*/
protected String getWhatToString(int what) {
return null;
}
/**
* @return Handler, maybe null if state machine has quit.
*/
public final Handler getHandler() {
return mSmHandler;
}
/**
* Get a message and set Message.target state machine handler.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @return A Message object from the global pool
*/
public final Message obtainMessage() {
return Message.obtain(mSmHandler);
}
/**
* Get a message and set Message.target state machine handler, what.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what) {
return Message.obtain(mSmHandler, what);
}
/**
* Get a message and set Message.target state machine handler,
* what and obj.
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is the assigned to Message.what.
* @param obj is assigned to Message.obj.
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(mSmHandler, what, obj);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1) {
// use this obtain so we don't match the obtain(h, what, Object) method
return Message.obtain(mSmHandler, what, arg1, 0);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1 and arg2
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2) {
return Message.obtain(mSmHandler, what, arg1, arg2);
}
/**
* Get a message and set Message.target state machine handler,
* what, arg1, arg2 and obj
*
* Note: The handler can be null if the state machine has quit,
* which means target will be null and may cause a AndroidRuntimeException
* in MessageQueue#enqueMessage if sent directly or if sent using
* StateMachine#sendMessage the message will just be ignored.
*
* @param what is assigned to Message.what
* @param arg1 is assigned to Message.arg1
* @param arg2 is assigned to Message.arg2
* @param obj is assigned to Message.obj
* @return A Message object from the global pool
*/
public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
return Message.obtain(mSmHandler, what, arg1, arg2, obj);
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to this state machine.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessage(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessage(msg);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, Object obj, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(int what, int arg1, int arg2, Object obj,
long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(obtainMessage(what, arg1, arg2, obj), delayMillis);
}
/**
* Enqueue a message to this state machine after a delay.
*
* Message is ignored if state machine has quit.
*/
public final void sendMessageDelayed(Message msg, long delayMillis) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageDelayed(msg, delayMillis);
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(int what, int arg1, int arg2, Object obj) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(obtainMessage(what, arg1, arg2, obj));
}
/**
* Enqueue a message to the front of the queue for this state machine.
* Protected, may only be called by instances of StateMachine.
*
* Message is ignored if state machine has quit.
*/
protected final void sendMessageAtFrontOfQueue(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.sendMessageAtFrontOfQueue(msg);
}
/**
* Removes a message from the message queue.
* Protected, may only be called by instances of StateMachine.
*/
protected final void removeMessages(int what) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.removeMessages(what);
}
/**
* Validate that the message was sent by
* {@link StateMachine#quit} or {@link StateMachine#quitNow}.
* */
protected final boolean isQuit(Message msg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return msg.what == SM_QUIT_CMD;
return smh.isQuit(msg);
}
/**
* Quit the state machine after all currently queued up messages are processed.
*/
protected final void quit() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quit();
}
/**
* Quit the state machine immediately all currently queued messages will be discarded.
*/
protected final void quitNow() {
// mSmHandler can be null if the state machine is already stopped.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.quitNow();
}
/**
* @return if debugging is enabled
*/
public boolean isDbg() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return false;
return smh.isDbg();
}
/**
* Set debug enable/disabled.
*
* @param dbg is true to enable debugging.
*/
public void setDbg(boolean dbg) {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
smh.setDbg(dbg);
}
/**
* Start the state machine.
*/
public void start() {
// mSmHandler can be null if the state machine has quit.
SmHandler smh = mSmHandler;
if (smh == null) return;
/** Send the complete construction message */
smh.completeConstruction();
}
/**
* Dump the current state.
*
* @param fd
* @param pw
* @param args
*/
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println(getName() + ":");
pw.println(" total records=" + getLogRecCount());
for (int i = 0; i < getLogRecSize(); i++) {
pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString());
pw.flush();
}
pw.println("curState=" + getCurrentState().getName());
}
/**
* Log with debug and add to the LogRecords.
*
* @param s is string log
*/
protected void logAndAddLogRec(String s) {
addLogRec(s);
log(s);
}
/**
* Log with debug
*
* @param s is string log
*/
protected void log(String s) {
Log.d(mName, s);
}
/**
* Log with debug attribute
*
* @param s is string log
*/
protected void logd(String s) {
Log.d(mName, s);
}
/**
* Log with verbose attribute
*
* @param s is string log
*/
protected void logv(String s) {
Log.v(mName, s);
}
/**
* Log with info attribute
*
* @param s is string log
*/
protected void logi(String s) {
Log.i(mName, s);
}
/**
* Log with warning attribute
*
* @param s is string log
*/
protected void logw(String s) {
Log.w(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
*/
protected void loge(String s) {
Log.e(mName, s);
}
/**
* Log with error attribute
*
* @param s is string log
* @param e is a Throwable which logs additional information.
*/
protected void loge(String s, Throwable e) {
Log.e(mName, s, e);
}
}
| hdodenhof/AndroidStateMachine | library/src/main/java/de/hdodenhof/androidstatemachine/StateMachine.java | Java | apache-2.0 | 68,024 |
/*
* Copyright 2015-2020 Noel Welsh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package doodle
package java2d
package effect
import cats.effect.IO
import doodle.core.{Point,Transform}
// import doodle.java2d.algebra.Algebra
import java.awt.event._
import java.util.concurrent.atomic.AtomicReference
import javax.swing.{JFrame, Timer, WindowConstants}
import monix.reactive.subjects.PublishSubject
/**
* A [[Canvas]] is an area on the screen to which Pictures can be drawn.
*/
final class Canvas(frame: Frame) extends JFrame(frame.title) {
val panel = new Java2DPanel(frame)
/**
* The current global transform from logical to screen coordinates
*/
private val currentInverseTx: AtomicReference[Transform] =
new AtomicReference(Transform.identity)
/**
* Draw the given Picture to this [[Canvas]].
*/
def render[A](picture: Picture[A]): IO[A] = {
// Possible race condition here setting the currentInverseTx
def register(cb: Either[Throwable, Java2DPanel.RenderResult[A]] => Unit): Unit = {
// val drawing = picture(algebra)
// val (bb, rdr) = drawing.runA(List.empty).value
// val (w, h) = Java2d.size(bb, frame.size)
// val rr = Java2DPanel.RenderRequest(bb, w, h, rdr, cb)
panel.render(Java2DPanel.RenderRequest(picture, frame, cb))
}
IO.async(register).map{result =>
val inverseTx = Java2d.inverseTransform(result.boundingBox, result.width, result.height, frame.center)
currentInverseTx.set(inverseTx)
result.value
}
}
val redraw = PublishSubject[Int]()
val frameRateMs = (1000.0 * (1 / 60.0)).toInt
val frameEvent = {
/** Delay between frames when rendering at 60fps */
var firstFrame = true
var lastFrameTime = 0L
new ActionListener {
def actionPerformed(e: ActionEvent): Unit = {
val now = e.getWhen()
if (firstFrame) {
firstFrame = false
lastFrameTime = now
redraw.onNext(0)
()
} else {
redraw.onNext((now - lastFrameTime).toInt)
lastFrameTime = now
}
}
}
}
val timer = new Timer(frameRateMs, frameEvent)
val mouseMove = PublishSubject[Point]()
this.addMouseMotionListener(
new MouseMotionListener {
import scala.concurrent.duration.Duration
import scala.concurrent.Await
def mouseDragged(e: MouseEvent): Unit = ()
def mouseMoved(e: MouseEvent): Unit = {
val pt = e.getPoint()
val inverseTx = currentInverseTx.get()
val ack = mouseMove.onNext(inverseTx(Point(pt.getX(), pt.getY())))
Await.ready(ack, Duration.Inf)
()
}
}
)
this.addWindowListener(
new WindowAdapter {
override def windowClosed(evt: WindowEvent): Unit =
timer.stop()
}
)
getContentPane().add(panel)
pack()
setVisible(true)
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
repaint()
timer.start()
}
| underscoreio/doodle | java2d/src/main/scala/doodle/java2d/effect/Canvas.scala | Scala | apache-2.0 | 3,467 |
// stdafx.cpp : source file that includes just the standard includes
// importkeyboard.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| tavultesoft/keymanweb | windows/src/test/mnemonic-to-positional/importkeyboard/importkeyboard/stdafx.cpp | C++ | apache-2.0 | 293 |
namespace GeolocationBoundingBox.Google.Json
{
public class Geometry
{
public Location location { get; set; }
public string location_type { get; set; }
public Viewport viewport { get; set; }
public Bounds bounds { get; set; }
}
} | saitolabs/geolocation-bounding-box | src/GeolocationBoundingBox.Google/Json/Geometry.cs | C# | apache-2.0 | 273 |
/*
* Camunda BPM REST API
* OpenApi Spec for Camunda BPM REST API.
*
* The version of the OpenAPI document: 7.13.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.camunda.consulting.openapi.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for MissingAuthorizationDto
*/
public class MissingAuthorizationDtoTest {
private final MissingAuthorizationDto model = new MissingAuthorizationDto();
/**
* Model tests for MissingAuthorizationDto
*/
@Test
public void testMissingAuthorizationDto() {
// TODO: test MissingAuthorizationDto
}
/**
* Test the property 'permissionName'
*/
@Test
public void permissionNameTest() {
// TODO: test permissionName
}
/**
* Test the property 'resourceName'
*/
@Test
public void resourceNameTest() {
// TODO: test resourceName
}
/**
* Test the property 'resourceId'
*/
@Test
public void resourceIdTest() {
// TODO: test resourceId
}
}
| camunda/camunda-consulting | snippets/camunda-openapi-client/camunda-openapi-client/src/test/java/com/camunda/consulting/openapi/client/model/MissingAuthorizationDtoTest.java | Java | apache-2.0 | 1,545 |
package th.ac.kmitl.ce.ooad.cest.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import th.ac.kmitl.ce.ooad.cest.domain.Course;
import th.ac.kmitl.ce.ooad.cest.domain.Faculty;
import java.util.List;
public interface CourseRepository extends CrudRepository<Course, Long>{
Course findFirstByCourseId(String courseId);
Course findFirstByCourseName(String courseName);
List<Course> findByCourseNameContainingOrCourseIdContainingOrderByCourseNameAsc(String courseName, String courseId);
List<Course> findByFacultyOrderByCourseNameAsc(Faculty faculty);
List<Course> findByDepartmentOrderByCourseNameAsc(String department);
@Query("select c from Course c where c.department = ?2 or c.department = '' and c.faculty = ?1 order by c.courseName")
List<Course> findByFacultyAndDepartmentOrNone(Faculty faculty, String department);
}
| CE-KMITL-OOAD-2015/CE-SMART-TRACKER-DEV | CE Smart Tracker Server/src/main/java/th/ac/kmitl/ce/ooad/cest/repository/CourseRepository.java | Java | apache-2.0 | 930 |
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2011 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////
#include "TestInc.h"
#include "LuceneTestFixture.h"
#include "ConcurrentMergeScheduler.h"
#include "DateTools.h"
namespace Lucene
{
LuceneTestFixture::LuceneTestFixture()
{
DateTools::setDateOrder(DateTools::DATEORDER_LOCALE);
ConcurrentMergeScheduler::setTestMode();
}
LuceneTestFixture::~LuceneTestFixture()
{
DateTools::setDateOrder(DateTools::DATEORDER_LOCALE);
if (ConcurrentMergeScheduler::anyUnhandledExceptions())
{
// Clear the failure so that we don't just keep failing subsequent test cases
ConcurrentMergeScheduler::clearUnhandledExceptions();
BOOST_FAIL("ConcurrentMergeScheduler hit unhandled exceptions");
}
}
}
| ustramooner/LucenePlusPlus | src/test/util/LuceneTestFixture.cpp | C++ | apache-2.0 | 1,080 |
macimport os
import subprocess
name = "gobuildmaster"
current_hash = ""
for line in os.popen("md5sum " + name).readlines():
current_hash = line.split(' ')[0]
# Move the old version over
for line in os.popen('cp ' + name + ' old' + name).readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./old' + name)
size_2 = os.path.getsize('./' + name)
lines = os.popen('ps -ef | grep ' + name).readlines()
running = False
for line in lines:
if "./" + name in line:
running = True
new_hash = ""
for line in os.popen("md5sum " + name).readlines():
new_hash = line.split(' ')[0]
if size_1 != size_2 or new_hash != current_hash or not running:
if not running:
for line in os.popen('cat out.txt | mail -E -s "Crash Report ' + name + '" [email protected]').readlines():
pass
for line in os.popen('echo "" > out.txt').readlines():
pass
for line in os.popen('killall ' + name).readlines():
pass
subprocess.Popen(['./' + name])
| brotherlogic/gobuildmaster | BuildAndRun.py | Python | apache-2.0 | 1,102 |
import unittest2
import helper
import simplejson as json
from nose.plugins.attrib import attr
PORTAL_ID = 62515
class ListsClientTest(unittest2.TestCase):
"""
Unit tests for the HubSpot List API Python wrapper (hapipy) client.
This file contains some unittest tests for the List API.
Questions, comments, etc: http://developers.hubspot.com
"""
def setUp(self):
self.client = ListsClient(**helper.get_options())
def tearDown(self):
pass
@attr('api')
def test_get_list(self):
# create a list to get
dummy_data = json.dumps(dict(
name='try_and_get_me',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was created
self.asserTrue(len(created_list['lists']))
# the id number of the list the test is trying to get
id_to_get = created_list['listID']
# try and get it
recieved_lists = self.client.get_list(id_to_get)
# see if the test got the right list
self.assertEqual(recieved_lists['lists'][0]['listId'], created_list['listId'])
print "Got this list: %s" % json.dumps(recieved_list['lists'][0])
# clean up
self.client.delete_list(id_to_get)
@attr('api')
def test_get_batch_lists(self):
# holds the ids of the lists being retrieved
list_ids = []
# make a list to get
dummy_data = json.dumps(dict(
name='first_test_list',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(created_list['listID'])
# put the id of the newly made list in list_ids
list_ids[0] = created_list['listId']
#change the data a little and make another list
dummy_data['name'] = 'second_test_list'
created_list = self.client.create_list(dummy_data)
# make sure itwas actually made
self.assertTrue(created_list['listID'])
# put the id number in list_ids
list_ids[1] = created_list['listId']
# try and get them
batch_lists = self.client.get_batch_lists(list_ids)
# make sure you got as many lists as you were searching for
self.assertEqual(len(list_ids), len(batch_lists['lists']))
# clean up
self.client.delete_list(list_ids[0])
self.client.delete_list(list_ids[1])
@attr('api')
def test_get_lists(self):
# try and get lists
recieved_lists = self.client.get_lists()
# see if the test got at least one
if len(recieved_lists['lists']) == 0:
self.fail("Unable to retrieve any lists")
else:
print "Got these lists %s" % json.dumps(recieved_lists)
@attr('api')
def test_get_static_lists(self):
# create a static list to get
dummy_data = json.dumps(dict(
name='static_test_list',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(created_list['listID'])
# this call will return 20 lists if not given another value
static_lists = self.client.get_static_lists()
if len(static_lists['lists']) == 0:
self.fail("Unable to retrieve any static lists")
else:
print "Found these static lists: %s" % json.dumps(static_lists)
# clean up
self.client.delete_list(created_list['listId'])
@attr('api')
def test_get_dynamic_lists(self):
# make a dynamic list to get
dummy_data = json.dumps(dict(
name='test_dynamic_list',
dynamic=True,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure the dynamic list was made
self.assertTrue(created_list['listId'])
dynamic_lists = self.client.get_dynamic_lists()
if len(dynamic_lists['lists']) == 0:
self.fail("Unable to retrieve any dynamic lists")
else:
print "Found these dynamic lists: %s" % json.dumps(dynamic_lists)
# clean up
self.client.delete_list(created_list['listId'])
@attr('api')
def test_get_list_contacts(self):
# the id number of the list you want the contacts of
# which_list =
# try and get the contacts
contacts = self.client.get_list_contacts(which_list)
# make sure you get at least one
self.assertTrue(len(contacts['contacts'])
print "Got these contacts: %s from this list: %s" % json.dumps(contacts), which_list)
@attr('api')
def test_get_list_contacts_recent(self):
# the id number of the list you want the recent contacts of
which_list =
recent_contacts = self.client.get_list_contacts_recent(which_list)
if len(recent_contacts['lists']) == 0:
self.fail("Did not find any recent contacts")
else:
print "Found these recent contacts: %s" % json.dumps(recent_conacts)
@attr('api')
def test_create_list(self):
# the data for the list the test is making
dummy_data = json.dumps(dict(
list_name='test_list',
dynamic=False,
portalId=PORTAL_ID
))
# try and make the list
created_list = self.client.create_list(dummy_data)
# make sure it was created
if len(created_lists['lists']) == 0:
self.fail("Did not create the list")
else:
print "Created this list: %s" % json.dumps(created_lists)
# clean up
self.client.delete_list(created_lists['lists'][0]['listId'])
@attr('api')
def test_update_list(self):
# make a list to update
dummy_data = json.dumps(dict(
name='delete_me',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(len(created_list['listId']))
# get the id number of the list
update_list_id = created_list['listId']
# this is the data updating the list
update_data = json.dumps(dict(
list_name='really_delete_me',
))
# try and do the update
http_response = self.client.update_list(update_list_id, update_data)
if http_response >= 400:
self.fail("Unable to update list!")
else:
print("Updated a list!")
# clean up
self.client.delete_list(update_list_id)
@attr('api')
def test_add_contacts_to_list_from_emails(self):
# make a list to add contacts to
dummy_data = json.dumps(dict(
name='give_me_contact_emails',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(len(created_list['lists']))
# the id number of the list being added to
which_list = created_list['listId']
# the emails of the contacts being added
emails = json.dumps(dict(
emails
))
# try and add the contacts
self.client.add_contacts_to_list_from_emails(which_list, emails)
@attr('api')
def test_add_contact_to_list(self):
# make a list to add a contact to
dummy_data = json.dumps(dict(
name='add_a_contact',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(created_list['listId'])
# the id number of the list the contact is being added to
which_list = created_list['listId']
# the id number of the contact being added to the list
which_contact =
added = self.client.add_contact_to_list(which_list, which_contact)
if added['updated'] == which_contact:
print "Succesfully added contact: %s to list: %s" % which_contact, which_list
# if it worked, clean up
self.client.delete_list(which_list)
else:
self.fail("Did not add contact: %s to list: %a" % which_contact, which_list)
@attr('api')
def test_remove_contact_from_list(self):
# make a list to remove a contact from
fake_data = json.dumps(dict(
name='remove_this_contact'
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(fake_data)
# make sure it was actually made
self.assertTrue(created_list['listId'])
# the id number of the list the contact is being deleted from
which_list = created_list['listId']
# the id number of the contact being deleted
which_contact =
# put the contact in the list so it can be removed
added = self.client.add_contact_to_list(which_list, which_contact)
# make sure it was added
self.assertTrue(added['updated'])
# try and remove it
removed = self.client.remove_contact_from_list(which_list, which_contact)
# check if it was actually removed
if removed['updated'] == which_contact:
print "Succesfully removed contact: %s from list: %s" % which_contact, which_list
# clean up
self.client.delete_list(created_list['listId'])
else:
self.fail("Did not remove contact %s from list: %s" % which_contact, which_list)
@attr('api')
def test_delete_list(self):
# make a list to delete
dummy_data = json.dumps(dict(
name='should_be_deleted',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# check if it was actually made
self.assertTrue(created_list['listId'])
# the id number of the list being deleted
id_to_delete = created_list['listId']
# try deleting it
self.client.delete_list(id_to_delete)
# try and get the list that should have been deleted
check = self.client.get_list(id_to_delete)
# check should not have any lists
self.assertEqual(len(check['lists']), 0)
print "Sucessfully deleted a test list"
@attr('api')
def test_refresh_list(self):
# make a dynamic list to refresh
dummy_data = json.dumps(dict(
name='refresh_this_list',
dynamic=True,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it actually made the list
self.assertTrue(created_list['listId'])
# do the refresh
refresh_response = self.client.refresh_list(created_list['listId'])
# check if it worked
if refresh_response >= 400:
self.fail("Failed to refresh list: %s" % json.dumps(created_list))
else:
print "Succesfully refreshed list: %s" % json.dumps(created_list)
# clean up
self.client.delete_list(created_list['listId'])
if __name__ == "__main__":
unittest2.main()
| jonathan-s/happy | happy/test/test_lists.py | Python | apache-2.0 | 11,513 |
package org.apache.lucene.facet.sampling;
import java.io.IOException;
import java.util.Collections;
import org.apache.lucene.document.Document;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.index.FacetFields;
import org.apache.lucene.facet.params.FacetIndexingParams;
import org.apache.lucene.facet.params.FacetSearchParams;
import org.apache.lucene.facet.sampling.RandomSampler;
import org.apache.lucene.facet.sampling.Sampler;
import org.apache.lucene.facet.sampling.SamplingAccumulator;
import org.apache.lucene.facet.sampling.SamplingParams;
import org.apache.lucene.facet.search.CountFacetRequest;
import org.apache.lucene.facet.search.FacetRequest;
import org.apache.lucene.facet.search.FacetResult;
import org.apache.lucene.facet.search.FacetResultNode;
import org.apache.lucene.facet.search.FacetsCollector;
import org.apache.lucene.facet.search.StandardFacetsAccumulator;
import org.apache.lucene.facet.search.FacetRequest.ResultMode;
import org.apache.lucene.facet.taxonomy.CategoryPath;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class OversampleWithDepthTest extends FacetTestCase {
@Test
public void testCountWithdepthUsingSampling() throws Exception, IOException {
Directory indexDir = newDirectory();
Directory taxoDir = newDirectory();
FacetIndexingParams fip = new FacetIndexingParams(randomCategoryListParams());
// index 100 docs, each with one category: ["root", docnum/10, docnum]
// e.g. root/8/87
index100Docs(indexDir, taxoDir, fip);
DirectoryReader r = DirectoryReader.open(indexDir);
TaxonomyReader tr = new DirectoryTaxonomyReader(taxoDir);
CountFacetRequest facetRequest = new CountFacetRequest(new CategoryPath("root"), 10);
// Setting the depth to '2', should potentially get all categories
facetRequest.setDepth(2);
facetRequest.setResultMode(ResultMode.PER_NODE_IN_TREE);
FacetSearchParams fsp = new FacetSearchParams(fip, facetRequest);
// Craft sampling params to enforce sampling
final SamplingParams params = new SamplingParams();
params.setMinSampleSize(2);
params.setMaxSampleSize(50);
params.setOversampleFactor(5);
params.setSamplingThreshold(60);
params.setSampleRatio(0.1);
FacetResult res = searchWithFacets(r, tr, fsp, params);
FacetRequest req = res.getFacetRequest();
assertEquals(facetRequest, req);
FacetResultNode rootNode = res.getFacetResultNode();
// Each node below root should also have sub-results as the requested depth was '2'
for (FacetResultNode node : rootNode.subResults) {
assertTrue("node " + node.label + " should have had children as the requested depth was '2'", node.subResults.size() > 0);
}
IOUtils.close(r, tr, indexDir, taxoDir);
}
private void index100Docs(Directory indexDir, Directory taxoDir, FacetIndexingParams fip) throws IOException {
IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, null);
IndexWriter w = new IndexWriter(indexDir, iwc);
TaxonomyWriter tw = new DirectoryTaxonomyWriter(taxoDir);
FacetFields facetFields = new FacetFields(tw, fip);
for (int i = 0; i < 100; i++) {
Document doc = new Document();
CategoryPath cp = new CategoryPath("root",Integer.toString(i / 10), Integer.toString(i));
facetFields.addFields(doc, Collections.singletonList(cp));
w.addDocument(doc);
}
IOUtils.close(tw, w);
}
/** search reader <code>r</code>*/
private FacetResult searchWithFacets(IndexReader r, TaxonomyReader tr, FacetSearchParams fsp,
final SamplingParams params) throws IOException {
// a FacetsCollector with a sampling accumulator
Sampler sampler = new RandomSampler(params, random());
StandardFacetsAccumulator sfa = new SamplingAccumulator(sampler, fsp, r, tr);
FacetsCollector fcWithSampling = FacetsCollector.create(sfa);
IndexSearcher s = new IndexSearcher(r);
s.search(new MatchAllDocsQuery(), fcWithSampling);
// there's only one expected result, return just it.
return fcWithSampling.getFacetResults().get(0);
}
}
| pkarmstr/NYBC | solr-4.2.1/lucene/facet/src/test/org/apache/lucene/facet/sampling/OversampleWithDepthTest.java | Java | apache-2.0 | 5,565 |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from six.moves.urllib import parse as urllib
from tempest_lib import exceptions as lib_exc
from tempest.api_schema.response.compute.v2_1 import images as schema
from tempest.common import service_client
from tempest.common import waiters
class ImagesClientJSON(service_client.ServiceClient):
def create_image(self, server_id, name, meta=None):
"""Creates an image of the original server."""
post_body = {
'createImage': {
'name': name,
}
}
if meta is not None:
post_body['createImage']['metadata'] = meta
post_body = json.dumps(post_body)
resp, body = self.post('servers/%s/action' % str(server_id),
post_body)
self.validate_response(schema.create_image, resp, body)
return service_client.ResponseBody(resp, body)
def list_images(self, params=None):
"""Returns a list of all images filtered by any parameters."""
url = 'images'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(schema.list_images, resp, body)
return service_client.ResponseBodyList(resp, body['images'])
def list_images_with_detail(self, params=None):
"""Returns a detailed list of images filtered by any parameters."""
url = 'images/detail'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(schema.list_images_details, resp, body)
return service_client.ResponseBodyList(resp, body['images'])
def show_image(self, image_id):
"""Returns the details of a single image."""
resp, body = self.get("images/%s" % str(image_id))
self.expected_success(200, resp.status)
body = json.loads(body)
self.validate_response(schema.get_image, resp, body)
return service_client.ResponseBody(resp, body['image'])
def delete_image(self, image_id):
"""Deletes the provided image."""
resp, body = self.delete("images/%s" % str(image_id))
self.validate_response(schema.delete, resp, body)
return service_client.ResponseBody(resp, body)
def wait_for_image_status(self, image_id, status):
"""Waits for an image to reach a given status."""
waiters.wait_for_image_status(self, image_id, status)
def list_image_metadata(self, image_id):
"""Lists all metadata items for an image."""
resp, body = self.get("images/%s/metadata" % str(image_id))
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def set_image_metadata(self, image_id, meta):
"""Sets the metadata for an image."""
post_body = json.dumps({'metadata': meta})
resp, body = self.put('images/%s/metadata' % str(image_id), post_body)
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def update_image_metadata(self, image_id, meta):
"""Updates the metadata for an image."""
post_body = json.dumps({'metadata': meta})
resp, body = self.post('images/%s/metadata' % str(image_id), post_body)
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['metadata'])
def get_image_metadata_item(self, image_id, key):
"""Returns the value for a specific image metadata key."""
resp, body = self.get("images/%s/metadata/%s" % (str(image_id), key))
body = json.loads(body)
self.validate_response(schema.image_meta_item, resp, body)
return service_client.ResponseBody(resp, body['meta'])
def set_image_metadata_item(self, image_id, key, meta):
"""Sets the value for a specific image metadata key."""
post_body = json.dumps({'meta': meta})
resp, body = self.put('images/%s/metadata/%s' % (str(image_id), key),
post_body)
body = json.loads(body)
self.validate_response(schema.image_meta_item, resp, body)
return service_client.ResponseBody(resp, body['meta'])
def delete_image_metadata_item(self, image_id, key):
"""Deletes a single image metadata key/value pair."""
resp, body = self.delete("images/%s/metadata/%s" %
(str(image_id), key))
self.validate_response(schema.delete, resp, body)
return service_client.ResponseBody(resp, body)
def is_resource_deleted(self, id):
try:
self.show_image(id)
except lib_exc.NotFound:
return True
return False
@property
def resource_type(self):
"""Returns the primary type of resource this client works with."""
return 'image'
| yamt/tempest | tempest/services/compute/json/images_client.py | Python | apache-2.0 | 5,741 |
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;//ÇëÏÈÌí¼ÓÒýÓÃ
namespace TSM.DAL
{
/// <summary>
/// Êý¾Ý·ÃÎÊÀàCK_People¡£
/// </summary>
public class CK_People
{
public CK_People()
{}
#region ³ÉÔ±·½·¨
/// <summary>
/// µÃµ½×î´óID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID("CK_PeopleID", "CK_People");
}
/// <summary>
/// ÊÇ·ñ´æÔڸüǼ
/// </summary>
public bool Exists(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from CK_People");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// Ôö¼ÓÒ»ÌõÊý¾Ý
/// </summary>
public int Add(TSM.Model.CK_People model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into CK_People(");
strSql.Append("CK_PeopleName,CK_PhoneNo,CK_Comment)");
strSql.Append(" values (");
strSql.Append("@CK_PeopleName,@CK_PhoneNo,@CK_Comment)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32),
new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32),
new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)};
parameters[0].Value = model.CK_PeopleName;
parameters[1].Value = model.CK_PhoneNo;
parameters[2].Value = model.CK_Comment;
object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
if (obj == null)
{
return 1;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// ¸üÐÂÒ»ÌõÊý¾Ý
/// </summary>
public void Update(TSM.Model.CK_People model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("update CK_People set ");
strSql.Append("CK_PeopleName=@CK_PeopleName,");
strSql.Append("CK_PhoneNo=@CK_PhoneNo,");
strSql.Append("CK_Comment=@CK_Comment");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4),
new SqlParameter("@CK_PeopleName", SqlDbType.VarChar,32),
new SqlParameter("@CK_PhoneNo", SqlDbType.VarChar,32),
new SqlParameter("@CK_Comment", SqlDbType.VarChar,100)};
parameters[0].Value = model.CK_PeopleID;
parameters[1].Value = model.CK_PeopleName;
parameters[2].Value = model.CK_PhoneNo;
parameters[3].Value = model.CK_Comment;
DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
}
/// <summary>
/// ɾ³ýÒ»ÌõÊý¾Ý
/// </summary>
public void Delete(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from CK_People ");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
}
/// <summary>
/// µÃµ½Ò»¸ö¶ÔÏóʵÌå
/// </summary>
public TSM.Model.CK_People GetModel(int CK_PeopleID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select top 1 CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment from CK_People ");
strSql.Append(" where CK_PeopleID=@CK_PeopleID ");
SqlParameter[] parameters = {
new SqlParameter("@CK_PeopleID", SqlDbType.Int,4)};
parameters[0].Value = CK_PeopleID;
TSM.Model.CK_People model=new TSM.Model.CK_People();
DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
if(ds.Tables[0].Rows.Count>0)
{
if(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString()!="")
{
model.CK_PeopleID=int.Parse(ds.Tables[0].Rows[0]["CK_PeopleID"].ToString());
}
model.CK_PeopleName=ds.Tables[0].Rows[0]["CK_PeopleName"].ToString();
model.CK_PhoneNo=ds.Tables[0].Rows[0]["CK_PhoneNo"].ToString();
model.CK_Comment=ds.Tables[0].Rows[0]["CK_Comment"].ToString();
return model;
}
else
{
return null;
}
}
/// <summary>
/// »ñµÃÊý¾ÝÁбí
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment ");
strSql.Append(" FROM CK_People ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// »ñµÃǰ¼¸ÐÐÊý¾Ý
/// </summary>
public DataSet GetList(int Top,string strWhere,string filedOrder)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select ");
if(Top>0)
{
strSql.Append(" top "+Top.ToString());
}
strSql.Append(" CK_PeopleID,CK_PeopleName,CK_PhoneNo,CK_Comment ");
strSql.Append(" FROM CK_People ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
strSql.Append(" order by " + filedOrder);
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// ·ÖÒ³»ñÈ¡Êý¾ÝÁбí
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@tblName", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@IsReCount", SqlDbType.Bit),
new SqlParameter("@OrderType", SqlDbType.Bit),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "CK_People";
parameters[1].Value = "CK_PeopleID";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}
#endregion ³ÉÔ±·½·¨
}
}
| kamiba/FineUIDemo | DAL/CK_People.cs | C# | apache-2.0 | 6,177 |
// Copyright 2016 Benjamin Glatzel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// UI related includes
#include "ui_IntrinsicEdPropertyEditorString.h"
class IntrinsicEdPropertyEditorString : public QWidget
{
Q_OBJECT
public:
IntrinsicEdPropertyEditorString(rapidjson::Document* p_Document,
rapidjson::Value* p_CurrentProperties,
rapidjson::Value* p_CurrentProperty,
const char* p_PropertyName,
QWidget* parent = nullptr);
~IntrinsicEdPropertyEditorString();
public slots:
void onValueChanged();
signals:
void valueChanged(rapidjson::Value& p_Properties);
private:
void updateFromProperty();
Ui::IntrinsicEdPropertyEditorStringClass _ui;
rapidjson::Value* _property;
rapidjson::Value* _properties;
rapidjson::Document* _document;
_INTR_STRING _propertyName;
};
| codedreality/Intrinsic | IntrinsicEd/src/IntrinsicEdPropertyEditorString.h | C | apache-2.0 | 1,451 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.jsprit.core.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.graphhopper.jsprit.core.algorithm.listener.AlgorithmEndsListener;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
public class SolutionVerifier implements AlgorithmEndsListener {
@Override
public void informAlgorithmEnds(VehicleRoutingProblem problem, Collection<VehicleRoutingProblemSolution> solutions) {
for (VehicleRoutingProblemSolution solution : solutions) {
Set<Job> jobsInSolution = new HashSet<Job>();
for (VehicleRoute route : solution.getRoutes()) {
jobsInSolution.addAll(route.getTourActivities().getJobs());
}
if (jobsInSolution.size() != problem.getJobs().size()) {
throw new IllegalStateException("we are at the end of the algorithm and still have not found a valid solution." +
"This cannot be.");
}
}
}
}
| balage1551/jsprit | jsprit-core/src/main/java/com/graphhopper/jsprit/core/util/SolutionVerifier.java | Java | apache-2.0 | 2,020 |
package jp.ac.keio.bio.fun.xitosbml.image;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import ij.ImagePlus;
import ij.ImageStack;
import ij.process.ByteProcessor;
/**
* The class Filler, which provides several morphological operations for filling holes in the image.
* Date Created: Feb 21, 2017
*
* @author Kaito Ii <[email protected]>
* @author Akira Funahashi <[email protected]>
*/
public class Filler {
/** The ImageJ image object. */
private ImagePlus image;
/** The width of an image. */
private int width;
/** The height of an image. */
private int height;
/** The depth of an image. */
private int depth;
/** The width of an image including padding. */
private int lwidth;
/** The height of an image including padding. */
private int lheight;
/** The depth of an image including padding. */
private int ldepth;
/** The mask which stores the label of each pixel. */
private int[] mask;
/**
* The hashmap of pixel value. <labelnumber, pixel value>.
* The domain which has pixel value = 0 will have a label = 1.
*/
private HashMap<Integer, Byte> hashPix = new HashMap<Integer, Byte>(); // label number, pixel value
/** The raw data (1D byte array) of the image. */
private byte[] pixels;
/** The raw data (1D int array) of inverted the image. */
private int[] invert;
/**
* Fill a hole in the given image (ImagePlus object) by morphology operation,
* and returns the filled image.
*
* @param image the ImageJ image object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(ImagePlus image){
this.width = image.getWidth();
this.height = image.getHeight();
this.depth = image.getStackSize();
this.image = image;
pixels = ImgProcessUtil.copyMat(image);
invertMat();
label();
if (checkHole()) {
while (checkHole()) {
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Fill a hole in the given image ({@link SpatialImage} object) by morphology operation,
* and returns the filled image as ImageJ image object.
*
* @param spImg the SpatialImage object
* @return the filled ImageJ image (ImagePlus) object
*/
public ImagePlus fill(SpatialImage spImg){
this.width = spImg.getWidth();
this.height = spImg.getHeight();
this.depth = spImg.getDepth();
this.image = spImg.getImage();
this.pixels = spImg.getRaw();
invertMat();
label();
if(checkHole()){
while(checkHole()){
fillHole();
hashPix.clear();
label();
}
ImageStack stack = createStack();
image.setStack(stack);
image.updateImage();
}
return image;
}
/**
* Creates the stack of images from raw data (1D array) of image (pixels[]),
* and returns the stack of images.
*
* @return the stack of images
*/
private ImageStack createStack(){
ImageStack altimage = new ImageStack(width, height);
for(int d = 0 ; d < depth ; d++){
byte[] matrix = new byte[width * height];
System.arraycopy(pixels, d * height * width, matrix, 0, matrix.length);
altimage.addSlice(new ByteProcessor(width,height,matrix,null));
}
return altimage;
}
/**
* Create an inverted 1D array of an image (invert[]) from 1D array of an image (pixels[]).
* Each pixel value will be inverted (0 -> 1, otherwise -> 0). For example, the Black and White
* binary image will be converted to a White and Black binary image.
*/
private void invertMat(){
lwidth = width + 2;
lheight = height + 2;
if(depth < 3) ldepth = depth;
else ldepth = depth + 2;
invert = new int[lwidth * lheight * ldepth];
mask = new int[lwidth * lheight * ldepth];
if (ldepth > depth) { // 3D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if (d == 0 || d == ldepth - 1 || h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1) {
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[(d - 1) * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 0; h < lheight; h++) {
for (int w = 0; w < lwidth; w++) {
if(h == 0 || h == lheight - 1 || w == 0 || w == lwidth - 1){
invert[d * lheight * lwidth + h * lwidth + w] = 1;
mask[d * lheight * lwidth + h * lwidth + w] = 1;
continue;
}
if (pixels[d * height * width + (h - 1) * width + w - 1] == 0)
invert[d * lheight * lwidth + h * lwidth + w] = 1;
else
invert[d * lheight * lwidth + h * lwidth + w] = 0;
}
}
}
}
}
/** The label count. */
private int labelCount;
/**
* Assign a label (label number) to each pixel.
* The label number will be stored in mask[] array.
* The domain which has pixel value = 0 will have a label = 1.
*/
public void label(){
hashPix.put(1, (byte)0);
labelCount = 2;
if (ldepth > depth) {
for (int d = 1; d < ldepth - 1; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[(d-1) * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[(d-1) * height * width + (h-1) * width + w - 1]);
}
}
}
}
}else{
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (invert[d * lheight * lwidth + h * lwidth + w] == 1 && pixels[d * height * width + (h-1) * width + w - 1] == 0) {
mask[d * lheight * lwidth + h * lwidth + w] = setLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}else{
mask[d * lheight * lwidth + h * lwidth + w] = setbackLabel(w, h, d, pixels[d * height * width + (h-1) * width + w - 1]);
}
}
}
}
}
}
/**
* Check whether a hole exists in the hashmap of pixels (HashMap<label number, pixel value>).
*
* @return true, if a hole exists
*/
public boolean checkHole(){
if(Collections.frequency(hashPix.values(), (byte) 0) > 1)
return true;
else
return false;
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The fill operation will be applied to each domain (which has unique label number).
*/
public void fillHole(){
for(Entry<Integer, Byte> e : hashPix.entrySet()){
if(!e.getKey().equals(1) && e.getValue().equals((byte)0)){
fill(e.getKey());
}
}
}
/**
* Fill a hole in the hashmap of pixels (HashMap<label number, pixel value> by morphology operation.
* The hole will be filled with the pixel value of adjacent pixel.
*
* @param labelNum the label number
*/
public void fill(int labelNum){
if (ldepth > depth) { // 3D image
for (int d = 1; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[(d-1) * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
} else { // 2D image
for (int d = 0; d < ldepth; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == labelNum ) {
pixels[d * height * width + (h-1) * width + w - 1] = checkAdjacentsLabel(w, h, d, labelNum);
}
}
}
}
}
}
/**
* Check adjacent pixels whether it contains the given label (labelNum).
* If all the adjacent pixels have same label with given label, then return 0.
* If the adjacent pixels contain different labels, then returns the pixel
* value of most enclosing adjacent domain.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param labelNum the label number
* @return the pixel value of most enclosing adjacent domain if different domain exists, otherwise 0
*/
public byte checkAdjacentsLabel(int w, int h, int d, int labelNum){
List<Byte> adjVal = new ArrayList<Byte>();
//check right
if(mask[d * lheight * lwidth + h * lwidth + w + 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w + 1]));
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]));
//check down
if(mask[d * lheight * lwidth + (h+1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h+1) * lwidth + w]));
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != labelNum)
adjVal.add(hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]));
//check above
if(d != depth - 1 && mask[(d+1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d+1) * lheight * lwidth + h * lwidth + w]));
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != labelNum)
adjVal.add(hashPix.get(mask[(d - 1) * lheight * lwidth + h * lwidth + w]));
if(adjVal.isEmpty())
return 0;
int max = 0;
int count = 0;
int freq, temp; Byte val = 0;
for(int n = 0 ; n < adjVal.size() ; n++){
val = adjVal.get(n);
if(val == 0)
continue;
freq = Collections.frequency(adjVal, val);
temp = val & 0xFF;
if(freq > count){
max = temp;
count = freq;
}
if(freq == count && max < temp){
max = temp;
count = freq;
}
}
return (byte) max;
}
/**
* Sets the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) == (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) == (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
rewriteLabel(d, min, adjVal.get(i));
hashPix.remove(adjVal.get(i));
}
return min;
}
/**
* Sets back the label of the given pixel (x offset, y offset, z offset) with its pixel value.
* Checks whether the adjacent pixel has the non-zero pixel value, and its label is already assigned.
*
* @param w the x offset
* @param h the y offset
* @param d the z offset
* @param pixVal the pixel value
* @return the label as integer value
*/
private int setbackLabel(int w , int h, int d, byte pixVal){
List<Integer> adjVal = new ArrayList<Integer>();
//check left
if(mask[d * lheight * lwidth + h * lwidth + w - 1] != 0 && hashPix.get(mask[d * lheight * lwidth + h * lwidth + w - 1]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + h * lwidth + w - 1]);
//check up
if(mask[d * lheight * lwidth + (h-1) * lwidth + w ] != 0 && hashPix.get(mask[d * lheight * lwidth + (h-1) * lwidth + w]) != (byte)0)
adjVal.add(mask[d * lheight * lwidth + (h-1) * lwidth + w]);
//check below
if(d != 0 && mask[(d-1) * lheight * lwidth + h * lwidth + w] != 0 && hashPix.get(mask[(d-1) * lheight * lwidth + h * lwidth + w]) != (byte)0)
adjVal.add(mask[(d-1) * lheight * lwidth + h * lwidth + w]);
if(adjVal.isEmpty()){
hashPix.put(labelCount, pixVal);
return labelCount++;
}
Collections.sort(adjVal);
//if all element are same or list has only one element
if(Collections.frequency(adjVal, adjVal.get(0)) == adjVal.size())
return adjVal.get(0);
int min = adjVal.get(0);
for(int i = 1; i < adjVal.size(); i++){
if(min == adjVal.get(i))
continue;
hashPix.remove(adjVal.get(i));
rewriteLabel(d, min, adjVal.get(i));
}
return min;
}
/**
* Replace the label of pixels in the spatial image which has "before" to "after".
*
* @param dEnd the end of the depth
* @param after the label to set by this replacement
* @param before the label to be replaced
*/
private void rewriteLabel(int dEnd, int after, int before){
if (ldepth > depth) {
for (int d = 1; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}else{
for (int d = 0; d <= dEnd; d++) {
for (int h = 1; h < lheight - 1; h++) {
for (int w = 1; w < lwidth - 1; w++) {
if (mask[d * lheight * lwidth + h * lwidth + w] == before)
mask[d * lheight * lwidth + h * lwidth + w] = after;
}
}
}
}
}
}
| spatialsimulator/XitoSBML | src/main/java/jp/ac/keio/bio/fun/xitosbml/image/Filler.java | Java | apache-2.0 | 14,320 |
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import com.adaptris.annotation.Removal;
import com.adaptris.core.stubs.UpgradedToJunit4;
import com.adaptris.interlok.junit.scaffolding.ExampleConfigGenerator;
@Deprecated
@Removal(version = "4.0.0",
message = "moved to com.adaptris.interlok.junit.scaffolding")
public abstract class ExampleConfigCase extends ExampleConfigGenerator implements UpgradedToJunit4 {
}
| adaptris/interlok | interlok-core/src/test/java/com/adaptris/core/ExampleConfigCase.java | Java | apache-2.0 | 997 |
/*! \file Texture.h
* \author Jared Hoberock
* \brief Defines the interface to a class abstracting
* textures for shading.
*/
#pragma once
#include <array2/Array2.h>
#include "../include/detail/Spectrum.h"
class Texture
: protected Array2<Spectrum>
{
public:
/*! Null constructor creates a 1x1 white Texture.
*/
Texture(void);
/*! Constructor calls the Parent.
* \param w The width of the Texture.
* \param h The height of the Texture.
* \param pixels The pixel data to copy into this Texture.
*/
Texture(const size_t w, const size_t h, const Spectrum *pixels);
/*! Constructor takes a filename referring to
* an image file on disk.
* \param filename The name of the image file of interest.
*/
Texture(const char *filename);
/*! This method provides const access to pixels.
* \param x The column index of the pixel of interest.
* \param y The row index of the pixel of interest.
* \return A const reference to pixel (x,y).
*/
virtual const Spectrum &texRect(const size_t x,
const size_t y) const;
/*! This method provides nearest-neighbor filtering
* given pixel coordinates in [0,1]^2.
* \param u The u-coordinate of the pixel location of interest.
* \param v The v-coordinate of the pixel location of interest.
* \return The box-filtered pixel at (u,v).
*/
virtual const Spectrum &tex2D(const float u,
const float v) const;
/*! This method loads this Texture's data from an
* image file on disk.
* \param filename
* \param filename The name of the image file of interest.
*/
virtual void load(const char *filename);
protected:
/*! \typedef Parent
* \brief Shorthand.
*/
typedef Array2<Spectrum> Parent;
}; // end Texture
| jaredhoberock/gotham | shading/Texture.h | C | apache-2.0 | 1,911 |
package org.ak.gitanalyzer.http.processor;
import org.ak.gitanalyzer.util.writer.CSVWriter;
import org.ak.gitanalyzer.util.writer.HTMLWriter;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* Created by Andrew on 02.12.2016.
*/
public class ProcessorMock extends BaseAnalysisProcessor {
public ProcessorMock(NumberFormat nf) {
super(nf);
}
@Override
public <T> String getCSVForReport(String[] headers, Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getCSVForReport(headers, collection, consumer);
}
@Override
public <T> String getJSONForTable(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONForTable(collection, consumer);
}
@Override
public <T> String getJSONFor2D(Collection<T> collection, BiConsumer<T, StringBuilder> consumer) {
return super.getJSONFor2D(collection, consumer);
}
@Override
public <T> String getJSONForGraph(Collection<T> collection, Function<T, Integer> nodeIdSupplier, TriConsumer<T, StringBuilder, Integer> consumer) {
return super.getJSONForGraph(collection, nodeIdSupplier, consumer);
}
@Override
public String getTypeString(double weight, double thickThreshold, double normalThreshold) {
return super.getTypeString(weight, thickThreshold, normalThreshold);
}
public HTMLWriter getHtmlWriter() {
return htmlWriter;
}
public CSVWriter getCsvWriter() {
return csvWriter;
}
}
| AndreyKunin/git-analyzer | src/test/java/org/ak/gitanalyzer/http/processor/ProcessorMock.java | Java | apache-2.0 | 1,622 |
# require './lib/class_extensions'
# require './lib/mylogger'
# DEV Only requries above.
require './lib/code_detector'
require './lib/dsl/style_dsl'
require './lib/dsl/selector_dsl'
require './lib/tag_helper'
require './lib/html/html_class_finder'
require './lib/html/style_list'
require './lib/highlighter/highlighters_enum'
require './lib/theme_store'
# Do bunch of apply, then invoke end_apply to close the style tag
class StyleGenerator
include HtmlClassFinder, HighlightersEnum, CodeDetector
def initialize(tag_helper, lang = 'none')
@tag_helper = tag_helper
# $logger.info(lang)
# # theming.
# @colorizer = if lang == 'git' || iscmd
# DarkColorizer.new
# elsif ['asp', 'csharp'].include?(lang)
# VisualStudioColorizer.new
# else
# LightColorizer.new
# end
# $logger.debug(@colorizer)
@lang = lang
end
def style_front(front_card_block)
front_style = style {}
front_style.styles << build_main
no_tag = @tag_helper.untagged? || @tag_helper.back_only?
front_style.styles << build_tag unless no_tag
tags = find(front_card_block, :span)
build_code(tags) { |style| front_style.styles << style }
front_style.styles << build_inline if inline?(front_card_block)
front_style
end
def style_back(back_card_block)
back_style = style(get_theme) {}
back_style.styles << build_main
no_tag = @tag_helper.untagged? || @tag_helper.front_only?
back_style.styles << build_tag unless no_tag
back_style.styles << build_figure if @tag_helper.figure?
back_style.styles << build_command if command?(back_card_block)
back_style.styles << build_well if well?(back_card_block)
back_style.styles << build_inline if inline?(back_card_block)
tags = find(back_card_block, :span)
build_code(tags) { |style| back_style.styles << style }
back_style
end
def get_theme
case @lang
when HighlightersEnum::RUBY
ThemeStore::SublimeText2_Sunburst_Ruby
else
ThemeStore::Default
end
end
def build_main
select 'div.main' do
font_size '16pt'
text_align 'left'
end
end
def build_tag
select 'span.tag' do
background_color '#5BC0DE'
border_radius '5px'
color 'white'
font_size '14pt'
padding '2px'
margin_right '10px'
end
end
def build_answer_only
select 'span.answer' do
background_color '#D9534F'
border_radius '5px'
color 'white'
display 'table'
font_weight 'bold'
margin '0 auto'
padding '2px 5px'
end
end
def build_figure
select '.fig', :line_height, '70%'
end
def build_inline
select 'code.inline' do
background_color '#F1F1F1'
border '1px solid #DDD'
border_radius '5px'
color 'black'
font_family 'monaco, courier'
font_size '13pt'
padding_left '2px'
padding_right '2px'
end
end
def build_command
select 'code.command' do
color 'white'
background_color 'black'
end
end
def build_well
select 'code.well' do
background_color '#F1F1F1'
border '1px solid #E3E3E3'
border_radius '4px'
box_shadow 'inset 0 1px 1px rgba(0, 0, 0, 0.05)'
color 'black'
display 'block'
font_family 'monaco, courier'
font_size '14pt'
margin_bottom '20px'
min_height '20px'
padding '19px'
end
end
def build_code(tags)
style_list = StyleList.new(tags)
style_list.add('keyword', :color, '#7E0854')
style_list.add('comment', :color, '#417E60')
style_list.add('quote', :color, '#1324BF')
style_list.add('var', :color, '#426F9C')
style_list.add('url', :color, 'blue')
style_list.add('html', :color, '#446FBD')
style_list.add('attr', :color, '#6D8600')
style_list.add('cls', :color, '#6D8600')
style_list.add('num', :color, '#812050')
style_list.add('opt', :color, 'darkgray')
# style_list.add('cmd', :color, '#7E0854')
# Per language Styles
style_list.add('phptag', :color, '#FC0D1B') if @lang == PHP
style_list.add('ann', :color, '#FC0D1B') if @lang == JAVA
style_list.add('symbol', :color, '#808080') if @lang == ASP
if @lang == GIT
style_list.add('opt', :color, 'black')
style_list.add('cmd', :color, '#FFFF9B')
end
style_list.each { |style| yield style }
end
end
# # tag_helper = TagHelper.new(tags: [])
# # tag_helper = TagHelper.new(tags: [:Concept])
# tag_helper = TagHelper.new(tags: [:FB])
# # tag_helper = TagHelper.new(tags: [:BF])
# generator = StyleGenerator.new(tag_helper)
# puts( generator.style_back(['span class="keyword comment"']) )
| roycetech/Anki-Tools | anki_card_maker/lib/html/style_generator.rb | Ruby | apache-2.0 | 4,672 |
# Tristachya bequaertii var. vanderystii VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Tristachya/Tristachya nodiglumis/ Syn. Tristachya bequaertii vanderystii/README.md | Markdown | apache-2.0 | 195 |
"""A client for the REST API of imeji instances."""
import logging
from collections import OrderedDict
import requests
from six import string_types
from pyimeji import resource
from pyimeji.config import Config
log = logging.getLogger(__name__)
class ImejiError(Exception):
def __init__(self, message, error):
super(ImejiError, self).__init__(message)
self.error = error.get('error') if isinstance(error, dict) else error
class GET(object):
"""Handle GET requests.
This includes requests
- to retrieve single objects,
- to fetch lists of object references (which are returned as `OrderedDict` mapping
object `id` to additional metadata present in the response).
"""
def __init__(self, api, name):
"""Initialize a handler.
:param api: An Imeji API instance.
:param name: Name specifying the kind of object(s) to retrieve. We check whether\
this name has a plural "s" to determine if a list is to be retrieved.
"""
self._list = name.endswith('s')
self.rsc = getattr(resource, (name[:-1] if self._list else name).capitalize())
self.api = api
self.name = name
self.path = name
if not self._list:
self.path += 's'
def __call__(self, id='', **kw):
"""Calling the handler initiates an HTTP request to the imeji server.
:param id: If a single object is to be retrieved it must be specified by id.
:return: An OrderedDict mapping id to additional metadata for lists, a \
:py:class:`pyimeji.resource.Resource` instance for single objects.
"""
if not self._list and not id:
raise ValueError('no id given')
if id:
id = '/' + id
res = self.api._req('/%s%s' % (self.path, id), params=kw)
if not self._list:
return self.rsc(res, self.api)
return OrderedDict([(d['id'], d) for d in res])
class Imeji(object):
"""The client.
>>> api = Imeji(service_url='http://demo.imeji.org/imeji/')
>>> collection_id = list(api.collections().keys())[0]
>>> collection = api.collection(collection_id)
>>> collection = api.create('collection', title='the new collection')
>>> item = collection.add_item(fetchUrl='http://example.org')
>>> item.delete()
"""
def __init__(self, cfg=None, service_url=None):
self.cfg = cfg or Config()
self.service_url = service_url or self.cfg.get('service', 'url')
user = self.cfg.get('service', 'user', default=None)
password = self.cfg.get('service', 'password', default=None)
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
def _req(self, path, method='get', json=True, assert_status=200, **kw):
"""Make a request to the API of an imeji instance.
:param path: HTTP path.
:param method: HTTP method.
:param json: Flag signalling whether the response should be treated as JSON.
:param assert_status: Expected HTTP response status of a successful request.
:param kw: Additional keyword parameters will be handed through to the \
appropriate function of the requests library.
:return: The return value of the function of the requests library or a decoded \
JSON object/array.
"""
method = getattr(self.session, method.lower())
res = method(self.service_url + '/rest' + path, **kw)
status_code = res.status_code
if json:
try:
res = res.json()
except ValueError: # pragma: no cover
log.error(res.text[:1000])
raise
if assert_status:
if status_code != assert_status:
log.error(
'got HTTP %s, expected HTTP %s' % (status_code, assert_status))
log.error(res.text[:1000] if hasattr(res, 'text') else res)
raise ImejiError('Unexpected HTTP status code', res)
return res
def __getattr__(self, name):
"""Names of resource classes are accepted and resolved as dynamic attribute names.
This allows convenient retrieval of resources as api.<resource-class>(id=<id>),
or api.<resource-class>s(q='x').
"""
return GET(self, name)
def create(self, rsc, **kw):
if isinstance(rsc, string_types):
cls = getattr(resource, rsc.capitalize())
rsc = cls(kw, self)
return rsc.save()
def delete(self, rsc):
return rsc.delete()
def update(self, rsc, **kw):
for k, v in kw.items():
setattr(rsc, k, v)
return rsc.save()
| xrotwang/pyimeji | pyimeji/api.py | Python | apache-2.0 | 4,739 |
//
// $Id: RawFileTypes.h 10422 2017-02-02 19:51:54Z chambm $
//
//
// Original author: Darren Kessner <[email protected]>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
// Cedars-Sinai Medical Center, Los Angeles, California 90048
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef _RAWFILETYPES_H_
#define _RAWFILETYPES_H_
#include "pwiz/utility/misc/Export.hpp"
#include <string>
#include <vector>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace bal = boost::algorithm;
namespace pwiz {
namespace vendor_api {
namespace Thermo {
enum PWIZ_API_DECL InstrumentModelType
{
InstrumentModelType_Unknown = -1,
// Finnigan MAT
InstrumentModelType_MAT253,
InstrumentModelType_MAT900XP,
InstrumentModelType_MAT900XP_Trap,
InstrumentModelType_MAT95XP,
InstrumentModelType_MAT95XP_Trap,
InstrumentModelType_SSQ_7000,
InstrumentModelType_TSQ_7000,
InstrumentModelType_TSQ,
// Thermo Electron
InstrumentModelType_Element_2,
// Thermo Finnigan
InstrumentModelType_Delta_Plus_Advantage,
InstrumentModelType_Delta_Plus_XP,
InstrumentModelType_LCQ_Advantage,
InstrumentModelType_LCQ_Classic,
InstrumentModelType_LCQ_Deca,
InstrumentModelType_LCQ_Deca_XP_Plus,
InstrumentModelType_Neptune,
InstrumentModelType_DSQ,
InstrumentModelType_PolarisQ,
InstrumentModelType_Surveyor_MSQ,
InstrumentModelType_Tempus_TOF,
InstrumentModelType_Trace_DSQ,
InstrumentModelType_Triton,
// Thermo Scientific
InstrumentModelType_LTQ,
InstrumentModelType_LTQ_Velos,
InstrumentModelType_LTQ_Velos_Plus,
InstrumentModelType_LTQ_FT,
InstrumentModelType_LTQ_FT_Ultra,
InstrumentModelType_LTQ_Orbitrap,
InstrumentModelType_LTQ_Orbitrap_Discovery,
InstrumentModelType_LTQ_Orbitrap_XL,
InstrumentModelType_LTQ_Orbitrap_Velos,
InstrumentModelType_LTQ_Orbitrap_Elite,
InstrumentModelType_LXQ,
InstrumentModelType_LCQ_Fleet,
InstrumentModelType_ITQ_700,
InstrumentModelType_ITQ_900,
InstrumentModelType_ITQ_1100,
InstrumentModelType_GC_Quantum,
InstrumentModelType_LTQ_XL_ETD,
InstrumentModelType_LTQ_Orbitrap_XL_ETD,
InstrumentModelType_DFS,
InstrumentModelType_DSQ_II,
InstrumentModelType_ISQ,
InstrumentModelType_MALDI_LTQ_XL,
InstrumentModelType_MALDI_LTQ_Orbitrap,
InstrumentModelType_TSQ_Quantum,
InstrumentModelType_TSQ_Quantum_Access,
InstrumentModelType_TSQ_Quantum_Ultra,
InstrumentModelType_TSQ_Quantum_Ultra_AM,
InstrumentModelType_TSQ_Vantage_Standard,
InstrumentModelType_TSQ_Vantage_EMR,
InstrumentModelType_Element_XR,
InstrumentModelType_Element_GD,
InstrumentModelType_GC_IsoLink,
InstrumentModelType_Exactive,
InstrumentModelType_Q_Exactive,
InstrumentModelType_Surveyor_PDA,
InstrumentModelType_Accela_PDA,
InstrumentModelType_Orbitrap_Fusion,
InstrumentModelType_Orbitrap_Fusion_ETD,
InstrumentModelType_TSQ_Quantiva,
InstrumentModelType_TSQ_Endura,
InstrumentModelType_Count,
};
inline InstrumentModelType parseInstrumentModelType(const std::string& instrumentModel)
{
std::string type = bal::to_upper_copy(instrumentModel);
if (type == "MAT253") return InstrumentModelType_MAT253;
else if (type == "MAT900XP") return InstrumentModelType_MAT900XP;
else if (type == "MAT900XP Trap") return InstrumentModelType_MAT900XP_Trap;
else if (type == "MAT95XP") return InstrumentModelType_MAT95XP;
else if (type == "MAT95XP Trap") return InstrumentModelType_MAT95XP_Trap;
else if (type == "SSQ 7000") return InstrumentModelType_SSQ_7000;
else if (type == "TSQ 7000") return InstrumentModelType_TSQ_7000;
else if (type == "TSQ") return InstrumentModelType_TSQ;
else if (type == "ELEMENT2" ||
type == "ELEMENT 2") return InstrumentModelType_Element_2;
else if (type == "DELTA PLUSADVANTAGE") return InstrumentModelType_Delta_Plus_Advantage;
else if (type == "DELTAPLUSXP") return InstrumentModelType_Delta_Plus_XP;
else if (type == "LCQ ADVANTAGE") return InstrumentModelType_LCQ_Advantage;
else if (type == "LCQ CLASSIC") return InstrumentModelType_LCQ_Classic;
else if (type == "LCQ DECA") return InstrumentModelType_LCQ_Deca;
else if (type == "LCQ DECA XP" ||
type == "LCQ DECA XP PLUS") return InstrumentModelType_LCQ_Deca_XP_Plus;
else if (type == "NEPTUNE") return InstrumentModelType_Neptune;
else if (type == "DSQ") return InstrumentModelType_DSQ;
else if (type == "POLARISQ") return InstrumentModelType_PolarisQ;
else if (type == "SURVEYOR MSQ") return InstrumentModelType_Surveyor_MSQ;
else if (type == "TEMPUS TOF") return InstrumentModelType_Tempus_TOF;
else if (type == "TRACE DSQ") return InstrumentModelType_Trace_DSQ;
else if (type == "TRITON") return InstrumentModelType_Triton;
else if (type == "LTQ" || type == "LTQ XL") return InstrumentModelType_LTQ;
else if (type == "LTQ FT" || type == "LTQ-FT") return InstrumentModelType_LTQ_FT;
else if (type == "LTQ FT ULTRA") return InstrumentModelType_LTQ_FT_Ultra;
else if (type == "LTQ ORBITRAP") return InstrumentModelType_LTQ_Orbitrap;
else if (type == "LTQ ORBITRAP DISCOVERY") return InstrumentModelType_LTQ_Orbitrap_Discovery;
else if (type == "LTQ ORBITRAP XL") return InstrumentModelType_LTQ_Orbitrap_XL;
else if (bal::contains(type, "ORBITRAP VELOS")) return InstrumentModelType_LTQ_Orbitrap_Velos;
else if (bal::contains(type, "ORBITRAP ELITE")) return InstrumentModelType_LTQ_Orbitrap_Elite;
else if (bal::contains(type, "VELOS PLUS")) return InstrumentModelType_LTQ_Velos_Plus;
else if (bal::contains(type, "VELOS PRO")) return InstrumentModelType_LTQ_Velos_Plus;
else if (type == "LTQ VELOS") return InstrumentModelType_LTQ_Velos;
else if (type == "LXQ") return InstrumentModelType_LXQ;
else if (type == "LCQ FLEET") return InstrumentModelType_LCQ_Fleet;
else if (type == "ITQ 700") return InstrumentModelType_ITQ_700;
else if (type == "ITQ 900") return InstrumentModelType_ITQ_900;
else if (type == "ITQ 1100") return InstrumentModelType_ITQ_1100;
else if (type == "GC QUANTUM") return InstrumentModelType_GC_Quantum;
else if (type == "LTQ XL ETD") return InstrumentModelType_LTQ_XL_ETD;
else if (type == "LTQ ORBITRAP XL ETD") return InstrumentModelType_LTQ_Orbitrap_XL_ETD;
else if (type == "DFS") return InstrumentModelType_DFS;
else if (type == "DSQ II") return InstrumentModelType_DSQ_II;
else if (type == "ISQ") return InstrumentModelType_ISQ;
else if (type == "MALDI LTQ XL") return InstrumentModelType_MALDI_LTQ_XL;
else if (type == "MALDI LTQ ORBITRAP") return InstrumentModelType_MALDI_LTQ_Orbitrap;
else if (type == "TSQ QUANTUM") return InstrumentModelType_TSQ_Quantum;
else if (bal::contains(type, "TSQ QUANTUM ACCESS")) return InstrumentModelType_TSQ_Quantum_Access;
else if (type == "TSQ QUANTUM ULTRA") return InstrumentModelType_TSQ_Quantum_Ultra;
else if (type == "TSQ QUANTUM ULTRA AM") return InstrumentModelType_TSQ_Quantum_Ultra_AM;
else if (type == "TSQ VANTAGE STANDARD") return InstrumentModelType_TSQ_Vantage_Standard;
else if (type == "TSQ VANTAGE EMR") return InstrumentModelType_TSQ_Vantage_EMR;
else if (type == "TSQ QUANTIVA") return InstrumentModelType_TSQ_Quantiva;
else if (type == "TSQ ENDURA") return InstrumentModelType_TSQ_Endura;
else if (type == "ELEMENT XR") return InstrumentModelType_Element_XR;
else if (type == "ELEMENT GD") return InstrumentModelType_Element_GD;
else if (type == "GC ISOLINK") return InstrumentModelType_GC_IsoLink;
else if (bal::contains(type, "Q EXACTIVE")) return InstrumentModelType_Q_Exactive;
else if (bal::contains(type, "EXACTIVE")) return InstrumentModelType_Exactive;
else if (bal::contains(type, "FUSION")) return bal::contains(type, "ETD") ? InstrumentModelType_Orbitrap_Fusion_ETD : InstrumentModelType_Orbitrap_Fusion;
else if (type == "SURVEYOR PDA") return InstrumentModelType_Surveyor_PDA;
else if (type == "ACCELA PDA") return InstrumentModelType_Accela_PDA;
else
return InstrumentModelType_Unknown;
}
enum PWIZ_API_DECL IonizationType
{
IonizationType_Unknown = -1,
IonizationType_EI = 0, // Electron Ionization
IonizationType_CI, // Chemical Ionization
IonizationType_FAB, // Fast Atom Bombardment
IonizationType_ESI, // Electrospray Ionization
IonizationType_NSI, // Nanospray Ionization
IonizationType_APCI, // Atmospheric Pressure Chemical Ionization
IonizationType_TSP, // Thermospray
IonizationType_FD, // Field Desorption
IonizationType_MALDI, // Matrix-assisted Laser Desorption Ionization
IonizationType_GD, // Glow Discharge
IonizationType_Count
};
inline std::vector<IonizationType> getIonSourcesForInstrumentModel(InstrumentModelType type)
{
std::vector<IonizationType> ionSources;
switch (type)
{
case InstrumentModelType_SSQ_7000:
case InstrumentModelType_TSQ_7000:
case InstrumentModelType_Surveyor_MSQ:
case InstrumentModelType_LCQ_Advantage:
case InstrumentModelType_LCQ_Classic:
case InstrumentModelType_LCQ_Deca:
case InstrumentModelType_LCQ_Deca_XP_Plus:
case InstrumentModelType_LCQ_Fleet:
case InstrumentModelType_LXQ:
case InstrumentModelType_LTQ:
case InstrumentModelType_LTQ_XL_ETD:
case InstrumentModelType_LTQ_Velos:
case InstrumentModelType_LTQ_Velos_Plus:
case InstrumentModelType_LTQ_FT:
case InstrumentModelType_LTQ_FT_Ultra:
case InstrumentModelType_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Discovery:
case InstrumentModelType_LTQ_Orbitrap_XL:
case InstrumentModelType_LTQ_Orbitrap_XL_ETD:
case InstrumentModelType_LTQ_Orbitrap_Velos:
case InstrumentModelType_LTQ_Orbitrap_Elite:
case InstrumentModelType_Exactive:
case InstrumentModelType_Q_Exactive:
case InstrumentModelType_Orbitrap_Fusion:
case InstrumentModelType_Orbitrap_Fusion_ETD:
case InstrumentModelType_TSQ:
case InstrumentModelType_TSQ_Quantum:
case InstrumentModelType_TSQ_Quantum_Access:
case InstrumentModelType_TSQ_Quantum_Ultra:
case InstrumentModelType_TSQ_Quantum_Ultra_AM:
case InstrumentModelType_TSQ_Vantage_Standard:
case InstrumentModelType_TSQ_Vantage_EMR:
case InstrumentModelType_TSQ_Quantiva:
case InstrumentModelType_TSQ_Endura:
ionSources.push_back(IonizationType_ESI);
break;
case InstrumentModelType_DSQ:
case InstrumentModelType_PolarisQ:
case InstrumentModelType_ITQ_700:
case InstrumentModelType_ITQ_900:
case InstrumentModelType_ITQ_1100:
case InstrumentModelType_Trace_DSQ:
case InstrumentModelType_GC_Quantum:
case InstrumentModelType_DFS:
case InstrumentModelType_DSQ_II:
case InstrumentModelType_ISQ:
case InstrumentModelType_GC_IsoLink:
ionSources.push_back(IonizationType_EI);
break;
case InstrumentModelType_MALDI_LTQ_XL:
case InstrumentModelType_MALDI_LTQ_Orbitrap:
ionSources.push_back(IonizationType_MALDI);
break;
case InstrumentModelType_Element_GD:
ionSources.push_back(IonizationType_GD);
break;
case InstrumentModelType_Element_XR:
case InstrumentModelType_Element_2:
case InstrumentModelType_Delta_Plus_Advantage:
case InstrumentModelType_Delta_Plus_XP:
case InstrumentModelType_Neptune:
case InstrumentModelType_Tempus_TOF:
case InstrumentModelType_Triton:
case InstrumentModelType_MAT253:
case InstrumentModelType_MAT900XP:
case InstrumentModelType_MAT900XP_Trap:
case InstrumentModelType_MAT95XP:
case InstrumentModelType_MAT95XP_Trap:
// TODO: get source information for these instruments
break;
case InstrumentModelType_Surveyor_PDA:
case InstrumentModelType_Accela_PDA:
case InstrumentModelType_Unknown:
default:
break;
}
return ionSources;
}
enum PWIZ_API_DECL ScanFilterMassAnalyzerType
{
ScanFilterMassAnalyzerType_Unknown = -1,
ScanFilterMassAnalyzerType_ITMS = 0, // Ion Trap
ScanFilterMassAnalyzerType_TQMS = 1, // Triple Quadrupole
ScanFilterMassAnalyzerType_SQMS = 2, // Single Quadrupole
ScanFilterMassAnalyzerType_TOFMS = 3, // Time of Flight
ScanFilterMassAnalyzerType_FTMS = 4, // Fourier Transform
ScanFilterMassAnalyzerType_Sector = 5, // Magnetic Sector
ScanFilterMassAnalyzerType_Count = 6
};
enum PWIZ_API_DECL MassAnalyzerType
{
MassAnalyzerType_Unknown = -1,
MassAnalyzerType_Linear_Ion_Trap,
MassAnalyzerType_Quadrupole_Ion_Trap,
MassAnalyzerType_Single_Quadrupole,
MassAnalyzerType_Triple_Quadrupole,
MassAnalyzerType_TOF,
MassAnalyzerType_Orbitrap,
MassAnalyzerType_FTICR,
MassAnalyzerType_Magnetic_Sector,
MassAnalyzerType_Count
};
inline MassAnalyzerType convertScanFilterMassAnalyzer(ScanFilterMassAnalyzerType scanFilterType,
InstrumentModelType instrumentModel)
{
switch (instrumentModel)
{
case InstrumentModelType_Exactive:
case InstrumentModelType_Q_Exactive:
return MassAnalyzerType_Orbitrap;
case InstrumentModelType_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Discovery:
case InstrumentModelType_LTQ_Orbitrap_XL:
case InstrumentModelType_LTQ_Orbitrap_XL_ETD:
case InstrumentModelType_MALDI_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Velos:
case InstrumentModelType_LTQ_Orbitrap_Elite:
case InstrumentModelType_Orbitrap_Fusion:
case InstrumentModelType_Orbitrap_Fusion_ETD:
{
switch (scanFilterType)
{
case ScanFilterMassAnalyzerType_FTMS: return MassAnalyzerType_Orbitrap;
//case ScanFilterMassAnalyzerType_SQMS: return MassAnalyzerType_Single_Quadrupole; FIXME: is this possible on the Fusion?
default:
case ScanFilterMassAnalyzerType_ITMS:
return MassAnalyzerType_Linear_Ion_Trap;
}
}
case InstrumentModelType_LTQ_FT:
case InstrumentModelType_LTQ_FT_Ultra:
if (scanFilterType == ScanFilterMassAnalyzerType_FTMS)
return MassAnalyzerType_FTICR;
else
return MassAnalyzerType_Linear_Ion_Trap;
case InstrumentModelType_SSQ_7000:
case InstrumentModelType_Surveyor_MSQ:
case InstrumentModelType_DSQ:
case InstrumentModelType_DSQ_II:
case InstrumentModelType_ISQ:
case InstrumentModelType_Trace_DSQ:
case InstrumentModelType_GC_IsoLink:
return MassAnalyzerType_Single_Quadrupole;
case InstrumentModelType_TSQ_7000:
case InstrumentModelType_TSQ:
case InstrumentModelType_TSQ_Quantum:
case InstrumentModelType_TSQ_Quantum_Access:
case InstrumentModelType_TSQ_Quantum_Ultra:
case InstrumentModelType_TSQ_Quantum_Ultra_AM:
case InstrumentModelType_TSQ_Vantage_Standard:
case InstrumentModelType_TSQ_Vantage_EMR:
case InstrumentModelType_GC_Quantum:
case InstrumentModelType_TSQ_Quantiva:
case InstrumentModelType_TSQ_Endura:
return MassAnalyzerType_Triple_Quadrupole;
case InstrumentModelType_LCQ_Advantage:
case InstrumentModelType_LCQ_Classic:
case InstrumentModelType_LCQ_Deca:
case InstrumentModelType_LCQ_Deca_XP_Plus:
case InstrumentModelType_LCQ_Fleet:
case InstrumentModelType_PolarisQ:
case InstrumentModelType_ITQ_700:
case InstrumentModelType_ITQ_900:
return MassAnalyzerType_Quadrupole_Ion_Trap;
case InstrumentModelType_LTQ:
case InstrumentModelType_LXQ:
case InstrumentModelType_LTQ_XL_ETD:
case InstrumentModelType_ITQ_1100:
case InstrumentModelType_MALDI_LTQ_XL:
case InstrumentModelType_LTQ_Velos:
case InstrumentModelType_LTQ_Velos_Plus:
return MassAnalyzerType_Linear_Ion_Trap;
case InstrumentModelType_DFS:
case InstrumentModelType_MAT253:
case InstrumentModelType_MAT900XP:
case InstrumentModelType_MAT900XP_Trap:
case InstrumentModelType_MAT95XP:
case InstrumentModelType_MAT95XP_Trap:
return MassAnalyzerType_Magnetic_Sector;
case InstrumentModelType_Tempus_TOF:
return MassAnalyzerType_TOF;
case InstrumentModelType_Element_XR:
case InstrumentModelType_Element_2:
case InstrumentModelType_Element_GD:
case InstrumentModelType_Delta_Plus_Advantage:
case InstrumentModelType_Delta_Plus_XP:
case InstrumentModelType_Neptune:
case InstrumentModelType_Triton:
// TODO: get mass analyzer information for these instruments
return MassAnalyzerType_Unknown;
case InstrumentModelType_Surveyor_PDA:
case InstrumentModelType_Accela_PDA:
case InstrumentModelType_Unknown:
default:
return MassAnalyzerType_Unknown;
}
}
inline std::vector<MassAnalyzerType> getMassAnalyzersForInstrumentModel(InstrumentModelType type)
{
std::vector<MassAnalyzerType> massAnalyzers;
switch (type)
{
case InstrumentModelType_Exactive:
case InstrumentModelType_Q_Exactive:
massAnalyzers.push_back(MassAnalyzerType_Orbitrap);
break;
case InstrumentModelType_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Discovery:
case InstrumentModelType_LTQ_Orbitrap_XL:
case InstrumentModelType_MALDI_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Velos:
case InstrumentModelType_LTQ_Orbitrap_Elite:
case InstrumentModelType_Orbitrap_Fusion: // has a quadrupole but only for mass filtering, not analysis
case InstrumentModelType_Orbitrap_Fusion_ETD: // has a quadrupole but only for mass filtering, not analysis
massAnalyzers.push_back(MassAnalyzerType_Orbitrap);
massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap);
break;
case InstrumentModelType_LTQ_FT:
case InstrumentModelType_LTQ_FT_Ultra:
massAnalyzers.push_back(MassAnalyzerType_FTICR);
massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap);
break;
case InstrumentModelType_SSQ_7000:
case InstrumentModelType_Surveyor_MSQ:
case InstrumentModelType_DSQ:
case InstrumentModelType_DSQ_II:
case InstrumentModelType_ISQ:
case InstrumentModelType_Trace_DSQ:
case InstrumentModelType_GC_IsoLink:
massAnalyzers.push_back(MassAnalyzerType_Single_Quadrupole);
break;
case InstrumentModelType_TSQ_7000:
case InstrumentModelType_TSQ:
case InstrumentModelType_TSQ_Quantum:
case InstrumentModelType_TSQ_Quantum_Access:
case InstrumentModelType_TSQ_Quantum_Ultra:
case InstrumentModelType_TSQ_Quantum_Ultra_AM:
case InstrumentModelType_TSQ_Vantage_Standard:
case InstrumentModelType_TSQ_Vantage_EMR:
case InstrumentModelType_GC_Quantum:
case InstrumentModelType_TSQ_Quantiva:
case InstrumentModelType_TSQ_Endura:
massAnalyzers.push_back(MassAnalyzerType_Triple_Quadrupole);
break;
case InstrumentModelType_LCQ_Advantage:
case InstrumentModelType_LCQ_Classic:
case InstrumentModelType_LCQ_Deca:
case InstrumentModelType_LCQ_Deca_XP_Plus:
case InstrumentModelType_LCQ_Fleet:
case InstrumentModelType_PolarisQ:
case InstrumentModelType_ITQ_700:
case InstrumentModelType_ITQ_900:
massAnalyzers.push_back(MassAnalyzerType_Quadrupole_Ion_Trap);
break;
case InstrumentModelType_LTQ:
case InstrumentModelType_LXQ:
case InstrumentModelType_LTQ_XL_ETD:
case InstrumentModelType_LTQ_Orbitrap_XL_ETD:
case InstrumentModelType_ITQ_1100:
case InstrumentModelType_MALDI_LTQ_XL:
case InstrumentModelType_LTQ_Velos:
case InstrumentModelType_LTQ_Velos_Plus:
massAnalyzers.push_back(MassAnalyzerType_Linear_Ion_Trap);
break;
case InstrumentModelType_DFS:
case InstrumentModelType_MAT253:
case InstrumentModelType_MAT900XP:
case InstrumentModelType_MAT900XP_Trap:
case InstrumentModelType_MAT95XP:
case InstrumentModelType_MAT95XP_Trap:
massAnalyzers.push_back(MassAnalyzerType_Magnetic_Sector);
break;
case InstrumentModelType_Tempus_TOF:
massAnalyzers.push_back(MassAnalyzerType_TOF);
break;
case InstrumentModelType_Element_XR:
case InstrumentModelType_Element_2:
case InstrumentModelType_Element_GD:
case InstrumentModelType_Delta_Plus_Advantage:
case InstrumentModelType_Delta_Plus_XP:
case InstrumentModelType_Neptune:
case InstrumentModelType_Triton:
// TODO: get mass analyzer information for these instruments
break;
case InstrumentModelType_Surveyor_PDA:
case InstrumentModelType_Accela_PDA:
case InstrumentModelType_Unknown:
default:
break;
}
return massAnalyzers;
}
enum PWIZ_API_DECL DetectorType
{
DetectorType_Unknown = -1,
DetectorType_Electron_Multiplier,
DetectorType_Inductive,
DetectorType_Photo_Diode_Array,
DetectorType_Count
};
inline std::vector<DetectorType> getDetectorsForInstrumentModel(InstrumentModelType type)
{
std::vector<DetectorType> detectors;
switch (type)
{
case InstrumentModelType_Exactive:
case InstrumentModelType_Q_Exactive:
detectors.push_back(DetectorType_Inductive);
break;
case InstrumentModelType_LTQ_FT:
case InstrumentModelType_LTQ_FT_Ultra:
case InstrumentModelType_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Discovery:
case InstrumentModelType_LTQ_Orbitrap_XL:
case InstrumentModelType_LTQ_Orbitrap_XL_ETD:
case InstrumentModelType_MALDI_LTQ_Orbitrap:
case InstrumentModelType_LTQ_Orbitrap_Velos:
case InstrumentModelType_LTQ_Orbitrap_Elite:
case InstrumentModelType_Orbitrap_Fusion:
case InstrumentModelType_Orbitrap_Fusion_ETD:
detectors.push_back(DetectorType_Inductive);
detectors.push_back(DetectorType_Electron_Multiplier);
break;
case InstrumentModelType_SSQ_7000:
case InstrumentModelType_TSQ_7000:
case InstrumentModelType_TSQ:
case InstrumentModelType_LCQ_Advantage:
case InstrumentModelType_LCQ_Classic:
case InstrumentModelType_LCQ_Deca:
case InstrumentModelType_LCQ_Deca_XP_Plus:
case InstrumentModelType_Surveyor_MSQ:
case InstrumentModelType_LTQ:
case InstrumentModelType_MALDI_LTQ_XL:
case InstrumentModelType_LXQ:
case InstrumentModelType_LCQ_Fleet:
case InstrumentModelType_LTQ_XL_ETD:
case InstrumentModelType_LTQ_Velos:
case InstrumentModelType_LTQ_Velos_Plus:
case InstrumentModelType_TSQ_Quantum:
case InstrumentModelType_TSQ_Quantum_Access:
case InstrumentModelType_TSQ_Quantum_Ultra:
case InstrumentModelType_TSQ_Quantum_Ultra_AM:
case InstrumentModelType_TSQ_Vantage_Standard:
case InstrumentModelType_TSQ_Vantage_EMR:
case InstrumentModelType_DSQ:
case InstrumentModelType_PolarisQ:
case InstrumentModelType_ITQ_700:
case InstrumentModelType_ITQ_900:
case InstrumentModelType_ITQ_1100:
case InstrumentModelType_Trace_DSQ:
case InstrumentModelType_GC_Quantum:
case InstrumentModelType_DFS:
case InstrumentModelType_DSQ_II:
case InstrumentModelType_ISQ:
case InstrumentModelType_GC_IsoLink:
case InstrumentModelType_TSQ_Quantiva:
case InstrumentModelType_TSQ_Endura:
detectors.push_back(DetectorType_Electron_Multiplier);
break;
case InstrumentModelType_Surveyor_PDA:
case InstrumentModelType_Accela_PDA:
detectors.push_back(DetectorType_Photo_Diode_Array);
case InstrumentModelType_Element_GD:
case InstrumentModelType_Element_XR:
case InstrumentModelType_Element_2:
case InstrumentModelType_Delta_Plus_Advantage:
case InstrumentModelType_Delta_Plus_XP:
case InstrumentModelType_Neptune:
case InstrumentModelType_Tempus_TOF:
case InstrumentModelType_Triton:
case InstrumentModelType_MAT253:
case InstrumentModelType_MAT900XP:
case InstrumentModelType_MAT900XP_Trap:
case InstrumentModelType_MAT95XP:
case InstrumentModelType_MAT95XP_Trap:
// TODO: get detector information for these instruments
break;
case InstrumentModelType_Unknown:
default:
break;
}
return detectors;
}
enum PWIZ_API_DECL ActivationType
{
ActivationType_Unknown = 0,
ActivationType_CID = 1, // Collision Induced Dissociation
ActivationType_MPD = 2, // TODO: what is this?
ActivationType_ECD = 4, // Electron Capture Dissociation
ActivationType_PQD = 8, // Pulsed Q Dissociation
ActivationType_ETD = 16, // Electron Transfer Dissociation
ActivationType_HCD = 32, // High Energy CID
ActivationType_Any = 64, // "any activation type" when used as input parameter
ActivationType_PTR = 128, // Proton Transfer Reaction
ActivationType_NETD = 256, // TODO: nano-ETD?
ActivationType_NPTR = 512, // TODO: nano-PTR?
ActivationType_Count = 1024
};
enum PWIZ_API_DECL MSOrder
{
MSOrder_NeutralGain = -3,
MSOrder_NeutralLoss = -2,
MSOrder_ParentScan = -1,
MSOrder_Any = 0,
MSOrder_MS = 1,
MSOrder_MS2 = 2,
MSOrder_MS3 = 3,
MSOrder_MS4 = 4,
MSOrder_MS5 = 5,
MSOrder_MS6 = 6,
MSOrder_MS7 = 7,
MSOrder_MS8 = 8,
MSOrder_MS9 = 9,
MSOrder_MS10 = 10,
MSOrder_Count = 11
};
enum PWIZ_API_DECL ScanType
{
ScanType_Unknown = -1,
ScanType_Full = 0,
ScanType_Zoom = 1,
ScanType_SIM = 2,
ScanType_SRM = 3,
ScanType_CRM = 4,
ScanType_Any = 5, /// "any scan type" when used as an input parameter
ScanType_Q1MS = 6,
ScanType_Q3MS = 7,
ScanType_Count = 8
};
enum PWIZ_API_DECL PolarityType
{
PolarityType_Unknown = -1,
PolarityType_Positive = 0,
PolarityType_Negative,
PolarityType_Count
};
enum PWIZ_API_DECL DataPointType
{
DataPointType_Unknown = -1,
DataPointType_Centroid = 0,
DataPointType_Profile,
DataPointType_Count
};
enum PWIZ_API_DECL AccurateMassType
{
AccurateMass_Unknown = -1,
AccurateMass_NotActive = 0, // NOTE: in filter as "!AM": accurate mass not active
AccurateMass_Active, // accurate mass active
AccurateMass_ActiveWithInternalCalibration, // accurate mass with internal calibration
AccurateMass_ActiveWithExternalCalibration // accurate mass with external calibration
};
enum PWIZ_API_DECL TriBool
{
TriBool_Unknown = -1,
TriBool_False = 0,
TriBool_True = 1
};
} // namespace Thermo
} // namespace vendor_api
} // namespace pwiz
#endif // _RAWFILETYPES_H_
| biospi/mzmlb | pwiz/pwiz_aux/msrc/utility/vendor_api/thermo/RawFileTypes.h | C | apache-2.0 | 29,997 |
-- main.lua
-- Implements the plugin entrypoint (in this case the entire plugin)
-- Global variables:
local g_Plugin = nil
local g_PluginFolder = ""
local g_Stats = {}
local g_TrackedPages = {}
local function LoadAPIFiles(a_Folder, a_DstTable)
assert(type(a_Folder) == "string")
assert(type(a_DstTable) == "table")
local Folder = g_PluginFolder .. a_Folder;
for _, fnam in ipairs(cFile:GetFolderContents(Folder)) do
local FileName = Folder .. fnam;
-- We only want .lua files from the folder:
if (cFile:IsFile(FileName) and fnam:match(".*%.lua$")) then
local TablesFn, Err = loadfile(FileName);
if (type(TablesFn) ~= "function") then
LOGWARNING("Cannot load API descriptions from " .. FileName .. ", Lua error '" .. Err .. "'.");
else
local Tables = TablesFn();
if (type(Tables) ~= "table") then
LOGWARNING("Cannot load API descriptions from " .. FileName .. ", returned object is not a table (" .. type(Tables) .. ").");
break
end
for k, cls in pairs(Tables) do
a_DstTable[k] = cls;
end
end -- if (TablesFn)
end -- if (is lua file)
end -- for fnam - Folder[]
end
local function CreateAPITables()
--[[
We want an API table of the following shape:
local API = {
{
Name = "cCuboid",
Functions = {
{Name = "Sort"},
{Name = "IsInside"}
},
Constants = {
},
Variables = {
},
Descendants = {}, -- Will be filled by ReadDescriptions(), array of class APIs (references to other member in the tree)
},
{
Name = "cBlockArea",
Functions = {
{Name = "Clear"},
{Name = "CopyFrom"},
...
},
Constants = {
{Name = "baTypes", Value = 0},
{Name = "baMetas", Value = 1},
...
},
Variables = {
},
...
},
cCuboid = {} -- Each array item also has the map item by its name
};
local Globals = {
Functions = {
...
},
Constants = {
...
}
};
--]]
local Globals = {Functions = {}, Constants = {}, Variables = {}, Descendants = {}};
local API = {};
local function Add(a_APIContainer, a_ObjName, a_ObjValue)
if (type(a_ObjValue) == "function") then
table.insert(a_APIContainer.Functions, {Name = a_ObjName});
elseif (
(type(a_ObjValue) == "number") or
(type(a_ObjValue) == "string")
) then
table.insert(a_APIContainer.Constants, {Name = a_ObjName, Value = a_ObjValue});
end
end
local function ParseClass(a_ClassName, a_ClassObj)
local res = {Name = a_ClassName, Functions = {}, Constants = {}, Variables = {}, Descendants = {}};
-- Add functions and constants:
for i, v in pairs(a_ClassObj) do
Add(res, i, v);
end
-- Member variables:
local SetField = a_ClassObj[".set"] or {};
if ((a_ClassObj[".get"] ~= nil) and (type(a_ClassObj[".get"]) == "table")) then
for k in pairs(a_ClassObj[".get"]) do
if (SetField[k] == nil) then
-- It is a read-only variable, add it as a constant:
table.insert(res.Constants, {Name = k, Value = ""});
else
-- It is a read-write variable, add it as a variable:
table.insert(res.Variables, { Name = k });
end
end
end
return res;
end
for i, v in pairs(_G) do
if (
(v ~= _G) and -- don't want the global namespace
(v ~= _G.packages) and -- don't want any packages
(v ~= _G[".get"]) and
(v ~= g_APIDesc)
) then
if (type(v) == "table") then
local cls = ParseClass(i, v)
table.insert(API, cls);
API[cls.Name] = cls
else
Add(Globals, i, v);
end
end
end
return API, Globals;
end
local function WriteArticles(f)
f:write([[
<a name="articles"><h2>Articles</h2></a>
<p>The following articles provide various extra information on plugin development</p>
<ul>
]]);
for _, extra in ipairs(g_APIDesc.ExtraPages) do
local SrcFileName = g_PluginFolder .. "/" .. extra.FileName;
if (cFile:Exists(SrcFileName)) then
local DstFileName = "API/" .. extra.FileName;
if (cFile:Exists(DstFileName)) then
cFile:Delete(DstFileName);
end
cFile:Copy(SrcFileName, DstFileName);
f:write("<li><a href=\"" .. extra.FileName .. "\">" .. extra.Title .. "</a></li>\n");
else
f:write("<li>" .. extra.Title .. " <i>(file is missing)</i></li>\n");
end
end
f:write("</ul><hr />");
end
-- Make a link out of anything with the special linkifying syntax {{link|title}}
local function LinkifyString(a_String, a_Referrer)
assert(a_Referrer ~= nil);
assert(a_Referrer ~= "");
--- Adds a page to the list of tracked pages (to be checked for existence at the end)
local function AddTrackedPage(a_PageName)
local Pg = (g_TrackedPages[a_PageName] or {});
table.insert(Pg, a_Referrer);
g_TrackedPages[a_PageName] = Pg;
end
--- Creates the HTML for the specified link and title
local function CreateLink(Link, Title)
if (Link:sub(1, 7) == "http://") then
-- The link is a full absolute URL, do not modify, do not track:
return "<a href=\"" .. Link .. "\">" .. Title .. "</a>";
end
local idxHash = Link:find("#");
if (idxHash ~= nil) then
-- The link contains an anchor:
if (idxHash == 1) then
-- Anchor in the current page, no need to track:
return "<a href=\"" .. Link .. "\">" .. Title .. "</a>";
end
-- Anchor in another page:
local PageName = Link:sub(1, idxHash - 1);
AddTrackedPage(PageName);
return "<a href=\"" .. PageName .. ".html#" .. Link:sub(idxHash + 1) .. "\">" .. Title .. "</a>";
end
-- Link without anchor:
AddTrackedPage(Link);
return "<a href=\"" .. Link .. ".html\">" .. Title .. "</a>";
end
-- Linkify the strings using the CreateLink() function:
local txt = a_String:gsub("{{([^|}]*)|([^}]*)}}", CreateLink) -- {{link|title}}
txt = txt:gsub("{{([^|}]*)}}", -- {{LinkAndTitle}}
function(LinkAndTitle)
local idxHash = LinkAndTitle:find("#");
if (idxHash ~= nil) then
-- The LinkAndTitle contains a hash, remove the hashed part from the title:
return CreateLink(LinkAndTitle, LinkAndTitle:sub(1, idxHash - 1));
end
return CreateLink(LinkAndTitle, LinkAndTitle);
end
);
return txt;
end
local function WriteHtmlHook(a_Hook, a_HookNav)
local fnam = "API/" .. a_Hook.DefaultFnName .. ".html";
local f, error = io.open(fnam, "w");
if (f == nil) then
LOG("Cannot write \"" .. fnam .. "\": \"" .. error .. "\".");
return;
end
local HookName = a_Hook.DefaultFnName;
f:write([[<!DOCTYPE html><html>
<head>
<title>MCServer API - ]], HookName, [[ Hook</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="prettify.css" />
<script src="prettify.js"></script>
<script src="lang-lua.js"></script>
</head>
<body>
<div id="content">
<header>
<h1>]], a_Hook.Name, [[</h1>
<hr />
</header>
<table><tr><td style="vertical-align: top;">
Index:<br />
<a href='index.html#articles'>Articles</a><br />
<a href='index.html#classes'>Classes</a><br />
<a href='index.html#hooks'>Hooks</a><br />
<br />
Quick navigation:<br />
]]);
f:write(a_HookNav);
f:write([[
</td><td style="vertical-align: top;"><p>
]]);
f:write(LinkifyString(a_Hook.Desc, HookName));
f:write("</p>\n<hr /><h1>Callback function</h1>\n<p>The default name for the callback function is ");
f:write(a_Hook.DefaultFnName, ". It has the following signature:\n");
f:write("<pre class=\"prettyprint lang-lua\">function ", HookName, "(");
if (a_Hook.Params == nil) then
a_Hook.Params = {};
end
for i, param in ipairs(a_Hook.Params) do
if (i > 1) then
f:write(", ");
end
f:write(param.Name);
end
f:write(")</pre>\n<hr /><h1>Parameters:</h1>\n<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n");
for _, param in ipairs(a_Hook.Params) do
f:write("<tr><td>", param.Name, "</td><td>", LinkifyString(param.Type, HookName), "</td><td>", LinkifyString(param.Notes, HookName), "</td></tr>\n");
end
f:write("</table>\n<p>" .. (a_Hook.Returns or "") .. "</p>\n\n");
f:write([[<hr /><h1>Code examples</h1><h2>Registering the callback</h2>]]);
f:write("<pre class=\"prettyprint lang-lua\">\n");
f:write([[cPluginManager:AddHook(cPluginManager.]] .. a_Hook.Name .. ", My" .. a_Hook.DefaultFnName .. [[);]]);
f:write("</pre>\n\n");
local Examples = a_Hook.CodeExamples or {};
for _, example in ipairs(Examples) do
f:write("<h2>", (example.Title or "<i>missing Title</i>"), "</h2>\n");
f:write("<p>", (example.Desc or "<i>missing Desc</i>"), "</p>\n");
f:write("<pre class=\"prettyprint lang-lua\">", (example.Code or "<i>missing Code</i>"), "\n</pre>\n\n");
end
f:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]);
f:close();
end
local function WriteHooks(f, a_Hooks, a_UndocumentedHooks, a_HookNav)
f:write([[
<a name="hooks"><h2>Hooks</h2></a>
<p>
A plugin can register to be called whenever an "interesting event" occurs. It does so by calling
<a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback
function to handle the event.</p>
<p>
A plugin can decide whether it will let the event pass through to the rest of the plugins, or hide it
from them. This is determined by the return value from the hook callback function. If the function
returns false or no value, the event is propagated further. If the function returns true, the processing
is stopped, no other plugin receives the notification (and possibly MCServer disables the default
behavior for the event). See each hook's details to see the exact behavior.</p>
<table>
<tr>
<th>Hook name</th>
<th>Called when</th>
</tr>
]]);
for _, hook in ipairs(a_Hooks) do
if (hook.DefaultFnName == nil) then
-- The hook is not documented yet
f:write(" <tr>\n <td>" .. hook.Name .. "</td>\n <td><i>(No documentation yet)</i></td>\n </tr>\n");
table.insert(a_UndocumentedHooks, hook.Name);
else
f:write(" <tr>\n <td><a href=\"" .. hook.DefaultFnName .. ".html\">" .. hook.Name .. "</a></td>\n <td>" .. LinkifyString(hook.CalledWhen, hook.Name) .. "</td>\n </tr>\n");
WriteHtmlHook(hook, a_HookNav);
end
end
f:write([[
</table>
<hr />
]]);
end
local function ReadDescriptions(a_API)
-- Returns true if the class of the specified name is to be ignored
local function IsClassIgnored(a_ClsName)
if (g_APIDesc.IgnoreClasses == nil) then
return false;
end
for _, name in ipairs(g_APIDesc.IgnoreClasses) do
if (a_ClsName:match(name)) then
return true;
end
end
return false;
end
-- Returns true if the function is to be ignored
local function IsFunctionIgnored(a_ClassName, a_FnName)
if (g_APIDesc.IgnoreFunctions == nil) then
return false;
end
if (((g_APIDesc.Classes[a_ClassName] or {}).Functions or {})[a_FnName] ~= nil) then
-- The function is documented, don't ignore
return false;
end
local FnName = a_ClassName .. "." .. a_FnName;
for _, name in ipairs(g_APIDesc.IgnoreFunctions) do
if (FnName:match(name)) then
return true;
end
end
return false;
end
-- Returns true if the constant (specified by its fully qualified name) is to be ignored
local function IsConstantIgnored(a_CnName)
if (g_APIDesc.IgnoreConstants == nil) then
return false;
end;
for _, name in ipairs(g_APIDesc.IgnoreConstants) do
if (a_CnName:match(name)) then
return true;
end
end
return false;
end
-- Returns true if the member variable (specified by its fully qualified name) is to be ignored
local function IsVariableIgnored(a_VarName)
if (g_APIDesc.IgnoreVariables == nil) then
return false;
end;
for _, name in ipairs(g_APIDesc.IgnoreVariables) do
if (a_VarName:match(name)) then
return true;
end
end
return false;
end
-- Remove ignored classes from a_API:
local APICopy = {};
for _, cls in ipairs(a_API) do
if not(IsClassIgnored(cls.Name)) then
table.insert(APICopy, cls);
end
end
for i = 1, #a_API do
a_API[i] = APICopy[i];
end;
-- Process the documentation for each class:
for _, cls in ipairs(a_API) do
-- Initialize default values for each class:
cls.ConstantGroups = {};
cls.NumConstantsInGroups = 0;
cls.NumConstantsInGroupsForDescendants = 0;
-- Rename special functions:
for _, fn in ipairs(cls.Functions) do
if (fn.Name == ".call") then
fn.DocID = "constructor";
fn.Name = "() <i>(constructor)</i>";
elseif (fn.Name == ".add") then
fn.DocID = "operator_plus";
fn.Name = "<i>operator +</i>";
elseif (fn.Name == ".div") then
fn.DocID = "operator_div";
fn.Name = "<i>operator /</i>";
elseif (fn.Name == ".mul") then
fn.DocID = "operator_mul";
fn.Name = "<i>operator *</i>";
elseif (fn.Name == ".sub") then
fn.DocID = "operator_sub";
fn.Name = "<i>operator -</i>";
elseif (fn.Name == ".eq") then
fn.DocID = "operator_eq";
fn.Name = "<i>operator ==</i>";
end
end
local APIDesc = g_APIDesc.Classes[cls.Name];
if (APIDesc ~= nil) then
APIDesc.IsExported = true;
cls.Desc = APIDesc.Desc;
cls.AdditionalInfo = APIDesc.AdditionalInfo;
-- Process inheritance:
if (APIDesc.Inherits ~= nil) then
for _, icls in ipairs(a_API) do
if (icls.Name == APIDesc.Inherits) then
table.insert(icls.Descendants, cls);
cls.Inherits = icls;
end
end
end
cls.UndocumentedFunctions = {}; -- This will contain names of all the functions that are not documented
cls.UndocumentedConstants = {}; -- This will contain names of all the constants that are not documented
cls.UndocumentedVariables = {}; -- This will contain names of all the variables that are not documented
local DoxyFunctions = {}; -- This will contain all the API functions together with their documentation
local function AddFunction(a_Name, a_Params, a_Return, a_Notes)
table.insert(DoxyFunctions, {Name = a_Name, Params = a_Params, Return = a_Return, Notes = a_Notes});
end
if (APIDesc.Functions ~= nil) then
-- Assign function descriptions:
for _, func in ipairs(cls.Functions) do
local FnName = func.DocID or func.Name;
local FnDesc = APIDesc.Functions[FnName];
if (FnDesc == nil) then
-- No description for this API function
AddFunction(func.Name);
if not(IsFunctionIgnored(cls.Name, FnName)) then
table.insert(cls.UndocumentedFunctions, FnName);
end
else
-- Description is available
if (FnDesc[1] == nil) then
-- Single function definition
AddFunction(func.Name, FnDesc.Params, FnDesc.Return, FnDesc.Notes);
else
-- Multiple function overloads
for _, desc in ipairs(FnDesc) do
AddFunction(func.Name, desc.Params, desc.Return, desc.Notes);
end -- for k, desc - FnDesc[]
end
FnDesc.IsExported = true;
end
end -- for j, func
-- Replace functions with their described and overload-expanded versions:
cls.Functions = DoxyFunctions;
else -- if (APIDesc.Functions ~= nil)
for _, func in ipairs(cls.Functions) do
local FnName = func.DocID or func.Name;
if not(IsFunctionIgnored(cls.Name, FnName)) then
table.insert(cls.UndocumentedFunctions, FnName);
end
end
end -- if (APIDesc.Functions ~= nil)
if (APIDesc.Constants ~= nil) then
-- Assign constant descriptions:
for _, cons in ipairs(cls.Constants) do
local CnDesc = APIDesc.Constants[cons.Name];
if (CnDesc == nil) then
-- Not documented
if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
table.insert(cls.UndocumentedConstants, cons.Name);
end
else
cons.Notes = CnDesc.Notes;
CnDesc.IsExported = true;
end
end -- for j, cons
else -- if (APIDesc.Constants ~= nil)
for _, cons in ipairs(cls.Constants) do
if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
table.insert(cls.UndocumentedConstants, cons.Name);
end
end
end -- else if (APIDesc.Constants ~= nil)
-- Assign member variables' descriptions:
if (APIDesc.Variables ~= nil) then
for _, var in ipairs(cls.Variables) do
local VarDesc = APIDesc.Variables[var.Name];
if (VarDesc == nil) then
-- Not documented
if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then
table.insert(cls.UndocumentedVariables, var.Name);
end
else
-- Copy all documentation:
for k, v in pairs(VarDesc) do
var[k] = v
end
end
end -- for j, var
else -- if (APIDesc.Variables ~= nil)
for _, var in ipairs(cls.Variables) do
if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then
table.insert(cls.UndocumentedVariables, var.Name);
end
end
end -- else if (APIDesc.Variables ~= nil)
if (APIDesc.ConstantGroups ~= nil) then
-- Create links between the constants and the groups:
local NumInGroups = 0;
local NumInDescendantGroups = 0;
for j, group in pairs(APIDesc.ConstantGroups) do
group.Name = j;
group.Constants = {};
if (type(group.Include) == "string") then
group.Include = { group.Include };
end
local NumInGroup = 0;
for _, incl in ipairs(group.Include or {}) do
for _, cons in ipairs(cls.Constants) do
if ((cons.Group == nil) and cons.Name:match(incl)) then
cons.Group = group;
table.insert(group.Constants, cons);
NumInGroup = NumInGroup + 1;
end
end -- for cidx - cls.Constants[]
end -- for idx - group.Include[]
NumInGroups = NumInGroups + NumInGroup;
if (group.ShowInDescendants) then
NumInDescendantGroups = NumInDescendantGroups + NumInGroup;
end
-- Sort the constants:
table.sort(group.Constants,
function(c1, c2)
return (c1.Name < c2.Name);
end
);
end -- for j - APIDesc.ConstantGroups[]
cls.ConstantGroups = APIDesc.ConstantGroups;
cls.NumConstantsInGroups = NumInGroups;
cls.NumConstantsInGroupsForDescendants = NumInDescendantGroups;
-- Remove grouped constants from the normal list:
local NewConstants = {};
for _, cons in ipairs(cls.Constants) do
if (cons.Group == nil) then
table.insert(NewConstants, cons);
end
end
cls.Constants = NewConstants;
end -- if (ConstantGroups ~= nil)
else -- if (APIDesc ~= nil)
-- Class is not documented at all, add all its members to Undocumented lists:
cls.UndocumentedFunctions = {};
cls.UndocumentedConstants = {};
cls.UndocumentedVariables = {};
cls.Variables = cls.Variables or {};
g_Stats.NumUndocumentedClasses = g_Stats.NumUndocumentedClasses + 1;
for _, func in ipairs(cls.Functions) do
local FnName = func.DocID or func.Name;
if not(IsFunctionIgnored(cls.Name, FnName)) then
table.insert(cls.UndocumentedFunctions, FnName);
end
end -- for j, func - cls.Functions[]
for _, cons in ipairs(cls.Constants) do
if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
table.insert(cls.UndocumentedConstants, cons.Name);
end
end -- for j, cons - cls.Constants[]
for _, var in ipairs(cls.Variables) do
if not(IsConstantIgnored(cls.Name .. "." .. var.Name)) then
table.insert(cls.UndocumentedVariables, var.Name);
end
end -- for j, var - cls.Variables[]
end -- else if (APIDesc ~= nil)
-- Remove ignored functions:
local NewFunctions = {};
for _, fn in ipairs(cls.Functions) do
if (not(IsFunctionIgnored(cls.Name, fn.Name))) then
table.insert(NewFunctions, fn);
end
end -- for j, fn
cls.Functions = NewFunctions;
-- Sort the functions (they may have been renamed):
table.sort(cls.Functions,
function(f1, f2)
if (f1.Name == f2.Name) then
-- Same name, either comparing the same function to itself, or two overloads, in which case compare the params
if ((f1.Params == nil) or (f2.Params == nil)) then
return 0;
end
return (f1.Params < f2.Params);
end
return (f1.Name < f2.Name);
end
);
-- Remove ignored constants:
local NewConstants = {};
for _, cn in ipairs(cls.Constants) do
if (not(IsFunctionIgnored(cls.Name, cn.Name))) then
table.insert(NewConstants, cn);
end
end -- for j, cn
cls.Constants = NewConstants;
-- Sort the constants:
table.sort(cls.Constants,
function(c1, c2)
return (c1.Name < c2.Name);
end
);
-- Remove ignored member variables:
local NewVariables = {};
for _, var in ipairs(cls.Variables) do
if (not(IsVariableIgnored(cls.Name .. "." .. var.Name))) then
table.insert(NewVariables, var);
end
end -- for j, var
cls.Variables = NewVariables;
-- Sort the member variables:
table.sort(cls.Variables,
function(v1, v2)
return (v1.Name < v2.Name);
end
);
end -- for i, cls
-- Sort the descendants lists:
for _, cls in ipairs(a_API) do
table.sort(cls.Descendants,
function(c1, c2)
return (c1.Name < c2.Name);
end
);
end -- for i, cls
end
local function ReadHooks(a_Hooks)
--[[
a_Hooks = {
{ Name = "HOOK_1"},
{ Name = "HOOK_2"},
...
};
We want to add hook descriptions to each hook in this array
--]]
for _, hook in ipairs(a_Hooks) do
local HookDesc = g_APIDesc.Hooks[hook.Name];
if (HookDesc ~= nil) then
for key, val in pairs(HookDesc) do
hook[key] = val;
end
end
end -- for i, hook - a_Hooks[]
g_Stats.NumTotalHooks = #a_Hooks;
end
local function WriteHtmlClass(a_ClassAPI, a_ClassMenu)
local cf, err = io.open("API/" .. a_ClassAPI.Name .. ".html", "w");
if (cf == nil) then
LOGINFO("Cannot write HTML API for class " .. a_ClassAPI.Name .. ": " .. err)
return;
end
-- Writes a table containing all functions in the specified list, with an optional "inherited from" header when a_InheritedName is valid
local function WriteFunctions(a_Functions, a_InheritedName)
if (#a_Functions == 0) then
return;
end
if (a_InheritedName ~= nil) then
cf:write("<h2>Functions inherited from ", a_InheritedName, "</h2>\n");
end
cf:write("<table>\n<tr><th>Name</th><th>Parameters</th><th>Return value</th><th>Notes</th></tr>\n");
for _, func in ipairs(a_Functions) do
cf:write("<tr><td>", func.Name, "</td>\n");
cf:write("<td>", LinkifyString(func.Params or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n");
cf:write("<td>", LinkifyString(func.Return or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n");
cf:write("<td>", LinkifyString(func.Notes or "<i>(undocumented)</i>", (a_InheritedName or a_ClassAPI.Name)), "</td></tr>\n");
end
cf:write("</table>\n");
end
local function WriteConstantTable(a_Constants, a_Source)
cf:write("<table>\n<tr><th>Name</th><th>Value</th><th>Notes</th></tr>\n");
for _, cons in ipairs(a_Constants) do
cf:write("<tr><td>", cons.Name, "</td>\n");
cf:write("<td>", cons.Value, "</td>\n");
cf:write("<td>", LinkifyString(cons.Notes or "", a_Source), "</td></tr>\n");
end
cf:write("</table>\n\n");
end
local function WriteConstants(a_Constants, a_ConstantGroups, a_NumConstantGroups, a_InheritedName)
if ((#a_Constants == 0) and (a_NumConstantGroups == 0)) then
return;
end
local Source = a_ClassAPI.Name
if (a_InheritedName ~= nil) then
cf:write("<h2>Constants inherited from ", a_InheritedName, "</h2>\n");
Source = a_InheritedName;
end
if (#a_Constants > 0) then
WriteConstantTable(a_Constants, Source);
end
for _, group in pairs(a_ConstantGroups) do
if ((a_InheritedName == nil) or group.ShowInDescendants) then
cf:write("<a name='", group.Name, "'><p>");
cf:write(LinkifyString(group.TextBefore or "", Source));
WriteConstantTable(group.Constants, a_InheritedName or a_ClassAPI.Name);
cf:write(LinkifyString(group.TextAfter or "", Source), "</a></p>");
end
end
end
local function WriteVariables(a_Variables, a_InheritedName)
if (#a_Variables == 0) then
return;
end
if (a_InheritedName ~= nil) then
cf:write("<h2>Member variables inherited from ", a_InheritedName, "</h2>\n");
end
cf:write("<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n");
for _, var in ipairs(a_Variables) do
cf:write("<tr><td>", var.Name, "</td>\n");
cf:write("<td>", LinkifyString(var.Type or "<i>(undocumented)</i>", a_InheritedName or a_ClassAPI.Name), "</td>\n");
cf:write("<td>", LinkifyString(var.Notes or "", a_InheritedName or a_ClassAPI.Name), "</td>\n </tr>\n");
end
cf:write("</table>\n\n");
end
local function WriteDescendants(a_Descendants)
if (#a_Descendants == 0) then
return;
end
cf:write("<ul>");
for _, desc in ipairs(a_Descendants) do
cf:write("<li><a href=\"", desc.Name, ".html\">", desc.Name, "</a>");
WriteDescendants(desc.Descendants);
cf:write("</li>\n");
end
cf:write("</ul>\n");
end
local ClassName = a_ClassAPI.Name;
-- Build an array of inherited classes chain:
local InheritanceChain = {};
local CurrInheritance = a_ClassAPI.Inherits;
while (CurrInheritance ~= nil) do
table.insert(InheritanceChain, CurrInheritance);
CurrInheritance = CurrInheritance.Inherits;
end
cf:write([[<!DOCTYPE html><html>
<head>
<title>MCServer API - ]], a_ClassAPI.Name, [[ Class</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="prettify.css" />
<script src="prettify.js"></script>
<script src="lang-lua.js"></script>
</head>
<body>
<div id="content">
<header>
<h1>]], a_ClassAPI.Name, [[</h1>
<hr />
</header>
<table><tr><td style="vertical-align: top;">
Index:<br />
<a href='index.html#articles'>Articles</a><br />
<a href='index.html#classes'>Classes</a><br />
<a href='index.html#hooks'>Hooks</a><br />
<br />
Quick navigation:<br />
]]);
cf:write(a_ClassMenu);
cf:write([[
</td><td style="vertical-align: top;"><h1>Contents</h1>
<p><ul>
]]);
local HasInheritance = ((#a_ClassAPI.Descendants > 0) or (a_ClassAPI.Inherits ~= nil));
local HasConstants = (#a_ClassAPI.Constants > 0) or (a_ClassAPI.NumConstantsInGroups > 0);
local HasFunctions = (#a_ClassAPI.Functions > 0);
local HasVariables = (#a_ClassAPI.Variables > 0);
for _, cls in ipairs(InheritanceChain) do
HasConstants = HasConstants or (#cls.Constants > 0) or (cls.NumConstantsInGroupsForDescendants > 0);
HasFunctions = HasFunctions or (#cls.Functions > 0);
HasVariables = HasVariables or (#cls.Variables > 0);
end
-- Write the table of contents:
if (HasInheritance) then
cf:write("<li><a href=\"#inherits\">Inheritance</a></li>\n");
end
if (HasConstants) then
cf:write("<li><a href=\"#constants\">Constants</a></li>\n");
end
if (HasVariables) then
cf:write("<li><a href=\"#variables\">Member variables</a></li>\n");
end
if (HasFunctions) then
cf:write("<li><a href=\"#functions\">Functions</a></li>\n");
end
if (a_ClassAPI.AdditionalInfo ~= nil) then
for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do
cf:write("<li><a href=\"#additionalinfo_", i, "\">", (additional.Header or "<i>(No header)</i>"), "</a></li>\n");
end
end
cf:write("</ul></p>\n");
-- Write the class description:
cf:write("<hr /><a name=\"desc\"><h1>", ClassName, " class</h1></a>\n");
if (a_ClassAPI.Desc ~= nil) then
cf:write("<p>");
cf:write(LinkifyString(a_ClassAPI.Desc, ClassName));
cf:write("</p>\n\n");
end;
-- Write the inheritance, if available:
if (HasInheritance) then
cf:write("<hr /><a name=\"inherits\"><h1>Inheritance</h1></a>\n");
if (#InheritanceChain > 0) then
cf:write("<p>This class inherits from the following parent classes:<ul>\n");
for _, cls in ipairs(InheritanceChain) do
cf:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n");
end
cf:write("</ul></p>\n");
end
if (#a_ClassAPI.Descendants > 0) then
cf:write("<p>This class has the following descendants:\n");
WriteDescendants(a_ClassAPI.Descendants);
cf:write("</p>\n\n");
end
end
-- Write the constants:
if (HasConstants) then
cf:write("<a name=\"constants\"><hr /><h1>Constants</h1></a>\n");
WriteConstants(a_ClassAPI.Constants, a_ClassAPI.ConstantGroups, a_ClassAPI.NumConstantsInGroups, nil);
g_Stats.NumTotalConstants = g_Stats.NumTotalConstants + #a_ClassAPI.Constants + (a_ClassAPI.NumConstantsInGroups or 0);
for _, cls in ipairs(InheritanceChain) do
WriteConstants(cls.Constants, cls.ConstantGroups, cls.NumConstantsInGroupsForDescendants, cls.Name);
end;
end;
-- Write the member variables:
if (HasVariables) then
cf:write("<a name=\"variables\"><hr /><h1>Member variables</h1></a>\n");
WriteVariables(a_ClassAPI.Variables, nil);
g_Stats.NumTotalVariables = g_Stats.NumTotalVariables + #a_ClassAPI.Variables;
for _, cls in ipairs(InheritanceChain) do
WriteVariables(cls.Variables, cls.Name);
end;
end
-- Write the functions, including the inherited ones:
if (HasFunctions) then
cf:write("<a name=\"functions\"><hr /><h1>Functions</h1></a>\n");
WriteFunctions(a_ClassAPI.Functions, nil);
g_Stats.NumTotalFunctions = g_Stats.NumTotalFunctions + #a_ClassAPI.Functions;
for _, cls in ipairs(InheritanceChain) do
WriteFunctions(cls.Functions, cls.Name);
end
end
-- Write the additional infos:
if (a_ClassAPI.AdditionalInfo ~= nil) then
for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do
cf:write("<a name=\"additionalinfo_", i, "\"><h1>", additional.Header, "</h1></a>\n");
cf:write(LinkifyString(additional.Contents, ClassName));
end
end
cf:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]);
cf:close();
end
local function WriteClasses(f, a_API, a_ClassMenu)
f:write([[
<a name="classes"><h2>Class index</h2></a>
<p>The following classes are available in the MCServer Lua scripting language:
<ul>
]]);
for _, cls in ipairs(a_API) do
f:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n");
WriteHtmlClass(cls, a_ClassMenu);
end
f:write([[
</ul></p>
<hr />
]]);
end
--- Writes a list of undocumented objects into a file
local function ListUndocumentedObjects(API, UndocumentedHooks)
f = io.open("API/_undocumented.lua", "w");
if (f ~= nil) then
f:write("\n-- This is the list of undocumented API objects, automatically generated by APIDump\n\n");
f:write("g_APIDesc =\n{\n\tClasses =\n\t{\n");
for _, cls in ipairs(API) do
local HasFunctions = ((cls.UndocumentedFunctions ~= nil) and (#cls.UndocumentedFunctions > 0));
local HasConstants = ((cls.UndocumentedConstants ~= nil) and (#cls.UndocumentedConstants > 0));
local HasVariables = ((cls.UndocumentedVariables ~= nil) and (#cls.UndocumentedVariables > 0));
g_Stats.NumUndocumentedFunctions = g_Stats.NumUndocumentedFunctions + #cls.UndocumentedFunctions;
g_Stats.NumUndocumentedConstants = g_Stats.NumUndocumentedConstants + #cls.UndocumentedConstants;
g_Stats.NumUndocumentedVariables = g_Stats.NumUndocumentedVariables + #cls.UndocumentedVariables;
if (HasFunctions or HasConstants or HasVariables) then
f:write("\t\t" .. cls.Name .. " =\n\t\t{\n");
if ((cls.Desc == nil) or (cls.Desc == "")) then
f:write("\t\t\tDesc = \"\"\n");
end
end
if (HasFunctions) then
f:write("\t\t\tFunctions =\n\t\t\t{\n");
table.sort(cls.UndocumentedFunctions);
for _, fn in ipairs(cls.UndocumentedFunctions) do
f:write("\t\t\t\t" .. fn .. " = { Params = \"\", Return = \"\", Notes = \"\" },\n");
end -- for j, fn - cls.UndocumentedFunctions[]
f:write("\t\t\t},\n\n");
end
if (HasConstants) then
f:write("\t\t\tConstants =\n\t\t\t{\n");
table.sort(cls.UndocumentedConstants);
for _, cn in ipairs(cls.UndocumentedConstants) do
f:write("\t\t\t\t" .. cn .. " = { Notes = \"\" },\n");
end -- for j, fn - cls.UndocumentedConstants[]
f:write("\t\t\t},\n\n");
end
if (HasVariables) then
f:write("\t\t\tVariables =\n\t\t\t{\n");
table.sort(cls.UndocumentedVariables);
for _, vn in ipairs(cls.UndocumentedVariables) do
f:write("\t\t\t\t" .. vn .. " = { Type = \"\", Notes = \"\" },\n");
end -- for j, fn - cls.UndocumentedVariables[]
f:write("\t\t\t},\n\n");
end
if (HasFunctions or HasConstants or HasVariables) then
f:write("\t\t},\n\n");
end
end -- for i, cls - API[]
f:write("\t},\n");
if (#UndocumentedHooks > 0) then
f:write("\n\tHooks =\n\t{\n");
for i, hook in ipairs(UndocumentedHooks) do
if (i > 1) then
f:write("\n");
end
f:write("\t\t" .. hook .. " =\n\t\t{\n");
f:write("\t\t\tCalledWhen = \"\",\n");
f:write("\t\t\tDefaultFnName = \"On\", -- also used as pagename\n");
f:write("\t\t\tDesc = [[\n\t\t\t\t\n\t\t\t]],\n");
f:write("\t\t\tParams =\n\t\t\t{\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
f:write("\t\t\t},\n");
f:write("\t\t\tReturns = [[\n\t\t\t\t\n\t\t\t]],\n");
f:write("\t\t}, -- " .. hook .. "\n");
end
f:write("\t},\n");
end
f:write("}\n\n\n\n");
f:close();
end
g_Stats.NumUndocumentedHooks = #UndocumentedHooks;
end
--- Lists the API objects that are documented but not available in the API:
local function ListUnexportedObjects()
f = io.open("API/_unexported-documented.txt", "w");
if (f ~= nil) then
for clsname, cls in pairs(g_APIDesc.Classes) do
if not(cls.IsExported) then
-- The whole class is not exported
f:write("class\t" .. clsname .. "\n");
else
if (cls.Functions ~= nil) then
for fnname, fnapi in pairs(cls.Functions) do
if not(fnapi.IsExported) then
f:write("func\t" .. clsname .. "." .. fnname .. "\n");
end
end -- for j, fn - cls.Functions[]
end
if (cls.Constants ~= nil) then
for cnname, cnapi in pairs(cls.Constants) do
if not(cnapi.IsExported) then
f:write("const\t" .. clsname .. "." .. cnname .. "\n");
end
end -- for j, fn - cls.Functions[]
end
end
end -- for i, cls - g_APIDesc.Classes[]
f:close();
end
end
local function ListMissingPages()
local MissingPages = {};
local NumLinks = 0;
for PageName, Referrers in pairs(g_TrackedPages) do
NumLinks = NumLinks + 1;
if not(cFile:Exists("API/" .. PageName .. ".html")) then
table.insert(MissingPages, {Name = PageName, Refs = Referrers} );
end
end;
g_Stats.NumTrackedLinks = NumLinks;
g_TrackedPages = {};
if (#MissingPages == 0) then
-- No missing pages, congratulations!
return;
end
-- Sort the pages by name:
table.sort(MissingPages,
function (Page1, Page2)
return (Page1.Name < Page2.Name);
end
);
-- Output the pages:
local f, err = io.open("API/_missingPages.txt", "w");
if (f == nil) then
LOGWARNING("Cannot open _missingPages.txt for writing: '" .. err .. "'. There are " .. #MissingPages .. " pages missing.");
return;
end
for _, pg in ipairs(MissingPages) do
f:write(pg.Name .. ":\n");
-- Sort and output the referrers:
table.sort(pg.Refs);
f:write("\t" .. table.concat(pg.Refs, "\n\t"));
f:write("\n\n");
end
f:close();
g_Stats.NumInvalidLinks = #MissingPages;
end
--- Writes the documentation statistics (in g_Stats) into the given HTML file
local function WriteStats(f)
local function ExportMeter(a_Percent)
local Color;
if (a_Percent > 99) then
Color = "green";
elseif (a_Percent > 50) then
Color = "orange";
else
Color = "red";
end
local meter = {
"\n",
"<div style=\"background-color: black; padding: 1px; width: 100px\">\n",
"<div style=\"background-color: ",
Color,
"; width: ",
a_Percent,
"%; height: 16px\"></div></div>\n</td><td>",
string.format("%.2f", a_Percent),
" %",
};
return table.concat(meter, "");
end
f:write([[
<hr /><a name="docstats"><h2>Documentation statistics</h2></a>
<table><tr><th>Object</th><th>Total</th><th>Documented</th><th>Undocumented</th><th colspan="2">Documented %</th></tr>
]]);
f:write("<tr><td>Classes</td><td>", g_Stats.NumTotalClasses);
f:write("</td><td>", g_Stats.NumTotalClasses - g_Stats.NumUndocumentedClasses);
f:write("</td><td>", g_Stats.NumUndocumentedClasses);
f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalClasses - g_Stats.NumUndocumentedClasses) / g_Stats.NumTotalClasses));
f:write("</td></tr>\n");
f:write("<tr><td>Functions</td><td>", g_Stats.NumTotalFunctions);
f:write("</td><td>", g_Stats.NumTotalFunctions - g_Stats.NumUndocumentedFunctions);
f:write("</td><td>", g_Stats.NumUndocumentedFunctions);
f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalFunctions - g_Stats.NumUndocumentedFunctions) / g_Stats.NumTotalFunctions));
f:write("</td></tr>\n");
f:write("<tr><td>Member variables</td><td>", g_Stats.NumTotalVariables);
f:write("</td><td>", g_Stats.NumTotalVariables - g_Stats.NumUndocumentedVariables);
f:write("</td><td>", g_Stats.NumUndocumentedVariables);
f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalVariables - g_Stats.NumUndocumentedVariables) / g_Stats.NumTotalVariables));
f:write("</td></tr>\n");
f:write("<tr><td>Constants</td><td>", g_Stats.NumTotalConstants);
f:write("</td><td>", g_Stats.NumTotalConstants - g_Stats.NumUndocumentedConstants);
f:write("</td><td>", g_Stats.NumUndocumentedConstants);
f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalConstants - g_Stats.NumUndocumentedConstants) / g_Stats.NumTotalConstants));
f:write("</td></tr>\n");
f:write("<tr><td>Hooks</td><td>", g_Stats.NumTotalHooks);
f:write("</td><td>", g_Stats.NumTotalHooks - g_Stats.NumUndocumentedHooks);
f:write("</td><td>", g_Stats.NumUndocumentedHooks);
f:write("</td><td>", ExportMeter(100 * (g_Stats.NumTotalHooks - g_Stats.NumUndocumentedHooks) / g_Stats.NumTotalHooks));
f:write("</td></tr>\n");
f:write([[
</table>
<p>There are ]], g_Stats.NumTrackedLinks, " internal links, ", g_Stats.NumInvalidLinks, " of them are invalid.</p>"
);
end
local function DumpAPIHtml(a_API)
LOG("Dumping all available functions and constants to API subfolder...");
-- Create the output folder
if not(cFile:IsFolder("API")) then
cFile:CreateFolder("API");
end
LOG("Copying static files..");
cFile:CreateFolder("API/Static");
local localFolder = g_Plugin:GetLocalFolder();
for _, fnam in ipairs(cFile:GetFolderContents(localFolder .. "/Static")) do
cFile:Delete("API/Static/" .. fnam);
cFile:Copy(localFolder .. "/Static/" .. fnam, "API/Static/" .. fnam);
end
-- Extract hook constants:
local Hooks = {};
local UndocumentedHooks = {};
for name, obj in pairs(cPluginManager) do
if (
(type(obj) == "number") and
name:match("HOOK_.*") and
(name ~= "HOOK_MAX") and
(name ~= "HOOK_NUM_HOOKS")
) then
table.insert(Hooks, { Name = name });
end
end
table.sort(Hooks,
function(Hook1, Hook2)
return (Hook1.Name < Hook2.Name);
end
);
ReadHooks(Hooks);
-- Create a "class index" file, write each class as a link to that file,
-- then dump class contents into class-specific file
LOG("Writing HTML files...");
local f, err = io.open("API/index.html", "w");
if (f == nil) then
LOGINFO("Cannot output HTML API: " .. err);
return;
end
-- Create a class navigation menu that will be inserted into each class file for faster navigation (#403)
local ClassMenuTab = {};
for _, cls in ipairs(a_API) do
table.insert(ClassMenuTab, "<a href='");
table.insert(ClassMenuTab, cls.Name);
table.insert(ClassMenuTab, ".html'>");
table.insert(ClassMenuTab, cls.Name);
table.insert(ClassMenuTab, "</a><br />");
end
local ClassMenu = table.concat(ClassMenuTab, "");
-- Create a hook navigation menu that will be inserted into each hook file for faster navigation(#403)
local HookNavTab = {};
for _, hook in ipairs(Hooks) do
table.insert(HookNavTab, "<a href='");
table.insert(HookNavTab, hook.DefaultFnName);
table.insert(HookNavTab, ".html'>");
table.insert(HookNavTab, (hook.Name:gsub("^HOOK_", ""))); -- remove the "HOOK_" part of the name
table.insert(HookNavTab, "</a><br />");
end
local HookNav = table.concat(HookNavTab, "");
-- Write the HTML file:
f:write([[<!DOCTYPE html>
<html>
<head>
<title>MCServer API - Index</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<div id="content">
<header>
<h1>MCServer API - Index</h1>
<hr />
</header>
<p>The API reference is divided into the following sections:</p>
<ul>
<li><a href="#articles">Articles</a></li>
<li><a href="#classes">Class index</a></li>
<li><a href="#hooks">Hooks</a></li>
<li><a href="#docstats">Documentation statistics</a></li>
</ul>
<hr />
]]);
WriteArticles(f);
WriteClasses(f, a_API, ClassMenu);
WriteHooks(f, Hooks, UndocumentedHooks, HookNav);
-- Copy the static files to the output folder:
local StaticFiles =
{
"main.css",
"prettify.js",
"prettify.css",
"lang-lua.js",
};
for _, fnam in ipairs(StaticFiles) do
cFile:Delete("API/" .. fnam);
cFile:Copy(g_Plugin:GetLocalFolder() .. "/" .. fnam, "API/" .. fnam);
end
-- List the documentation problems:
LOG("Listing leftovers...");
ListUndocumentedObjects(a_API, UndocumentedHooks);
ListUnexportedObjects();
ListMissingPages();
WriteStats(f);
f:write([[ </ul>
</div>
</body>
</html>]]);
f:close();
LOG("API subfolder written");
end
--- Returns the string with extra tabs and CR/LFs removed
local function CleanUpDescription(a_Desc)
-- Get rid of indent and newlines, normalize whitespace:
local res = a_Desc:gsub("[\n\t]", "")
res = a_Desc:gsub("%s%s+", " ")
-- Replace paragraph marks with newlines:
res = res:gsub("<p>", "\n")
res = res:gsub("</p>", "")
-- Replace list items with dashes:
res = res:gsub("</?ul>", "")
res = res:gsub("<li>", "\n - ")
res = res:gsub("</li>", "")
return res
end
--- Writes a list of methods into the specified file in ZBS format
local function WriteZBSMethods(f, a_Methods)
for _, func in ipairs(a_Methods or {}) do
f:write("\t\t\t[\"", func.Name, "\"] =\n")
f:write("\t\t\t{\n")
f:write("\t\t\t\ttype = \"method\",\n")
if ((func.Notes ~= nil) and (func.Notes ~= "")) then
f:write("\t\t\t\tdescription = [[", CleanUpDescription(func.Notes or ""), " ]],\n")
end
f:write("\t\t\t},\n")
end
end
--- Writes a list of constants into the specified file in ZBS format
local function WriteZBSConstants(f, a_Constants)
for _, cons in ipairs(a_Constants or {}) do
f:write("\t\t\t[\"", cons.Name, "\"] =\n")
f:write("\t\t\t{\n")
f:write("\t\t\t\ttype = \"value\",\n")
if ((cons.Desc ~= nil) and (cons.Desc ~= "")) then
f:write("\t\t\t\tdescription = [[", CleanUpDescription(cons.Desc or ""), " ]],\n")
end
f:write("\t\t\t},\n")
end
end
--- Writes one MCS class definition into the specified file in ZBS format
local function WriteZBSClass(f, a_Class)
assert(type(a_Class) == "table")
-- Write class header:
f:write("\t", a_Class.Name, " =\n\t{\n")
f:write("\t\ttype = \"class\",\n")
f:write("\t\tdescription = [[", CleanUpDescription(a_Class.Desc or ""), " ]],\n")
f:write("\t\tchilds =\n")
f:write("\t\t{\n")
-- Export methods and constants:
WriteZBSMethods(f, a_Class.Functions)
WriteZBSConstants(f, a_Class.Constants)
-- Finish the class definition:
f:write("\t\t},\n")
f:write("\t},\n\n")
end
--- Dumps the entire API table into a file in the ZBS format
local function DumpAPIZBS(a_API)
LOG("Dumping ZBS API description...")
local f, err = io.open("mcserver_api.lua", "w")
if (f == nil) then
LOG("Cannot open mcserver_lua.lua for writing, ZBS API will not be dumped. " .. err)
return
end
-- Write the file header:
f:write("-- This is a MCServer API file automatically generated by the APIDump plugin\n")
f:write("-- Note that any manual changes will be overwritten by the next dump\n\n")
f:write("return {\n")
-- Export each class except Globals, store those aside:
local Globals
for _, cls in ipairs(a_API) do
if (cls.Name ~= "Globals") then
WriteZBSClass(f, cls)
else
Globals = cls
end
end
-- Export the globals:
if (Globals) then
WriteZBSMethods(f, Globals.Functions)
WriteZBSConstants(f, Globals.Constants)
end
-- Finish the file:
f:write("}\n")
f:close()
LOG("ZBS API dumped...")
end
--- Returns true if a_Descendant is declared to be a (possibly indirect) descendant of a_Base
local function IsDeclaredDescendant(a_DescendantName, a_BaseName, a_API)
-- Check params:
assert(type(a_DescendantName) == "string")
assert(type(a_BaseName) == "string")
assert(type(a_API) == "table")
if not(a_API[a_BaseName]) then
return false
end
assert(type(a_API[a_BaseName]) == "table", "Not a class name: " .. a_BaseName)
assert(type(a_API[a_BaseName].Descendants) == "table")
-- Check direct inheritance:
for _, desc in ipairs(a_API[a_BaseName].Descendants) do
if (desc.Name == a_DescendantName) then
return true
end
end -- for desc - a_BaseName's descendants
-- Check indirect inheritance:
for _, desc in ipairs(a_API[a_BaseName].Descendants) do
if (IsDeclaredDescendant(a_DescendantName, desc.Name, a_API)) then
return true
end
end -- for desc - a_BaseName's descendants
return false
end
--- Checks the specified class' inheritance
-- Reports any problems as new items in the a_Report table
local function CheckClassInheritance(a_Class, a_API, a_Report)
-- Check params:
assert(type(a_Class) == "table")
assert(type(a_API) == "table")
assert(type(a_Report) == "table")
-- Check that the declared descendants are really descendants:
local registry = debug.getregistry()
for _, desc in ipairs(a_Class.Descendants or {}) do
local isParent = false
local parents = registry["tolua_super"][_G[desc.Name]]
if not(parents[a_Class.Name]) then
table.insert(a_Report, desc.Name .. " is not a descendant of " .. a_Class.Name)
end
end -- for desc - a_Class.Descendants[]
-- Check that all inheritance is listed for the class:
local parents = registry["tolua_super"][_G[a_Class.Name]] -- map of "classname" -> true for each class that a_Class inherits
for clsName, isParent in pairs(parents or {}) do
if ((clsName ~= "") and not(clsName:match("const .*"))) then
if not(IsDeclaredDescendant(a_Class.Name, clsName, a_API)) then
table.insert(a_Report, a_Class.Name .. " inherits from " .. clsName .. " but this isn't documented")
end
end
end
end
--- Checks each class's declared inheritance versus the actual inheritance
local function CheckAPIDescendants(a_API)
-- Check each class:
local report = {}
for _, cls in ipairs(a_API) do
if (cls.Name ~= "Globals") then
CheckClassInheritance(cls, a_API, report)
end
end
-- If there's anything to report, output it to a file:
if (report[1] ~= nil) then
LOG("There are inheritance errors in the API description:")
for _, msg in ipairs(report) do
LOG(" " .. msg)
end
local f, err = io.open("API/_inheritance_errors.txt", "w")
if (f == nil) then
LOG("Cannot report inheritance problems to a file: " .. tostring(err))
return
end
f:write(table.concat(report, "\n"))
f:close()
end
end
local function DumpApi()
LOG("Dumping the API...")
-- Load the API descriptions from the Classes and Hooks subfolders:
-- This needs to be done each time the command is invoked because the export modifies the tables' contents
dofile(g_PluginFolder .. "/APIDesc.lua")
if (g_APIDesc.Classes == nil) then
g_APIDesc.Classes = {};
end
if (g_APIDesc.Hooks == nil) then
g_APIDesc.Hooks = {};
end
LoadAPIFiles("/Classes/", g_APIDesc.Classes);
LoadAPIFiles("/Hooks/", g_APIDesc.Hooks);
-- Reset the stats:
g_TrackedPages = {}; -- List of tracked pages, to be checked later whether they exist. Each item is an array of referring pagenames.
g_Stats = -- Statistics about the documentation
{
NumTotalClasses = 0,
NumUndocumentedClasses = 0,
NumTotalFunctions = 0,
NumUndocumentedFunctions = 0,
NumTotalConstants = 0,
NumUndocumentedConstants = 0,
NumTotalVariables = 0,
NumUndocumentedVariables = 0,
NumTotalHooks = 0,
NumUndocumentedHooks = 0,
NumTrackedLinks = 0,
NumInvalidLinks = 0,
}
-- Create the API tables:
local API, Globals = CreateAPITables();
-- Sort the classes by name:
table.sort(API,
function (c1, c2)
return (string.lower(c1.Name) < string.lower(c2.Name));
end
);
g_Stats.NumTotalClasses = #API;
-- Add Globals into the API:
Globals.Name = "Globals";
table.insert(API, Globals);
-- Read in the descriptions:
LOG("Reading descriptions...");
ReadDescriptions(API);
-- Check that the API lists the inheritance properly, report any problems to a file:
CheckAPIDescendants(API)
-- Dump all available API objects in HTML format into a subfolder:
DumpAPIHtml(API);
-- Dump all available API objects in format used by ZeroBraneStudio API descriptions:
DumpAPIZBS(API)
LOG("APIDump finished");
return true
end
local function HandleWebAdminDump(a_Request)
if (a_Request.PostParams["Dump"] ~= nil) then
DumpApi()
end
return
[[
<p>Pressing the button will generate the API dump on the server. Note that this can take some time.</p>
<form method="POST"><input type="submit" name="Dump" value="Dump the API"/></form>
]]
end
local function HandleCmdApi(a_Split)
DumpApi()
return true
end
function Initialize(Plugin)
g_Plugin = Plugin;
g_PluginFolder = Plugin:GetLocalFolder();
LOG("Initialising " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
-- Bind a console command to dump the API:
cPluginManager:BindConsoleCommand("api", HandleCmdApi, "Dumps the Lua API docs into the API/ subfolder")
-- Add a WebAdmin tab that has a Dump button
g_Plugin:AddWebTab("APIDump", HandleWebAdminDump)
return true
end
| jammet/MCServer | MCServer/Plugins/APIDump/main_APIDump.lua | Lua | apache-2.0 | 50,162 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/glue/model/TaskStatusType.h>
#include <aws/glue/model/TaskRunProperties.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Glue
{
namespace Model
{
class AWS_GLUE_API GetMLTaskRunResult
{
public:
GetMLTaskRunResult();
GetMLTaskRunResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetMLTaskRunResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The unique identifier of the task run.</p>
*/
inline const Aws::String& GetTransformId() const{ return m_transformId; }
/**
* <p>The unique identifier of the task run.</p>
*/
inline void SetTransformId(const Aws::String& value) { m_transformId = value; }
/**
* <p>The unique identifier of the task run.</p>
*/
inline void SetTransformId(Aws::String&& value) { m_transformId = std::move(value); }
/**
* <p>The unique identifier of the task run.</p>
*/
inline void SetTransformId(const char* value) { m_transformId.assign(value); }
/**
* <p>The unique identifier of the task run.</p>
*/
inline GetMLTaskRunResult& WithTransformId(const Aws::String& value) { SetTransformId(value); return *this;}
/**
* <p>The unique identifier of the task run.</p>
*/
inline GetMLTaskRunResult& WithTransformId(Aws::String&& value) { SetTransformId(std::move(value)); return *this;}
/**
* <p>The unique identifier of the task run.</p>
*/
inline GetMLTaskRunResult& WithTransformId(const char* value) { SetTransformId(value); return *this;}
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline const Aws::String& GetTaskRunId() const{ return m_taskRunId; }
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline void SetTaskRunId(const Aws::String& value) { m_taskRunId = value; }
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline void SetTaskRunId(Aws::String&& value) { m_taskRunId = std::move(value); }
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline void SetTaskRunId(const char* value) { m_taskRunId.assign(value); }
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline GetMLTaskRunResult& WithTaskRunId(const Aws::String& value) { SetTaskRunId(value); return *this;}
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline GetMLTaskRunResult& WithTaskRunId(Aws::String&& value) { SetTaskRunId(std::move(value)); return *this;}
/**
* <p>The unique run identifier associated with this run.</p>
*/
inline GetMLTaskRunResult& WithTaskRunId(const char* value) { SetTaskRunId(value); return *this;}
/**
* <p>The status for this task run.</p>
*/
inline const TaskStatusType& GetStatus() const{ return m_status; }
/**
* <p>The status for this task run.</p>
*/
inline void SetStatus(const TaskStatusType& value) { m_status = value; }
/**
* <p>The status for this task run.</p>
*/
inline void SetStatus(TaskStatusType&& value) { m_status = std::move(value); }
/**
* <p>The status for this task run.</p>
*/
inline GetMLTaskRunResult& WithStatus(const TaskStatusType& value) { SetStatus(value); return *this;}
/**
* <p>The status for this task run.</p>
*/
inline GetMLTaskRunResult& WithStatus(TaskStatusType&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline const Aws::String& GetLogGroupName() const{ return m_logGroupName; }
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline void SetLogGroupName(const Aws::String& value) { m_logGroupName = value; }
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline void SetLogGroupName(Aws::String&& value) { m_logGroupName = std::move(value); }
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline void SetLogGroupName(const char* value) { m_logGroupName.assign(value); }
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithLogGroupName(const Aws::String& value) { SetLogGroupName(value); return *this;}
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithLogGroupName(Aws::String&& value) { SetLogGroupName(std::move(value)); return *this;}
/**
* <p>The names of the log groups that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithLogGroupName(const char* value) { SetLogGroupName(value); return *this;}
/**
* <p>The list of properties that are associated with the task run.</p>
*/
inline const TaskRunProperties& GetProperties() const{ return m_properties; }
/**
* <p>The list of properties that are associated with the task run.</p>
*/
inline void SetProperties(const TaskRunProperties& value) { m_properties = value; }
/**
* <p>The list of properties that are associated with the task run.</p>
*/
inline void SetProperties(TaskRunProperties&& value) { m_properties = std::move(value); }
/**
* <p>The list of properties that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithProperties(const TaskRunProperties& value) { SetProperties(value); return *this;}
/**
* <p>The list of properties that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithProperties(TaskRunProperties&& value) { SetProperties(std::move(value)); return *this;}
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline const Aws::String& GetErrorString() const{ return m_errorString; }
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline void SetErrorString(const Aws::String& value) { m_errorString = value; }
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline void SetErrorString(Aws::String&& value) { m_errorString = std::move(value); }
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline void SetErrorString(const char* value) { m_errorString.assign(value); }
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithErrorString(const Aws::String& value) { SetErrorString(value); return *this;}
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithErrorString(Aws::String&& value) { SetErrorString(std::move(value)); return *this;}
/**
* <p>The error strings that are associated with the task run.</p>
*/
inline GetMLTaskRunResult& WithErrorString(const char* value) { SetErrorString(value); return *this;}
/**
* <p>The date and time when this task run started.</p>
*/
inline const Aws::Utils::DateTime& GetStartedOn() const{ return m_startedOn; }
/**
* <p>The date and time when this task run started.</p>
*/
inline void SetStartedOn(const Aws::Utils::DateTime& value) { m_startedOn = value; }
/**
* <p>The date and time when this task run started.</p>
*/
inline void SetStartedOn(Aws::Utils::DateTime&& value) { m_startedOn = std::move(value); }
/**
* <p>The date and time when this task run started.</p>
*/
inline GetMLTaskRunResult& WithStartedOn(const Aws::Utils::DateTime& value) { SetStartedOn(value); return *this;}
/**
* <p>The date and time when this task run started.</p>
*/
inline GetMLTaskRunResult& WithStartedOn(Aws::Utils::DateTime&& value) { SetStartedOn(std::move(value)); return *this;}
/**
* <p>The date and time when this task run was last modified.</p>
*/
inline const Aws::Utils::DateTime& GetLastModifiedOn() const{ return m_lastModifiedOn; }
/**
* <p>The date and time when this task run was last modified.</p>
*/
inline void SetLastModifiedOn(const Aws::Utils::DateTime& value) { m_lastModifiedOn = value; }
/**
* <p>The date and time when this task run was last modified.</p>
*/
inline void SetLastModifiedOn(Aws::Utils::DateTime&& value) { m_lastModifiedOn = std::move(value); }
/**
* <p>The date and time when this task run was last modified.</p>
*/
inline GetMLTaskRunResult& WithLastModifiedOn(const Aws::Utils::DateTime& value) { SetLastModifiedOn(value); return *this;}
/**
* <p>The date and time when this task run was last modified.</p>
*/
inline GetMLTaskRunResult& WithLastModifiedOn(Aws::Utils::DateTime&& value) { SetLastModifiedOn(std::move(value)); return *this;}
/**
* <p>The date and time when this task run was completed.</p>
*/
inline const Aws::Utils::DateTime& GetCompletedOn() const{ return m_completedOn; }
/**
* <p>The date and time when this task run was completed.</p>
*/
inline void SetCompletedOn(const Aws::Utils::DateTime& value) { m_completedOn = value; }
/**
* <p>The date and time when this task run was completed.</p>
*/
inline void SetCompletedOn(Aws::Utils::DateTime&& value) { m_completedOn = std::move(value); }
/**
* <p>The date and time when this task run was completed.</p>
*/
inline GetMLTaskRunResult& WithCompletedOn(const Aws::Utils::DateTime& value) { SetCompletedOn(value); return *this;}
/**
* <p>The date and time when this task run was completed.</p>
*/
inline GetMLTaskRunResult& WithCompletedOn(Aws::Utils::DateTime&& value) { SetCompletedOn(std::move(value)); return *this;}
/**
* <p>The amount of time (in seconds) that the task run consumed resources.</p>
*/
inline int GetExecutionTime() const{ return m_executionTime; }
/**
* <p>The amount of time (in seconds) that the task run consumed resources.</p>
*/
inline void SetExecutionTime(int value) { m_executionTime = value; }
/**
* <p>The amount of time (in seconds) that the task run consumed resources.</p>
*/
inline GetMLTaskRunResult& WithExecutionTime(int value) { SetExecutionTime(value); return *this;}
private:
Aws::String m_transformId;
Aws::String m_taskRunId;
TaskStatusType m_status;
Aws::String m_logGroupName;
TaskRunProperties m_properties;
Aws::String m_errorString;
Aws::Utils::DateTime m_startedOn;
Aws::Utils::DateTime m_lastModifiedOn;
Aws::Utils::DateTime m_completedOn;
int m_executionTime;
};
} // namespace Model
} // namespace Glue
} // namespace Aws
| cedral/aws-sdk-cpp | aws-cpp-sdk-glue/include/aws/glue/model/GetMLTaskRunResult.h | C | apache-2.0 | 11,893 |
using MatrixApi.Domain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace MatrixPhone.DataModel
{
public static class UserDataSource
{
public static User user = new User();
public static User GetUser() {
return user;
}
public static async void Login(string Email, string Password)
{
user.Email = Email;
user.Password = Password;
var httpClient = new appHttpClient();
var response = await httpClient.GetAsync("Users");
try
{
response.EnsureSuccessStatusCode(); // Throw on error code.
} catch {
user = new User();
}
var result = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<User>(result);
}
public static string Auth()
{
var authText = string.Format("{0}:{1}", user.Email, user.Password);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(authText));
}
}
}
| jdehlin/MatrixApi | MatrixPhone/DataModel/UserDataSource.cs | C# | apache-2.0 | 1,203 |
// svgmap.js 0.2.0
//
// Copyright (c) 2014 jalal @ gnomedia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
var SvgMap = function (opts) {
/*global Snap:false, console:false */
'use strict';
console.log("SvgMap initializing");
var defaults = {
svgid: '',
mapurl: '',
mapid: '',
coordsurl: '',
hoverFill: '#fff',
strokeColor: '#000',
resultid: 'results'
};
var svgid = opts.svgid || defaults.svgid,
mapurl = opts.mapurl || defaults.mapurl,
mapid = opts.mapid || defaults.mapid,
coordsurl = opts.coordsurl || defaults.coordsurl,
strokeColor = opts.strokeColor || defaults.strokeColor,
hoverFill = opts.hoverFill || defaults.hoverFill,
resultid = opts.resultid || defaults.resultid;
var i, w, h, areas, pre;
var s = new Snap(svgid);
var group = s.group();
Snap.load(mapurl, function (f) {
i = f.select('image');
h = i.attr('height');
w = i.attr('width');
group.append(f);
s.attr({
viewBox: [0, 0, w, h]
});
var newmap = document.getElementById('newmap');
if (newmap) {
newmap.style.height = h + 'px';
newmap.style.maxWidth = w + 'px';
}
});
var shadow = new Snap(svgid);
areas = document.getElementsByTagName('area');
var area;
for (var j = areas.length - 1; j >= 0; j--) {
area = areas[j];
// console.log("Coord: " + area.coords);
var coords = area.coords.split(',');
var path = 'M ';
if (coords.length) {
for (var k = 0; k < coords.length; k += 2) {
if (!k) {pre = ''; } else {pre = ' L '; }
path += pre + coords[k] + ',' + coords[k + 1];
}
}
var p = new Snap();
var el = p.path(path);
el.attr({ id: area.title, fill: 'none', stroke: strokeColor, link: area.href, d: path, title: area.title});
el.hover(function () {
this.attr('fill', hoverFill);
}, function () {
this.attr('fill', 'transparent');
});
el.click(function () {
// console.log('click: ' + this.attr('id'));
hideAll();
show('Clicked: ' + this.attr('id'));
});
el.touchstart(function () {
console.log('touch: ' + this.attr('id'));
this.attr('fill', hoverFill);
hideAll();
show('Touched: ' + this.attr('id'));
});
el.touchend(function () {
this.attr('fill', 'transparent');
});
shadow.append(el);
}
function hideAll() {
var el = document.getElementById(resultid);
if (el) {el.style.display = "none"; }
// $(resultid).hide();
}
function show(txt) {
var el = document.getElementById(resultid);
if (el) {
el.style.display = "";
if (el.firstChild) {
el.removeChild(el.firstChild);
}
var t = document.createTextNode(txt);
el.appendChild(t);
}
}
};
| jalal/svgmap | js/svgmap.js | JavaScript | apache-2.0 | 3,661 |
package com.yezi.text.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import com.yezi.text.activity.AdapterSampleActivity;
import com.yezi.text.activity.AnimatorSampleActivity;
import com.yezi.text.R;
public class MyRecycleview extends AppCompatActivity {
private boolean enabledGrid = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycycleview);
findViewById(R.id.btn_animator_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AnimatorSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
findViewById(R.id.btn_adapter_sample).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MyRecycleview.this, AdapterSampleActivity.class);
i.putExtra("GRID", enabledGrid);
startActivity(i);
}
});
((SwitchCompat) findViewById(R.id.grid)).setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enabledGrid = isChecked;
}
});
}
}
| qwertyezi/Test | text/app/src/main/java/com/yezi/text/widget/MyRecycleview.java | Java | apache-2.0 | 1,720 |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.datalint.open.shared.xml;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import com.datalint.open.shared.xml.impl.XMLParserImpl;
/**
* This class represents the client interface to XML parsing.
*/
public class XMLParser {
private static final XMLParserImpl impl = XMLParserImpl.getInstance();
/**
* This method creates a new document, to be manipulated by the DOM API.
*
* @return the newly created document
*/
public static Document createDocument() {
return impl.createDocument();
}
/**
* This method parses a new document from the supplied string, throwing a
* <code>DOMParseException</code> if the parse fails.
*
* @param contents the String to be parsed into a <code>Document</code>
* @return the newly created <code>Document</code>
*/
public static Document parse(String contents) {
return impl.parse(contents);
}
// Update on 2020-05-10, does not work with XPath.
public static Document parseReadOnly(String contents) {
return impl.parseReadOnly(contents);
}
/**
* This method removes all <code>Text</code> nodes which are made up of only
* white space.
*
* @param n the node which is to have all of its whitespace descendents removed.
*/
public static void removeWhitespace(Node n) {
removeWhitespaceInner(n, null);
}
/**
* This method determines whether the browser supports {@link CDATASection} as
* distinct entities from <code>Text</code> nodes.
*
* @return true if the browser supports {@link CDATASection}, otherwise
* <code>false</code>.
*/
public static boolean supportsCDATASection() {
return impl.supportsCDATASection();
}
/*
* The inner recursive method for removeWhitespace
*/
private static void removeWhitespaceInner(Node n, Node parent) {
// This n is removed from the parent if n is a whitespace node
if (parent != null && n instanceof Text && (!(n instanceof CDATASection))) {
Text t = (Text) n;
if (t.getData().matches("[ \t\n]*")) {
parent.removeChild(t);
}
}
if (n.hasChildNodes()) {
int length = n.getChildNodes().getLength();
List<Node> toBeProcessed = new ArrayList<Node>();
// We collect all the nodes to iterate as the child nodes will
// change upon removal
for (int i = 0; i < length; i++) {
toBeProcessed.add(n.getChildNodes().item(i));
}
// This changes the child nodes, but the iterator of nodes never
// changes meaning that this is safe
for (Node childNode : toBeProcessed) {
removeWhitespaceInner(childNode, n);
}
}
}
/**
* Not instantiable.
*/
private XMLParser() {
}
}
| datalint/open | Open/src/main/java/com/datalint/open/shared/xml/XMLParser.java | Java | apache-2.0 | 3,302 |
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.api;
import static org.assertj.core.util.Lists.newArrayList;
import org.junit.Rule;
import org.junit.Test;
public class JUnitBDDSoftAssertionsSuccessTest {
@Rule
public final JUnitBDDSoftAssertions softly = new JUnitBDDSoftAssertions();
@Test
public void all_assertions_should_pass() throws Throwable {
softly.then(1).isEqualTo(1);
softly.then(newArrayList(1, 2)).containsOnly(1, 2);
}
}
| dorzey/assertj-core | src/test/java/org/assertj/core/api/JUnitBDDSoftAssertionsSuccessTest.java | Java | apache-2.0 | 1,039 |
(function () {
'use strict';
app.service('reportService', reportService);
function reportService($http, $window, $interval, timeAgo, restCall, queryService, dashboardFactory, ngAuthSettings, reportServiceUrl) {
var populateReport = function (report, url) {
function successCallback(response) {
if (response.data.data.length === 0) {
report.status = 'EMPTY'
} else {
report.status = 'SUCCESS';
report.data = response.data.data;
report.getTotal();
console.log(report);
}
}
function errorCallback(error) {
console.log(error);
this.status = 'FAILED';
}
restCall('GET', url, null, successCallback, errorCallback)
}
var getReport = function () {
return {
data: {},
searchParam : {
startdate: null,
enddate: null,
type: "ENTERPRISE",
generateexcel: false,
userid: null,
username: null
},
total : {
totalVendor: 0,
totalDelivery: 0,
totalPending: 0,
totalInProgress: 0,
totalCompleted: 0,
totalCancelled: 0,
totalProductPrice: 0,
totalDeliveryCharge: 0
},
getTotal: function () {
var itSelf = this;
itSelf.total.totalVendor = 0;
itSelf.total.totalDelivery = 0;
itSelf.total.totalPending = 0;
itSelf.total.totalInProgress = 0;
itSelf.total.totalCompleted = 0;
itSelf.total.totalCancelled = 0;
itSelf.total.totalProductPrice = 0;
itSelf.total.totalDeliveryCharge = 0;
angular.forEach(this.data, function (value, key) {
itSelf.total.totalVendor += 1;
itSelf.total.totalDelivery += value.TotalDelivery;
itSelf.total.totalPending += value.TotalPending;
itSelf.total.totalInProgress += value.TotalInProgress;
itSelf.total.totalCompleted += value.TotalCompleted;
itSelf.total.totalCancelled += value.TotalCancelled;
itSelf.total.totalProductPrice += value.TotalProductPrice;
itSelf.total.totalDeliveryCharge += value.TotalDeliveryCharge;
});
console.log(this.total)
},
getUrl: function () {
// FIXME: need to be refactored
if (this.searchParam.type === "BIKE_MESSENGER") {
return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type;
}
return reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type;
},
getReport: function () {
var reportUrl = this.getUrl();
this.status = 'IN_PROGRESS';
populateReport(this, reportUrl);
},
goToReportJobs : function (user) {
console.log(user)
console.log(this.data)
if (this.searchParam.type === "BIKE_MESSENGER") {
$window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate +
"&usertype=BIKE_MESSENGER" + "&userid=" + this.data[user].UserId, '_blank');
} else {
$window.open("#/report/jobs?" + "startdate=" + this.searchParam.startdate + "&enddate="+ this.searchParam.enddate + "&usertype=" + this.searchParam.type + "&username=" + user, '_blank');
}
},
exportExcel : function () {
var excelReportUrl = reportServiceUrl + "api/report?startdate="+this.searchParam.startdate+"&enddate="+this.searchParam.enddate+"&usertype="+this.searchParam.type + "&generateexcel=true";
$window.open(excelReportUrl, '_blank');
},
status : 'NONE'
}
}
return {
getReport: getReport
}
}
})();
| NerdCats/T-Rex | app/services/reportService.js | JavaScript | apache-2.0 | 3,588 |
/*******************************************************************************
* Copyright 2013-2015 alladin-IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package at.alladin.rmbt.controlServer;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.naming.NamingException;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.engine.header.Header;
import org.restlet.representation.Representation;
import org.restlet.resource.Options;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import at.alladin.rmbt.db.DbConnection;
import at.alladin.rmbt.shared.ResourceManager;
import at.alladin.rmbt.util.capability.Capabilities;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class ServerResource extends org.restlet.resource.ServerResource
{
protected Connection conn;
protected ResourceBundle labels;
protected ResourceBundle settings;
protected Capabilities capabilities = new Capabilities();
public static class MyDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime>
{
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context)
{
return new JsonPrimitive(src.toString());
}
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
public void readCapabilities(final JSONObject request) throws JSONException {
if (request != null) {
if (request.has("capabilities")) {
capabilities = new Gson().fromJson(request.get("capabilities").toString(), Capabilities.class);
}
}
}
public static Gson getGson(boolean prettyPrint)
{
GsonBuilder gb = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new MyDateTimeAdapter());
if (prettyPrint)
gb = gb.setPrettyPrinting();
return gb.create();
}
@Override
public void doInit() throws ResourceException
{
super.doInit();
settings = ResourceManager.getCfgBundle();
// Set default Language for System
Locale.setDefault(new Locale(settings.getString("RMBT_DEFAULT_LANGUAGE")));
labels = ResourceManager.getSysMsgBundle();
try {
if (getQuery().getNames().contains("capabilities")) {
capabilities = new Gson().fromJson(getQuery().getValues("capabilities"), Capabilities.class);
}
} catch (final Exception e) {
e.printStackTrace();
}
// Get DB-Connection
try
{
conn = DbConnection.getConnection();
}
catch (final NamingException e)
{
e.printStackTrace();
}
catch (final SQLException e)
{
System.out.println(labels.getString("ERROR_DB_CONNECTION_FAILED"));
e.printStackTrace();
}
}
@Override
protected void doRelease() throws ResourceException
{
try
{
if (conn != null)
conn.close();
}
catch (final SQLException e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
protected void addAllowOrigin()
{
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Series<>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
responseHeaders.add("Access-Control-Allow-Credentials", "false");
responseHeaders.add("Access-Control-Max-Age", "60");
}
@Options
public void doOptions(final Representation entity)
{
addAllowOrigin();
}
@SuppressWarnings("unchecked")
public String getIP()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realIp = headers.getFirstValue("X-Real-IP", true);
if (realIp != null)
return realIp;
else
return getRequest().getClientInfo().getAddress();
}
@SuppressWarnings("unchecked")
public Reference getURL()
{
final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
final String realURL = headers.getFirstValue("X-Real-URL", true);
if (realURL != null)
return new Reference(realURL);
else
return getRequest().getOriginalRef();
}
protected String getSetting(String key, String lang)
{
if (conn == null)
return null;
try (final PreparedStatement st = conn.prepareStatement(
"SELECT value"
+ " FROM settings"
+ " WHERE key=? AND (lang IS NULL OR lang = ?)"
+ " ORDER BY lang NULLS LAST LIMIT 1");)
{
st.setString(1, key);
st.setString(2, lang);
try (final ResultSet rs = st.executeQuery();)
{
if (rs != null && rs.next())
return rs.getString("value");
}
return null;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
}
}
| alladin-IT/open-rmbt | RMBTControlServer/src/at/alladin/rmbt/controlServer/ServerResource.java | Java | apache-2.0 | 7,059 |
package io.github.marktony.reader.qsbk;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import io.github.marktony.reader.R;
import io.github.marktony.reader.adapter.QsbkArticleAdapter;
import io.github.marktony.reader.data.Qiushibaike;
import io.github.marktony.reader.interfaze.OnRecyclerViewClickListener;
import io.github.marktony.reader.interfaze.OnRecyclerViewLongClickListener;
/**
* Created by Lizhaotailang on 2016/8/4.
*/
public class QsbkFragment extends Fragment
implements QsbkContract.View {
private QsbkContract.Presenter presenter;
private QsbkArticleAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
public QsbkFragment() {
// requires empty constructor
}
public static QsbkFragment newInstance(int page) {
return new QsbkFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_list_fragment, container, false);
initViews(view);
presenter.loadArticle(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.loadArticle(true);
adapter.notifyDataSetChanged();
if (refreshLayout.isRefreshing()){
refreshLayout.setRefreshing(false);
}
}
});
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
boolean isSlidingToLast = false;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
// 当不滚动时
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 获取最后一个完全显示的itemposition
int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
int totalItemCount = manager.getItemCount();
// 判断是否滚动到底部并且是向下滑动
if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
presenter.loadMore();
}
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
isSlidingToLast = dy > 0;
}
});
return view;
}
@Override
public void setPresenter(QsbkContract.Presenter presenter) {
if (presenter != null) {
this.presenter = presenter;
}
}
@Override
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.qsbk_rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
}
@Override
public void showResult(ArrayList<Qiushibaike.Item> articleList) {
if (adapter == null) {
adapter = new QsbkArticleAdapter(getActivity(), articleList);
recyclerView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.setOnItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void OnClick(View v, int position) {
presenter.shareTo(position);
}
});
adapter.setOnItemLongClickListener(new OnRecyclerViewLongClickListener() {
@Override
public void OnLongClick(View view, int position) {
presenter.copyToClipboard(position);
}
});
}
@Override
public void startLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}
@Override
public void stopLoading() {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
}
});
}
@Override
public void showLoadError() {
Snackbar.make(recyclerView, "加载失败", Snackbar.LENGTH_SHORT)
.setAction("重试", new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadArticle(false);
}
}).show();
}
@Override
public void onResume() {
super.onResume();
presenter.start();
}
}
| HeJianF/iReader | app/src/main/java/io/github/marktony/reader/qsbk/QsbkFragment.java | Java | apache-2.0 | 5,506 |
package org.gradle.test.performance.mediummonolithicjavaproject.p428;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8570 {
Production8570 objectUnderTest = new Production8570();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p428/Test8570.java | Java | apache-2.0 | 2,111 |
var array = trace ( new Array());
var m = trace ( 0 );
var n = trace ( 3 );
var o = trace ( 5 );
var p = trace ( 7 );
array[0] = m;
array[1] = n;
array[2] = o;
array[3] = p;
var result = new Array();
// FOR-IN Schleife
for ( i in array ) {
result.push(i);
x = i;
z = 7;
}
var a = result;
var b = result[0];
var c = 7;
var d = x; | keil/TbDA | test/dependency_state/rule_forin.js | JavaScript | apache-2.0 | 360 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.management.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.InternalCacheForClientAccess;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.management.ManagementService;
/**
* Super class to all Management Service
*
* @since GemFire 7.0
*/
public abstract class BaseManagementService extends ManagementService {
private static final Logger logger = LogService.getLogger();
/**
* The main mapping between different resources and Service instance Object can be Cache
*/
@MakeNotStatic
protected static final Map<Object, BaseManagementService> instances =
new HashMap<Object, BaseManagementService>();
/** List of connected <code>DistributedSystem</code>s */
@MakeNotStatic
private static final List<InternalDistributedSystem> systems =
new ArrayList<InternalDistributedSystem>(1);
/** Protected constructor. */
protected BaseManagementService() {}
// Static block to initialize the ConnectListener on the System
static {
initInternalDistributedSystem();
}
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract void close();
/**
* This method will close the service. Any operation on the service instance will throw exception
*/
protected abstract boolean isClosed();
/**
* Returns a ManagementService to use for the specified Cache.
*
* @param cache defines the scope of resources to be managed
*/
public static ManagementService getManagementService(InternalCacheForClientAccess cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache);
if (service == null) {
service = SystemManagementService.newSystemManagementService(cache);
instances.put(cache, service);
}
return service;
}
}
public static ManagementService getExistingManagementService(InternalCache cache) {
synchronized (instances) {
BaseManagementService service = instances.get(cache.getCacheForProcessingClientRequests());
return service;
}
}
/**
* Initialises the distributed system listener
*/
private static void initInternalDistributedSystem() {
synchronized (instances) {
// Initialize our own list of distributed systems via a connect listener
@SuppressWarnings("unchecked")
List<InternalDistributedSystem> existingSystems = InternalDistributedSystem
.addConnectListener(new InternalDistributedSystem.ConnectListener() {
@Override
public void onConnect(InternalDistributedSystem sys) {
addInternalDistributedSystem(sys);
}
});
// While still holding the lock on systems, add all currently known
// systems to our own list
for (InternalDistributedSystem sys : existingSystems) {
try {
if (sys.isConnected()) {
addInternalDistributedSystem(sys);
}
} catch (DistributedSystemDisconnectedException e) {
if (logger.isDebugEnabled()) {
logger.debug("DistributedSystemDisconnectedException {}", e.getMessage(), e);
}
}
}
}
}
/**
* Add an Distributed System and adds a Discon Listener
*/
private static void addInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
sys.addDisconnectListener(new InternalDistributedSystem.DisconnectListener() {
@Override
public String toString() {
return "Disconnect listener for BaseManagementService";
}
@Override
public void onDisconnect(InternalDistributedSystem ss) {
removeInternalDistributedSystem(ss);
}
});
systems.add(sys);
}
}
/**
* Remove a Distributed System from the system lists. If list is empty it closes down all the
* services if not closed
*/
private static void removeInternalDistributedSystem(InternalDistributedSystem sys) {
synchronized (instances) {
systems.remove(sys);
if (systems.isEmpty()) {
for (Object key : instances.keySet()) {
BaseManagementService service = (BaseManagementService) instances.get(key);
try {
if (!service.isClosed()) {
// Service close method should take care of the cleaning up
// activities
service.close();
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("ManagementException while removing InternalDistributedSystem {}",
e.getMessage(), e);
}
}
}
instances.clear();
}
}
}
}
| davebarnes97/geode | geode-core/src/main/java/org/apache/geode/management/internal/BaseManagementService.java | Java | apache-2.0 | 5,962 |
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.adapter.okhttp.extractor;
import okhttp3.Connection;
import okhttp3.Request;
/**
* @author zhaoyuguang
*/
public class DefaultOkHttpResourceExtractor implements OkHttpResourceExtractor {
@Override
public String extract(Request request, Connection connection) {
return request.method() + ":" + request.url().toString();
}
}
| alibaba/Sentinel | sentinel-adapter/sentinel-okhttp-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/okhttp/extractor/DefaultOkHttpResourceExtractor.java | Java | apache-2.0 | 997 |
'use strict'
/*eslint-env node */
exports.config = {
specs: [
'test/e2e/**/*.js'
],
baseUrl: 'http://localhost:9000',
chromeOnly: true
}
| musamusa/move | protractor.conf.js | JavaScript | apache-2.0 | 150 |
---
title: Fall's Fabulous Floral, Fruit, and Foliage Finery
date: 2014-10-13 00:00:00 -06:00
categories:
- whats-blooming
layout: post
blog-banner: whats-blooming-now-fall.jpg
post-date: October 13, 2014
post-time: 2:32 PM
blog-image: wbn-default.jpg
---
<div class="text-center">Fall weather brings about a fabulous display throughout the Garden. Many of our plants are creating a show not only with their flowers, but with their fruits and leaves as well. Be sure to take heed of the cool autumn air as it beckons you to the Garden!</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x377xRudbeckia,P20fulgida,P20var.,P20sullivantii,P20,P27Goldstrum,P27,P20Fall,P20Flower,P20Fruit,P20SQS12.jpg.pagespeed.ic.f1uSSoBXkl.jpg" width="560" height="377" alt="" title="" />
<p>Black-Eyed Susan <i> Rudbeckia fulgida</i> var. <i>sullivantii </i> 'Goldstrum'</p>
<p>Bright yellow petals adorn this perennial in the summer, but fall has given this sturdy flower a more manila appearance.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x718xDianthus,P20chinensis,P20,P27Baby,P20Doll,P27,P20Flower,P20SQS14.jpg.pagespeed.ic.NulNQJ865H.jpg" width="560" height="718" alt="" title="" />
<p>Baby Doll Dianthus <i>Dianthus chinensis</i> 'Baby Doll'</p>
<p>This diminutive Dianthus displays blooms that range from a deep rose pink to a bright white and about every shade in between.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x804xDelphinium,P20elatum,P20,P27Royal,P20Aspirations,P27,P20Flower,P20SQS14.jpg.pagespeed.ic.HiSf5VqLN4.jpg" width="560" height="804" alt="" title="" />
<p>Candle Larkspur <i> Delphinium elatum</i> 'Royal Aspirations'</p>
<p>Bold spikes of purple-blue are complemented with white centers on this dense-flowering larkspur.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x712xDatura,P20wrightii,P20Fruit,P20SQS14.jpg.pagespeed.ic.XnicWsL0jE.jpg" width="560" height="712" alt="" title="" />
<p>Sacred Datura <i> Datura wrightii</i> </p>
<p>Large, fragrant white flowers develop into decorative, but poisonous, spiky fruits on this Utah native.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" />
<p>Yellow Scabiosa <i> Scabiosa ochroleuca</i> </p>
<p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x395xTaxus,P20x,P20media,P20,P27Hicksii,P27,P20Fruit,P20SQS14.jpg.pagespeed.ic.qczwZHOutw.jpg" width="560" height="395" alt="" title="" />
<p>Hick's Yew <i> Taxus x media</i> 'Hicksii'</p>
<p>The almost alien looking fruits of this evergreen range from bright red to opaque pink.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" />
<p>Yellow Scabiosa <i> Scabiosa ochroleuca</i> </p>
<p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x383xScabiosa,P20ochroleuca,P20Fruit,P20SQS12.jpg.pagespeed.ic.2fjs1lx_k0.jpg" width="560" height="383" alt="" title="" />
<p>Yellow Scabiosa <i> Scabiosa ochroleuca</i> </p>
<p>The multitude of spikes adorning this fun, decorative seed head give this plant it's other common name of pincushion flower.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x395xTaxus,P20x,P20media,P20,P27Hicksii,P27,P20Fruit,P20SQS14.jpg.pagespeed.ic.qczwZHOutw.jpg" width="560" height="395" alt="" title="" />
<p>Hick's Yew <i> Taxus x media</i> 'Hicksii'</p>
<p>The almost alien looking fruits of this evergreen range from bright red to opaque pink.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x367xEuonymus,P20europaeus,P20,P27Red,P20Cascade,P27,P20Fall,P20Leaves,P20SQS12,P202.jpg.pagespeed.ic._frvi_J7Kk.jpg" width="560" height="367" alt="" title="" />
<p>Common Spindle Tree <i> Euonymus europaeus</i> 'Red Cascade'</p>
<p>The leaves of this tree become decorated with a spectacular array and design of colors in the fall.</p>
</div>
<br>
<br>
<div class="text-center">
<img src="/images/blogs/old-posts/550x563xViburnum,P20x,P20burkwoodii,P20Fall,P20Leaves,P20SQS13.JPG.pagespeed.ic.qQmTdz6e3i.jpg" width="560" height="563" alt="" title="" />
<p>Burkwood Viburnum <i>Viburnum x burkwoodii</i> </p>
<p>The leaves of this Viburnum make a lovely show of their transition from green to a deep wine-red hue.</p>
</div>
<br>
<br>
<div class="text-center">
<p>This is a spectacular time of year to visit the Garden and bask in the warmth of the sun. Don't take these autumnal opportunities for granted, winter will be here soon!</p>
</div>
<br>
<h5 class="text-center green">Photos by Sarah Sandoval</h5>
| redbuttegarden/redbuttegarden.github.io | whats-blooming/_posts/2014-10-13-falls-fabulous-floral-fruit-and-foliage-finery.html | HTML | apache-2.0 | 5,555 |
package com.melvin.share.ui.activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.melvin.share.R;
import com.melvin.share.Utils.ShapreUtils;
import com.melvin.share.Utils.Utils;
import com.melvin.share.databinding.ActivityOrderEvaluateBinding;
import com.melvin.share.model.Evaluation;
import com.melvin.share.model.WaitPayOrderInfo;
import com.melvin.share.model.list.CommonList;
import com.melvin.share.model.serverReturn.CommonReturnModel;
import com.melvin.share.modelview.acti.OrderEvaluateViewModel;
import com.melvin.share.network.GlobalUrl;
import com.melvin.share.rx.RxActivityHelper;
import com.melvin.share.rx.RxFragmentHelper;
import com.melvin.share.rx.RxModelSubscribe;
import com.melvin.share.rx.RxSubscribe;
import com.melvin.share.ui.activity.common.BaseActivity;
import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity;
import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment;
import com.melvin.share.view.MyRecyclerView;
import com.melvin.share.view.RatingBar;
import java.util.HashMap;
import java.util.Map;
import static com.melvin.share.R.id.map;
import static com.melvin.share.R.id.ratingbar;
/**
* Author: Melvin
* <p/>
* Data: 2017/4/8
* <p/>
* 描述: 订单评价页面
*/
public class OderEvaluateActivity extends BaseActivity {
private ActivityOrderEvaluateBinding binding;
private Context mContext = null;
private int starCount;
private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean;
@Override
protected void initView() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate);
mContext = this;
initWindow();
initToolbar(binding.toolbar);
ininData();
}
private void ininData() {
binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
@Override
public void onRatingChange(int var1) {
starCount = var1;
}
});
orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean");
if (orderItemResponsesBean != null) {
String[] split = orderItemResponsesBean.mainPicture.split("\\|");
if (split != null && split.length >= 1) {
String url = GlobalUrl.SERVICE_URL + split[0];
Glide.with(mContext)
.load(url)
.placeholder(R.mipmap.logo)
.centerCrop()
.into(binding.image);
}
binding.name.setText(orderItemResponsesBean.productName);
}
}
public void submit(View view) {
String contents = binding.content.getText().toString();
if (TextUtils.isEmpty(contents)) {
Utils.showToast(mContext, "请评价");
}
if (starCount == 0) {
Utils.showToast(mContext, "请评分");
}
Map map = new HashMap();
map.put("orderItemId", orderItemResponsesBean.id);
map.put("startlevel", starCount);
map.put("picture", orderItemResponsesBean.mainPicture);
map.put("content", contents);
ShapreUtils.putParamCustomerId(map);
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map)));
fromNetwork.insertOderItemEvaluation(jsonObject)
.compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true))
.subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) {
@Override
protected void myNext(CommonReturnModel commonReturnModel) {
Utils.showToast(mContext, commonReturnModel.message);
finish();
}
@Override
protected void myError(String message) {
Utils.showToast(mContext, message);
}
});
}
}
| MelvinWang/NewShare | NewShare/app/src/main/java/com/melvin/share/ui/activity/OderEvaluateActivity.java | Java | apache-2.0 | 4,380 |
# Weebly
=============
http://themehack.beta.weebly.com/weebly/main.php
| alex-accellerator/weebly | README.md | Markdown | apache-2.0 | 73 |
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnDestroy } from '@angular/core';
import { Platform, NavParams } from 'ionic-angular';
import { TranslateService } from '@ngx-translate/core';
import { CoreEventsProvider } from '@providers/events';
import { CoreSitesProvider } from '@providers/sites';
import { AddonMessagesProvider } from '../../providers/messages';
import { CoreDomUtilsProvider } from '@providers/utils/dom';
import { CoreUtilsProvider } from '@providers/utils/utils';
import { CoreAppProvider } from '@providers/app';
import { AddonPushNotificationsDelegate } from '@addon/pushnotifications/providers/delegate';
/**
* Component that displays the list of discussions.
*/
@Component({
selector: 'addon-messages-discussions',
templateUrl: 'addon-messages-discussions.html',
})
export class AddonMessagesDiscussionsComponent implements OnDestroy {
protected newMessagesObserver: any;
protected readChangedObserver: any;
protected cronObserver: any;
protected appResumeSubscription: any;
protected loadingMessages: string;
protected siteId: string;
loaded = false;
loadingMessage: string;
discussions: any;
discussionUserId: number;
pushObserver: any;
search = {
enabled: false,
showResults: false,
results: [],
loading: '',
text: ''
};
constructor(private eventsProvider: CoreEventsProvider, sitesProvider: CoreSitesProvider, translate: TranslateService,
private messagesProvider: AddonMessagesProvider, private domUtils: CoreDomUtilsProvider, navParams: NavParams,
private appProvider: CoreAppProvider, platform: Platform, utils: CoreUtilsProvider,
pushNotificationsDelegate: AddonPushNotificationsDelegate) {
this.search.loading = translate.instant('core.searching');
this.loadingMessages = translate.instant('core.loading');
this.siteId = sitesProvider.getCurrentSiteId();
// Update discussions when new message is received.
this.newMessagesObserver = eventsProvider.on(AddonMessagesProvider.NEW_MESSAGE_EVENT, (data) => {
if (data.userId) {
const discussion = this.discussions.find((disc) => {
return disc.message.user == data.userId;
});
if (typeof discussion == 'undefined') {
this.loaded = false;
this.refreshData().finally(() => {
this.loaded = true;
});
} else {
// An existing discussion has a new message, update the last message.
discussion.message.message = data.message;
discussion.message.timecreated = data.timecreated;
}
}
}, this.siteId);
// Update discussions when a message is read.
this.readChangedObserver = eventsProvider.on(AddonMessagesProvider.READ_CHANGED_EVENT, (data) => {
if (data.userId) {
const discussion = this.discussions.find((disc) => {
return disc.message.user == data.userId;
});
if (typeof discussion != 'undefined') {
// A discussion has been read reset counter.
discussion.unread = false;
// Discussions changed, invalidate them.
this.messagesProvider.invalidateDiscussionsCache();
}
}
}, this.siteId);
// Update discussions when cron read is executed.
this.cronObserver = eventsProvider.on(AddonMessagesProvider.READ_CRON_EVENT, (data) => {
this.refreshData();
}, this.siteId);
// Refresh the view when the app is resumed.
this.appResumeSubscription = platform.resume.subscribe(() => {
if (!this.loaded) {
return;
}
this.loaded = false;
this.refreshData();
});
this.discussionUserId = navParams.get('discussionUserId') || false;
// If a message push notification is received, refresh the view.
this.pushObserver = pushNotificationsDelegate.on('receive').subscribe((notification) => {
// New message received. If it's from current site, refresh the data.
if (utils.isFalseOrZero(notification.notif) && notification.site == this.siteId) {
this.refreshData();
}
});
}
/**
* Component loaded.
*/
ngOnInit(): void {
if (this.discussionUserId) {
// There is a discussion to load, open the discussion in a new state.
this.gotoDiscussion(this.discussionUserId);
}
this.fetchData().then(() => {
if (!this.discussionUserId && this.discussions.length > 0) {
// Take first and load it.
this.gotoDiscussion(this.discussions[0].message.user, undefined, true);
}
});
}
/**
* Refresh the data.
*
* @param {any} [refresher] Refresher.
* @return {Promise<any>} Promise resolved when done.
*/
refreshData(refresher?: any): Promise<any> {
return this.messagesProvider.invalidateDiscussionsCache().then(() => {
return this.fetchData().finally(() => {
if (refresher) {
// Actions to take if refresh comes from the user.
this.eventsProvider.trigger(AddonMessagesProvider.READ_CHANGED_EVENT, undefined, this.siteId);
refresher.complete();
}
});
});
}
/**
* Fetch discussions.
*
* @return {Promise<any>} Promise resolved when done.
*/
protected fetchData(): Promise<any> {
this.loadingMessage = this.loadingMessages;
this.search.enabled = this.messagesProvider.isSearchMessagesEnabled();
return this.messagesProvider.getDiscussions().then((discussions) => {
// Convert to an array for sorting.
const discussionsSorted = [];
for (const userId in discussions) {
discussions[userId].unread = !!discussions[userId].unread;
discussionsSorted.push(discussions[userId]);
}
this.discussions = discussionsSorted.sort((a, b) => {
return b.message.timecreated - a.message.timecreated;
});
}).catch((error) => {
this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true);
}).finally(() => {
this.loaded = true;
});
}
/**
* Clear search and show discussions again.
*/
clearSearch(): void {
this.loaded = false;
this.search.showResults = false;
this.search.text = ''; // Reset searched string.
this.fetchData().finally(() => {
this.loaded = true;
});
}
/**
* Search messages cotaining text.
*
* @param {string} query Text to search for.
* @return {Promise<any>} Resolved when done.
*/
searchMessage(query: string): Promise<any> {
this.appProvider.closeKeyboard();
this.loaded = false;
this.loadingMessage = this.search.loading;
return this.messagesProvider.searchMessages(query).then((searchResults) => {
this.search.showResults = true;
this.search.results = searchResults;
}).catch((error) => {
this.domUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true);
}).finally(() => {
this.loaded = true;
});
}
/**
* Navigate to a particular discussion.
*
* @param {number} discussionUserId Discussion Id to load.
* @param {number} [messageId] Message to scroll after loading the discussion. Used when searching.
* @param {boolean} [onlyWithSplitView=false] Only go to Discussion if split view is on.
*/
gotoDiscussion(discussionUserId: number, messageId?: number, onlyWithSplitView: boolean = false): void {
this.discussionUserId = discussionUserId;
const params = {
discussion: discussionUserId,
onlyWithSplitView: onlyWithSplitView
};
if (messageId) {
params['message'] = messageId;
}
this.eventsProvider.trigger(AddonMessagesProvider.SPLIT_VIEW_LOAD_EVENT, params, this.siteId);
}
/**
* Component destroyed.
*/
ngOnDestroy(): void {
this.newMessagesObserver && this.newMessagesObserver.off();
this.readChangedObserver && this.readChangedObserver.off();
this.cronObserver && this.cronObserver.off();
this.appResumeSubscription && this.appResumeSubscription.unsubscribe();
this.pushObserver && this.pushObserver.unsubscribe();
}
}
| jleyva/moodlemobile2 | src/addon/messages/components/discussions/discussions.ts | TypeScript | apache-2.0 | 9,547 |
# Crataegus nitidula var. recedens (Sarg.) Kruschke VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Crataegus/Crataegus nitidula/ Syn. Crataegus nitidula recedens/README.md | Markdown | apache-2.0 | 206 |
package clockworktest.water;
import com.clockwork.app.SimpleApplication;
import com.clockwork.audio.AudioNode;
import com.clockwork.audio.LowPassFilter;
import com.clockwork.effect.ParticleEmitter;
import com.clockwork.effect.ParticleMesh;
import com.clockwork.input.KeyInput;
import com.clockwork.input.controls.ActionListener;
import com.clockwork.input.controls.KeyTrigger;
import com.clockwork.light.DirectionalLight;
import com.clockwork.material.Material;
import com.clockwork.material.RenderState.BlendMode;
import com.clockwork.math.ColorRGBA;
import com.clockwork.math.FastMath;
import com.clockwork.math.Quaternion;
import com.clockwork.math.Vector3f;
import com.clockwork.post.FilterPostProcessor;
import com.clockwork.post.filters.BloomFilter;
import com.clockwork.post.filters.DepthOfFieldFilter;
import com.clockwork.post.filters.LightScatteringFilter;
import com.clockwork.renderer.Camera;
import com.clockwork.renderer.queue.RenderQueue.Bucket;
import com.clockwork.renderer.queue.RenderQueue.ShadowMode;
import com.clockwork.scene.Geometry;
import com.clockwork.scene.Node;
import com.clockwork.scene.Spatial;
import com.clockwork.scene.shape.Box;
import com.clockwork.terrain.geomipmap.TerrainQuad;
import com.clockwork.terrain.heightmap.AbstractHeightMap;
import com.clockwork.terrain.heightmap.ImageBasedHeightMap;
import com.clockwork.texture.Texture;
import com.clockwork.texture.Texture.WrapMode;
import com.clockwork.texture.Texture2D;
import com.clockwork.util.SkyFactory;
import com.clockwork.water.WaterFilter;
import java.util.ArrayList;
import java.util.List;
/**
* test
*
*/
public class TestPostWater extends SimpleApplication {
private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f, 5.896916f);
private WaterFilter water;
TerrainQuad terrain;
Material matRock;
AudioNode waves;
LowPassFilter underWaterAudioFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter underWaterReverbFilter = new LowPassFilter(0.5f, 0.1f);
LowPassFilter aboveWaterAudioFilter = new LowPassFilter(1, 1);
public static void main(String[] args) {
TestPostWater app = new TestPostWater();
app.start();
}
@Override
public void simpleInitApp() {
setDisplayFps(false);
setDisplayStatView(false);
Node mainScene = new Node("Main Scene");
rootNode.attachChild(mainScene);
createTerrain(mainScene);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(lightDir);
sun.setColor(ColorRGBA.White.clone().multLocal(1.7f));
mainScene.addLight(sun);
DirectionalLight l = new DirectionalLight();
l.setDirection(Vector3f.UNIT_Y.mult(-1));
l.setColor(ColorRGBA.White.clone().multLocal(0.3f));
// mainScene.addLight(l);
flyCam.setMoveSpeed(50);
//cam.setLocation(new Vector3f(-700, 100, 300));
//cam.setRotation(new Quaternion().fromAngleAxis(0.5f, Vector3f.UNIT_Z));
cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f));
cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f, 0.2678024f));
cam.setRotation(new Quaternion().fromAngles(new float[]{FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0}));
Spatial sky = SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false);
sky.setLocalScale(350);
mainScene.attachChild(sky);
cam.setFrustumFar(4000);
//cam.setFrustumNear(100);
//private FilterPostProcessor fpp;
water = new WaterFilter(rootNode, lightDir);
FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
fpp.addFilter(water);
BloomFilter bloom = new BloomFilter();
//bloom.getE
bloom.setExposurePower(55);
bloom.setBloomIntensity(1.0f);
fpp.addFilter(bloom);
LightScatteringFilter lsf = new LightScatteringFilter(lightDir.mult(-300));
lsf.setLightDensity(1.0f);
fpp.addFilter(lsf);
DepthOfFieldFilter dof = new DepthOfFieldFilter();
dof.setFocusDistance(0);
dof.setFocusRange(100);
fpp.addFilter(dof);
//
// fpp.addFilter(new TranslucentBucketFilter());
//
// fpp.setNumSamples(4);
water.setWaveScale(0.003f);
water.setMaxAmplitude(2f);
water.setFoamExistence(new Vector3f(1f, 4, 0.5f));
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
//water.setNormalScale(0.5f);
//water.setRefractionConstant(0.25f);
water.setRefractionStrength(0.2f);
//water.setFoamHardness(0.6f);
water.setWaterHeight(initialWaterHeight);
uw = cam.getLocation().y < waterHeight;
waves = new AudioNode(assetManager, "Sound/Environment/Ocean Waves.ogg", false);
waves.setLooping(true);
waves.setReverbEnabled(true);
if (uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
} else {
waves.setDryFilter(aboveWaterAudioFilter);
}
audioRenderer.playSource(waves);
//
viewPort.addProcessor(fpp);
inputManager.addListener(new ActionListener() {
public void onAction(String name, boolean isPressed, float tpf) {
if (isPressed) {
if (name.equals("foam1")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg"));
}
if (name.equals("foam2")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg"));
}
if (name.equals("foam3")) {
water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam3.jpg"));
}
if (name.equals("upRM")) {
water.setReflectionMapSize(Math.min(water.getReflectionMapSize() * 2, 4096));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
if (name.equals("downRM")) {
water.setReflectionMapSize(Math.max(water.getReflectionMapSize() / 2, 32));
System.out.println("Reflection map size : " + water.getReflectionMapSize());
}
}
}
}, "foam1", "foam2", "foam3", "upRM", "downRM");
inputManager.addMapping("foam1", new KeyTrigger(KeyInput.KEY_1));
inputManager.addMapping("foam2", new KeyTrigger(KeyInput.KEY_2));
inputManager.addMapping("foam3", new KeyTrigger(KeyInput.KEY_3));
inputManager.addMapping("upRM", new KeyTrigger(KeyInput.KEY_PGUP));
inputManager.addMapping("downRM", new KeyTrigger(KeyInput.KEY_PGDN));
// createBox();
// createFire();
}
Geometry box;
private void createBox() {
//creating a transluscent box
box = new Geometry("box", new Box(new Vector3f(0, 0, 0), 50, 50, 50));
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", new ColorRGBA(1.0f, 0, 0, 0.3f));
mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
//mat.getAdditionalRenderState().setDepthWrite(false);
//mat.getAdditionalRenderState().setDepthTest(false);
box.setMaterial(mat);
box.setQueueBucket(Bucket.Translucent);
//creating a post view port
// ViewPort post=renderManager.createPostView("transpPost", cam);
// post.setClearFlags(false, true, true);
box.setLocalTranslation(-600, 0, 300);
//attaching the box to the post viewport
//Don't forget to updateGeometricState() the box in the simpleUpdate
// post.attachScene(box);
rootNode.attachChild(box);
}
private void createFire() {
/**
* Uses Texture from CW-test-data library!
*/
ParticleEmitter fire = new ParticleEmitter("Emitter", ParticleMesh.Type.Triangle, 30);
Material mat_red = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md");
mat_red.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png"));
fire.setMaterial(mat_red);
fire.setImagesX(2);
fire.setImagesY(2); // 2x2 texture animation
fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f)); // red
fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f)); // yellow
fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 2, 0));
fire.setStartSize(10f);
fire.setEndSize(1f);
fire.setGravity(0, 0, 0);
fire.setLowLife(0.5f);
fire.setHighLife(1.5f);
fire.getParticleInfluencer().setVelocityVariation(0.3f);
fire.setLocalTranslation(-350, 40, 430);
fire.setQueueBucket(Bucket.Transparent);
rootNode.attachChild(fire);
}
private void createTerrain(Node rootNode) {
matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md");
matRock.setBoolean("useTriPlanarMapping", false);
matRock.setBoolean("WardIso", true);
matRock.setTexture("AlphaMap", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png"));
Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png");
Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg");
grass.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap", grass);
matRock.setFloat("DiffuseMap_0_scale", 64);
Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
dirt.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_1", dirt);
matRock.setFloat("DiffuseMap_1_scale", 16);
Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg");
rock.setWrap(WrapMode.Repeat);
matRock.setTexture("DiffuseMap_2", rock);
matRock.setFloat("DiffuseMap_2_scale", 128);
Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg");
normalMap0.setWrap(WrapMode.Repeat);
Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png");
normalMap1.setWrap(WrapMode.Repeat);
Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png");
normalMap2.setWrap(WrapMode.Repeat);
matRock.setTexture("NormalMap", normalMap0);
matRock.setTexture("NormalMap_1", normalMap2);
matRock.setTexture("NormalMap_2", normalMap2);
AbstractHeightMap heightmap = null;
try {
heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f);
heightmap.load();
} catch (Exception e) {
e.printStackTrace();
}
terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap());
List<Camera> cameras = new ArrayList<Camera>();
cameras.add(getCamera());
terrain.setMaterial(matRock);
terrain.setLocalScale(new Vector3f(5, 5, 5));
terrain.setLocalTranslation(new Vector3f(0, -30, 0));
terrain.setLocked(false); // unlock it so we can edit the height
terrain.setShadowMode(ShadowMode.Receive);
rootNode.attachChild(terrain);
}
//This part is to emulate tides, slightly varrying the height of the water plane
private float time = 0.0f;
private float waterHeight = 0.0f;
private float initialWaterHeight = 90f;//0.8f;
private boolean uw = false;
@Override
public void simpleUpdate(float tpf) {
super.simpleUpdate(tpf);
// box.updateGeometricState();
time += tpf;
waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f;
water.setWaterHeight(initialWaterHeight + waterHeight);
if (water.isUnderWater() && !uw) {
waves.setDryFilter(new LowPassFilter(0.5f, 0.1f));
uw = true;
}
if (!water.isUnderWater() && uw) {
uw = false;
//waves.setReverbEnabled(false);
waves.setDryFilter(new LowPassFilter(1, 1f));
//waves.setDryFilter(new LowPassFilter(1,1f));
}
}
}
| PlanetWaves/clockworkengine | branches/3.0/engine/src/test/clockworktest/water/TestPostWater.java | Java | apache-2.0 | 12,539 |
/*******************************************************************************
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.github.lothar.security.acl.elasticsearch.repository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject;
@Repository
public interface UnknownStrategyRepository
extends ElasticsearchRepository<UnknownStrategyObject, Long> {
}
| lordlothar99/strategy-spring-security-acl | elasticsearch/src/test/java/com/github/lothar/security/acl/elasticsearch/repository/UnknownStrategyRepository.java | Java | apache-2.0 | 1,173 |
# Meliosma cuneifolia Franch. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Sabiales/Sabiaceae/Meliosma/Meliosma cuneifolia/README.md | Markdown | apache-2.0 | 177 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
window.alert("你好");
console.log("今天是");
console.warn("星期五");
console.info("哈哈");
console.error("天气很好");
document.write("今天下雪啦");
</script>
</body>
</html> | puyanLiu/LPYFramework | 前端练习/04基本功/01js/01体验js.html | HTML | apache-2.0 | 581 |
-- phpMyAdmin SQL Dump
-- version 4.1.12
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 12-08-2014 a las 22:00:26
-- Versión del servidor: 5.5.36
-- Versión de PHP: 5.4.27
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `smeagol`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `menu`
--
CREATE TABLE IF NOT EXISTS `menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`label` varchar(150) DEFAULT NULL,
`url` varchar(250) DEFAULT NULL,
`parent_id` int(11) NOT NULL DEFAULT '0',
`order_id` int(11) NOT NULL DEFAULT '0',
`node_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_menu_node1_idx` (`node_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;
--
-- Volcado de datos para la tabla `menu`
--
INSERT INTO `menu` (`id`, `name`, `label`, `url`, `parent_id`, `order_id`, `node_id`) VALUES
(1, 'default', NULL, NULL, 0, 0, NULL),
(2, 'admin', NULL, NULL, 0, 0, NULL),
(3, NULL, 'Inicio', '/', 1, 0, NULL),
(4, NULL, 'Nosotros', NULL, 1, 1, 1),
(5, NULL, 'Servicios', NULL, 1, 2, 5),
(6, NULL, 'Programación web', NULL, 5, 0, 4),
(7, NULL, 'Desarrollo de Portales', NULL, 5, 1, 6),
(8, NULL, 'Soluciones', NULL, 1, 3, 7),
(9, NULL, 'Soporte', NULL, 1, 4, 8),
(10, NULL, 'Contáctenos', NULL, 1, 5, 9),
(11, NULL, 'Dashboard', 'admin', 2, 0, NULL),
(12, NULL, 'Contenido', 'admin/page', 2, 1, NULL),
(13, NULL, 'Noticias', 'admin/noticias', 2, 2, NULL),
(14, NULL, 'Menus', 'admin/menus', 2, 3, NULL),
(15, NULL, 'Temas', 'admin/themes', 2, 4, NULL),
(16, NULL, 'Usuarios', 'admin/users', 2, 5, NULL),
(17, NULL, 'Permisos', 'admin/permissions', 16, 1, NULL),
(18, NULL, 'Roles', 'admin/roles', 16, 0, NULL),
(19, NULL, 'Smeagol CMS', NULL, 7, 0, 10),
(20, NULL, 'Drupal CMS', NULL, 7, 1, 11);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `node`
--
CREATE TABLE IF NOT EXISTS `node` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) NOT NULL,
`content` text NOT NULL,
`url` varchar(250) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`node_type_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_node_node_type1_idx` (`node_type_id`),
KEY `fk_node_user1_idx` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
--
-- Volcado de datos para la tabla `node`
--
INSERT INTO `node` (`id`, `title`, `content`, `url`, `created`, `modified`, `node_type_id`, `user_id`) VALUES
(1, 'Nosotros', '<p><strong>Smeagol CMS, un</strong><strong> demo de desarrolado en Zend Framework 2</strong></p>\r\n\r\n<p>Nosotros somos hinchas de Zend Framework 2</p>\r\n\r\n<p>Gurus del php </p>\r\n\r\n<p>que deasrrollamos aplicaciones alucinantes</p>\r\n', 'nosotros', '2014-07-01 20:47:24', '2014-07-17 13:56:17', 1, 1),
(2, 'Smeagol primer CMS en ZF2', 'haber si funca', 'noticias/smeagol-primer-cms-en-zf2', '2014-07-01 20:47:24', NULL, 2, 1),
(3, 'El mundial Brasil 2014 esta que quema', 'El mundial esta super emocionante', 'noticias/mundialsuper-emocionante', '2014-07-01 20:47:24', NULL, 2, 1),
(4, 'Programación Web', '<p>Somos unos tigres del PHP y demás hierbas</p>\r\n', 'servicios/programacion-web', '2014-07-10 22:47:08', '2014-07-17 13:50:46', 1, 1),
(5, 'Servicios', '<p>Somos Expertos Programadores y le ofrecemos los siguientes servicios</p>\r\n\r\n<p><a href="/servicios/programacion-web">Programación web</a> </p>\r\n\r\n<p><a href="/servicios/desarrollo-de-portales">Desarrollo de Portales</a></p>\r\n', 'servicios', '2014-07-17 13:50:18', '2014-07-17 13:50:18', 1, 1),
(6, 'Desarrollo de Portales', '<p>Creamos portales con smeagol y drupal </p>\r\n', 'servicios/desarrollo-de-portales', '2014-07-17 13:52:35', '2014-07-17 13:52:35', 1, 1),
(7, 'Soluciones', '<p><img alt="" src="/files/fotos/puesta-de-sol.jpg" style="float:left; height:141px; width:188px" />Hacemos desarrollo de software a medida y contamos con las siguientes soluciones</p>\r\n\r\n<p><a href="/soluciones/smeagolcms">Smeagol CMS</a></p>\r\n\r\n<p><a href="/soluciones/intranets">Intranets</a></p>\r\n', 'soluciones/intranets', '2014-07-17 13:54:35', '2014-08-03 19:41:00', 1, 1),
(8, 'Soporte', '<p>Brindamos el mejor soporte al mejor precio</p>\r\n\r\n<p>en planes</p>\r\n\r\n<p>8x5</p>\r\n\r\n<p>24x7</p>\r\n', 'soporte', '2014-07-17 13:58:17', '2014-08-12 21:58:34', 1, 3),
(9, 'Contactenos', '<p>Contáctenos y no se arrepentirá</p>\r\n\r\n<p>al fono 666-666-666</p>\r\n', 'contactenos', '2014-07-17 13:59:13', '2014-07-17 13:59:13', 1, 1),
(10, 'Smeagol', '<h1>El mejor CMS en Zend Frammework 2 :D</h1>', 'servicios/desarrollo-de-portales/smeagol', '2014-07-22 08:05:00', NULL, 1, 1),
(11, 'Drupal 7', '<h1> El Mejor CMS del mundo</h1>\r\n<h2> Que lo usa hasta el tío Obama<h2>', 'servicios/desarrollo-de-portales/drupal', '2014-07-22 08:05:00', NULL, 1, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `node_type`
--
CREATE TABLE IF NOT EXISTS `node_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Volcado de datos para la tabla `node_type`
--
INSERT INTO `node_type` (`id`, `name`) VALUES
(1, 'page'),
(2, 'notice');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `permission`
--
CREATE TABLE IF NOT EXISTS `permission` (
`resource` varchar(250) NOT NULL,
`description` varchar(250) NOT NULL,
PRIMARY KEY (`resource`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `permission`
--
INSERT INTO `permission` (`resource`, `description`) VALUES
('mvc:admin.*', 'Acceso total al módulo de administración'),
('mvc:admin.index.index', 'Acceso al Dashboard del Admin'),
('mvc:admin.page.*', 'Acceso total para crear, editar, borrar páginas estáticas de cualquier usuario'),
('mvc:admin.page.add', 'Crear páginas estáticas'),
('mvc:admin.page.delete:owner', 'Borrar páginas estáticas que sean propiedad del usuario'),
('mvc:admin.page.edit:owner', 'Editar páginas estáticas que sean propiedad del usuario'),
('mvc:admin.page.index', 'Acceso al listado de páginas estáticas'),
('mvc:application.*', 'Acceso total al módulo público');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `role`
--
CREATE TABLE IF NOT EXISTS `role` (
`type` varchar(30) NOT NULL,
`description` varchar(250) NOT NULL,
PRIMARY KEY (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `role`
--
INSERT INTO `role` (`type`, `description`) VALUES
('admin', 'Usuarios Administradores, todos los permisos'),
('editor', 'Usuarios con el rol de editor, por defecto puede crear, editar y borrar todos los contenidos'),
('guest', 'Usuarios anónimos, por defecto pueden acceder a todos los contenidos'),
('member', 'Usuarios Autenticados, por defecto pueden editar su propio contenido');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `role_permission`
--
CREATE TABLE IF NOT EXISTS `role_permission` (
`role_type` varchar(30) NOT NULL,
`permission_resource` varchar(250) NOT NULL,
PRIMARY KEY (`role_type`,`permission_resource`),
KEY `fk_role_permission_role1_idx` (`role_type`),
KEY `fk_role_permission_permission1_idx` (`permission_resource`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `role_permission`
--
INSERT INTO `role_permission` (`role_type`, `permission_resource`) VALUES
('admin', 'mvc:admin.*'),
('admin', 'mvc:application.*'),
('editor', 'mvc:admin.index.index'),
('editor', 'mvc:admin.page.*'),
('editor', 'mvc:application.*'),
('guest', 'mvc:application.*'),
('member', 'mvc:admin.index.index'),
('member', 'mvc:admin.page.add'),
('member', 'mvc:admin.page.delete:owner'),
('member', 'mvc:admin.page.edit:owner'),
('member', 'mvc:admin.page.index'),
('member', 'mvc:application.*');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`surname` varchar(100) DEFAULT NULL,
`email` varchar(150) NOT NULL,
`active` int(11) DEFAULT '1',
`last_login` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`role_type` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_role_idx` (`role_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Volcado de datos para la tabla `user`
--
INSERT INTO `user` (`id`, `username`, `password`, `name`, `surname`, `email`, `active`, `last_login`, `modified`, `role_type`) VALUES
(1, 'admin', 'c6865cf98b133f1f3de596a4a2894630', 'Admin', 'of Universe', '[email protected]', 1, NULL, '2014-07-01 20:47:24', 'admin'),
(2, 'pepito', 'c6865cf98b133f1f3de596a4a2894630', 'Pepito', 'Linuxero', '[email protected]', 1, '2014-08-04 00:00:00', '2014-08-04 00:00:00', 'editor'),
(3, 'tuxito', 'c6865cf98b133f1f3de596a4a2894630', 'Tuxito', 'Linuxero', '[email protected]', 1, '2014-08-11 17:17:00', '2014-08-11 17:17:00', 'member');
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `menu`
--
ALTER TABLE `menu`
ADD CONSTRAINT `fk_menu_node1` FOREIGN KEY (`node_id`) REFERENCES `node` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Filtros para la tabla `node`
--
ALTER TABLE `node`
ADD CONSTRAINT `fk_node_node_type1` FOREIGN KEY (`node_type_id`) REFERENCES `node_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_node_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Filtros para la tabla `role_permission`
--
ALTER TABLE `role_permission`
ADD CONSTRAINT `fk_role_permission_permission1` FOREIGN KEY (`permission_resource`) REFERENCES `permission` (`resource`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_role_permission_role1` FOREIGN KEY (`role_type`) REFERENCES `role` (`type`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Filtros para la tabla `user`
--
ALTER TABLE `user`
ADD CONSTRAINT `fk_user_role` FOREIGN KEY (`role_type`) REFERENCES `role` (`type`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| cleverflores/smeagol | sql/smeagol.sql | SQL | apache-2.0 | 11,020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.