code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/**
* @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.
*/
'use strict';
// MAIN //
/**
* Computes the variance of a strided array ignoring `NaN` values and using Welford's algorithm.
*
* ## References
*
* - Welford, B. P. 1962. "Note on a Method for Calculating Corrected Sums of Squares and Products." _Technometrics_ 4 (3). Taylor & Francis: 419–20. doi:[10.1080/00401706.1962.10490022](https://doi.org/10.1080/00401706.1962.10490022).
* - van Reeken, A. J. 1968. "Letters to the Editor: Dealing with Neely's Algorithms." _Communications of the ACM_ 11 (3): 149–50. doi:[10.1145/362929.362961](https://doi.org/10.1145/362929.362961).
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {NumericArray} x - input array
* @param {integer} stride - stride length
* @param {NonNegativeInteger} offset - starting index
* @returns {number} variance
*
* @example
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var x = [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ];
* var N = floor( x.length / 2 );
*
* var v = nanvariancewd( N, 1, x, 2, 1 );
* // returns 6.25
*/
function nanvariancewd( N, correction, x, stride, offset ) {
var delta;
var mu;
var M2;
var ix;
var nc;
var v;
var n;
var i;
if ( N <= 0 ) {
return NaN;
}
if ( N === 1 || stride === 0 ) {
v = x[ offset ];
if ( v === v && N-correction > 0.0 ) {
return 0.0;
}
return NaN;
}
ix = offset;
M2 = 0.0;
mu = 0.0;
n = 0;
for ( i = 0; i < N; i++ ) {
v = x[ ix ];
if ( v === v ) {
delta = v - mu;
n += 1;
mu += delta / n;
M2 += delta * ( v - mu );
}
ix += stride;
}
nc = n - correction;
if ( nc <= 0.0 ) {
return NaN;
}
return M2 / nc;
}
// EXPORTS //
module.exports = nanvariancewd;
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/stats/base/nanvariancewd/lib/ndarray.js
|
JavaScript
|
apache-2.0
| 2,365
|
/**
* @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.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var floor = require( '@stdlib/math/base/special/floor' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var Float64Array = require( '@stdlib/array/float64' );
var dcusumpw = require( './../lib/ndarray.js' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof dcusumpw, 'function', 'main export is a function' );
t.end();
});
tape( 'the function has an arity of 8', function test( t ) {
t.strictEqual( dcusumpw.length, 8, 'has expected arity' );
t.end();
});
tape( 'the function calculates the cumulative sum', function test( t ) {
var expected;
var x;
var y;
var i;
x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
y = new Float64Array( x.length );
dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
expected = new Float64Array([
1.0,
3.0,
6.0,
10.0,
15.0
]);
t.deepEqual( y, expected, 'returns expected value' );
x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
y = new Float64Array( x.length );
dcusumpw( x.length, 10.0, x, 1, 0, y, 1, 0 );
expected = new Float64Array([
11.0,
13.0,
16.0,
20.0,
25.0
]);
t.deepEqual( y, expected, 'returns expected value' );
x = new Float64Array( [ NaN, NaN ] );
y = new Float64Array( x.length );
dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
for ( i = 0; i < y.length; i++ ) {
t.strictEqual( isnan( y[ i ] ), true, 'returns expected value. i: ' + i );
}
x = new Float64Array( [ 1.0, NaN, 3.0, NaN ] );
y = new Float64Array( x.length );
dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
expected = new Float64Array([
1.0,
NaN,
NaN,
NaN
]);
for ( i = 0; i < y.length; i++ ) {
if ( isnan( expected[ i ] ) ) {
t.strictEqual( isnan( y[ i ] ), true, 'returns expected value. i: ' + i );
} else {
t.strictEqual( y[ i ], expected[ i ], true, 'returns expected value. i: ' + i );
}
}
x = new Float64Array( [ 1.0, 1.0e100, 1.0, -1.0e100 ] );
y = new Float64Array( x.length );
dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
expected = new Float64Array([
1.0,
1.0e100,
1.0e100,
0.0
]);
t.deepEqual( y, expected, 'returns expected value' );
x = new Float64Array( 1e3 );
y = new Float64Array( x.length );
expected = new Float64Array( x.length );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = i + 1;
if ( i === 0 ) {
expected[ i ] += x[ i ];
} else {
expected[ i ] += expected[ i-1 ] + x[ i ];
}
}
dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function returns a reference to the output array', function test( t ) {
var out;
var x;
var y;
x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
y = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
out = dcusumpw( x.length, 0.0, x, 1, 0, y, 1, 0 );
t.strictEqual( out, y, 'same reference' );
t.end();
});
tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `y` unchanged', function test( t ) {
var expected;
var x;
var y;
x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
y = new Float64Array( [ 6.0, 7.0, 8.0, 9.0, 10.0 ] );
expected = new Float64Array( [ 6.0, 7.0, 8.0, 9.0, 10.0 ] );
dcusumpw( -1, 0.0, x, 1, 0, y, 1, 0 );
t.deepEqual( y, expected, 'returns `y` unchanged' );
dcusumpw( 0, 0.0, x, 1, 0, y, 1, 0 );
t.deepEqual( y, expected, 'returns `y` unchanged' );
t.end();
});
tape( 'the function supports an `x` stride', function test( t ) {
var expected;
var x;
var y;
var N;
x = new Float64Array([
1.0, // 0
2.0,
3.0, // 1
4.0,
5.0 // 2
]);
y = new Float64Array([
0.0, // 0
0.0, // 1
0.0, // 2
0.0,
0.0
]);
N = 3;
dcusumpw( N, 0.0, x, 2, 0, y, 1, 0 );
expected = new Float64Array( [ 1.0, 4.0, 9.0, 0.0, 0.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function supports a `y` stride', function test( t ) {
var expected;
var x;
var y;
var N;
x = new Float64Array([
1.0, // 0
2.0, // 1
3.0, // 2
4.0,
5.0
]);
y = new Float64Array([
0.0, // 0
0.0,
0.0, // 1
0.0,
0.0 // 2
]);
N = 3;
dcusumpw( N, 0.0, x, 1, 0, y, 2, 0 );
expected = new Float64Array( [ 1.0, 0.0, 3.0, 0.0, 6.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function supports negative strides', function test( t ) {
var expected;
var x;
var y;
var N;
var i;
x = new Float64Array([
1.0, // 2
2.0,
3.0, // 1
4.0,
5.0 // 0
]);
y = new Float64Array([
0.0, // 2
0.0, // 1
0.0, // 0
0.0,
0.0
]);
N = 3;
dcusumpw( N, 0.0, x, -2, x.length-1, y, -1, 2 );
expected = new Float64Array( [ 9.0, 8.0, 5.0, 0.0, 0.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
x = new Float64Array( 1e3 );
y = new Float64Array( x.length );
expected = new Float64Array( x.length );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = i + 1;
}
for ( i = x.length-1; i >= 0; i-- ) {
if ( i === x.length-1 ) {
expected[ i ] += x[ i ];
} else {
expected[ i ] += expected[ i+1 ] + x[ i ];
}
}
dcusumpw( x.length, 0.0, x, -1, x.length-1, y, -1, y.length-1 );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function supports an `x` offset', function test( t ) {
var expected;
var N;
var x;
var y;
x = new Float64Array([
2.0,
1.0, // 0
2.0,
-2.0, // 1
-2.0,
2.0, // 2
3.0,
4.0 // 3
]);
y = new Float64Array([
0.0, // 0
0.0, // 1
0.0, // 2
0.0, // 3
0.0,
0.0,
0.0,
0.0
]);
N = floor( x.length / 2 );
dcusumpw( N, 0.0, x, 2, 1, y, 1, 0 );
expected = new Float64Array( [ 1.0, -1.0, 1.0, 5.0, 0.0, 0.0, 0.0, 0.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function supports a `y` offset', function test( t ) {
var expected;
var N;
var x;
var y;
x = new Float64Array([
2.0, // 0
1.0, // 1
2.0, // 2
-2.0, // 3
-2.0,
2.0,
3.0,
4.0
]);
y = new Float64Array([
0.0,
0.0, // 0
0.0,
0.0, // 1
0.0,
0.0, // 2
0.0,
0.0 // 3
]);
N = floor( x.length / 2 );
dcusumpw( N, 0.0, x, 1, 0, y, 2, 1 );
expected = new Float64Array( [ 0.0, 2.0, 0.0, 3.0, 0.0, 5.0, 0.0, 3.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
tape( 'the function supports complex access patterns', function test( t ) {
var expected;
var x;
var y;
var N;
x = new Float64Array([
1.0, // 0
2.0,
3.0, // 1
4.0,
5.0, // 2
6.0
]);
y = new Float64Array([
0.0, // 2
0.0, // 1
0.0, // 0
0.0,
0.0,
0.0
]);
N = 3;
dcusumpw( N, 0.0, x, 2, 0, y, -1, 2 );
expected = new Float64Array( [ 9.0, 4.0, 1.0, 0.0, 0.0, 0.0 ] );
t.deepEqual( y, expected, 'returns expected value' );
t.end();
});
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/blas/ext/base/dcusumpw/test/test.ndarray.js
|
JavaScript
|
apache-2.0
| 7,412
|
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.kernel.component.core.test;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.sakaiproject.kernel.api.ComponentSpecificationException;
import org.sakaiproject.kernel.api.DependencyScope;
import org.sakaiproject.kernel.api.Exporter;
import org.sakaiproject.kernel.component.KernelImpl;
import org.sakaiproject.kernel.component.core.Maven2ArtifactResolver;
import org.sakaiproject.kernel.component.core.PackageRegistryServiceImpl;
import org.sakaiproject.kernel.component.core.SharedClassLoader;
import org.sakaiproject.kernel.component.core.SharedClassloaderArtifact;
import org.sakaiproject.kernel.component.model.DependencyImpl;
import org.sakaiproject.kernel.component.test.mock.MockArtifact;
import java.io.IOException;
import java.net.MalformedURLException;
/**
*
*/
public class SharedClassloaderTest {
private static final Log LOG = LogFactory.getLog(SharedClassloaderTest.class);
@Test
public void testExportedPackages() throws MalformedURLException, IOException,
ComponentSpecificationException {
PackageRegistryServiceImpl prs = new PackageRegistryServiceImpl();
Maven2ArtifactResolver dependencyResolver = new Maven2ArtifactResolver();
KernelImpl kernel = new KernelImpl();
// add an export that wont be used
Exporter exportClassloader = new MockClassExport(this.getClass()
.getClassLoader(),new MockArtifact("unused-exporter"),"META-INF/persistance.xml");
prs.addExport("org.sakaiproject.kernel.component.test", exportClassloader);
SharedClassLoader cc = new SharedClassLoader(prs, dependencyResolver,
new SharedClassloaderArtifact(), kernel);
LOG.info("Classloader Structure is " + cc.toString());
// Check the class in not visible
try {
cc.loadClass("org.apache.commons.codec.binary.Base64");
fail();
} catch (ClassNotFoundException e) {
}
DependencyImpl cpdep = new DependencyImpl();
cpdep.setGroupId("commons-codec");
cpdep.setArtifactId("commons-codec");
cpdep.setVersion("1.3");
cpdep.setScope(DependencyScope.SHARE);
cc.addDependency(cpdep);
LOG.info("Classloader Structure after add is " + cc.toString());
// load something from the exported classloader
try {
Class<?> c = cc.loadClass("org.apache.commons.codec.binary.Base64");
assertSame(cc, c.getClassLoader());
} catch (ClassNotFoundException e) {
fail();
}
}
}
|
sakai-mirror/k2
|
agnostic/shared/src/test/java/org/sakaiproject/kernel/component/core/test/SharedClassloaderTest.java
|
Java
|
apache-2.0
| 3,369
|
<!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_67) on Wed Oct 08 15:57:24 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<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.hadoop.hbase.mapreduce.TableRecordReaderImpl (HBase 0.98.7-hadoop2 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/hadoop/hbase/mapreduce/TableRecordReaderImpl.html" title="class in org.apache.hadoop.hbase.mapreduce">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?org/apache/hadoop/hbase/mapreduce/class-use/TableRecordReaderImpl.html" target="_top">Frames</a></li>
<li><a href="TableRecordReaderImpl.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.hadoop.hbase.mapreduce.TableRecordReaderImpl" class="title">Uses of Class<br>org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl</h2>
</div>
<div class="classUseContainer">No usage of org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl</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/hadoop/hbase/mapreduce/TableRecordReaderImpl.html" title="class in org.apache.hadoop.hbase.mapreduce">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?org/apache/hadoop/hbase/mapreduce/class-use/TableRecordReaderImpl.html" target="_top">Frames</a></li>
<li><a href="TableRecordReaderImpl.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 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
|
gsoundar/mambo-ec2-deploy
|
packages/hbase-0.98.7-hadoop2/docs/devapidocs/org/apache/hadoop/hbase/mapreduce/class-use/TableRecordReaderImpl.html
|
HTML
|
apache-2.0
| 4,650
|
<?php
/*
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.
This page provides information about the most recent crawl. It was
created to help Ilya download the crawl information including
pageids & WebPagetest IDs.
Querystring parameters:
label - The label of the crawl, eg, "Dec 15 2014".
crawlid - The crawlid of the crawl, eg, 268.
format - The only option currently is "json". Default: "json"
jsonp - Name of a callback function to pass the JSON object to. If
not specified then the JSON object is returned.
If neither label nor crawlid is specified then the latest crawl is returned.
If the crawl is NOT finished, then only the crawl's meta info is returned.
If the crawl IS finished, then the "pages" property is an array containing
an array of information about each page: pageid, wptid, & medianrun. With
that you can construct the HA URL (from which you can find the crawl):
http://httparchive.org/viewsite.php?pageid=[pageid]
As well as the HAR URL:
http://httparchive.webpagetest.org/export.php?test=[wptid]&run=[medianrun]&cached=0&pretty=1
The most typical usage is simply:
http://dev.httparchive.org/crawl-data.php
*/
require_once("ui.inc");
require_once("utils.inc");
if ( getParam("crawlid") ) {
$crawl = getCrawlFromId(getParam("crawlid"));
}
else if ( getParam("label") ) {
$crawl = getCrawl(getParam("label"));
}
else {
// This is the latest crawl regardless of whether it's finished.
$crawl = latestCrawl(null, null, false);
}
if ( $crawl["finishedDateTime"] ) {
// Add all the info about pages crawled.
$crawl["pages"] = array();
$query = "select pageid, wptid, wptrun from $gPagesTable where crawlid = ${crawl['crawlid']} order by pageid asc;";
$result = doQuery($query);
while ( $row = mysqli_fetch_row($result) ) {
array_push($crawl["pages"], $row);
}
mysqli_free_result($result);
}
$response = json_encode($crawl);
$jsonp = getParam("jsonp");
if ( $jsonp ) {
echo "$jsonp($response);";
}
else {
echo $response;
}
?>
|
HTTPArchive/httparchive
|
crawl-data.php
|
PHP
|
apache-2.0
| 2,474
|
<!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_92) on Wed Jul 27 21:25:53 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>net.sourceforge.pmd (PMD Objective-C 5.5.1 Test API)</title>
<meta name="date" content="2016-07-27">
<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="net.sourceforge.pmd (PMD Objective-C 5.5.1 Test 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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>Prev Package</li>
<li><a href="../../../net/sourceforge/pmd/cpd/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/sourceforge/pmd/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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="Package" class="title">Package net.sourceforge.pmd</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../net/sourceforge/pmd/LanguageVersionTest.html" title="class in net.sourceforge.pmd">LanguageVersionTest</a></td>
<td class="colLast"> </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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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>Prev Package</li>
<li><a href="../../../net/sourceforge/pmd/cpd/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?net/sourceforge/pmd/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 © 2002–2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p>
</body>
</html>
|
jasonwee/videoOnCloud
|
pmd/pmd-doc-5.5.1/pmd-objectivec/testapidocs/net/sourceforge/pmd/package-summary.html
|
HTML
|
apache-2.0
| 4,926
|
package Paws::Pinpoint::GetCampaignVersions;
use Moose;
has ApplicationId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'application-id', required => 1);
has CampaignId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'campaign-id', required => 1);
has PageSize => (is => 'ro', isa => 'Str', traits => ['ParamInQuery'], query_name => 'page-size');
has Token => (is => 'ro', isa => 'Str', traits => ['ParamInQuery'], query_name => 'token');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetCampaignVersions');
class_has _api_uri => (isa => 'Str', is => 'ro', default => '/v1/apps/{application-id}/campaigns/{campaign-id}/versions');
class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Pinpoint::GetCampaignVersionsResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::Pinpoint::GetCampaignVersions - Arguments for method GetCampaignVersions on Paws::Pinpoint
=head1 DESCRIPTION
This class represents the parameters used for calling the method GetCampaignVersions on the
Amazon Pinpoint service. Use the attributes of this class
as arguments to method GetCampaignVersions.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetCampaignVersions.
As an example:
$service_obj->GetCampaignVersions(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> ApplicationId => Str
=head2 B<REQUIRED> CampaignId => Str
=head2 PageSize => Str
The number of entries you want on each page in the response.
=head2 Token => Str
The NextToken string returned on a previous page that you use to get
the next page of results in a paginated response.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method GetCampaignVersions in L<Paws::Pinpoint>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
|
ioanrogers/aws-sdk-perl
|
auto-lib/Paws/Pinpoint/GetCampaignVersions.pm
|
Perl
|
apache-2.0
| 2,461
|
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { StateStorageService } from '../../shared';
@Component({
selector: 'jhi-main',
templateUrl: './main.component.html'
})
export class JhiMainComponent implements OnInit {
constructor(
private titleService: Title,
private router: Router,
private $storageService: StateStorageService,
) {}
private getPageTitle(routeSnapshot: ActivatedRouteSnapshot) {
let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'tasksApp';
if (routeSnapshot.firstChild) {
title = this.getPageTitle(routeSnapshot.firstChild) || title;
}
return title;
}
ngOnInit() {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.titleService.setTitle(this.getPageTitle(this.router.routerState.snapshot.root));
}
});
}
}
|
cfaddict/jhipster-course
|
jhipster-tasks/src/main/webapp/app/layouts/main/main.component.ts
|
TypeScript
|
apache-2.0
| 1,143
|
<!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_60-ea) on Tue Aug 16 17:15:35 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.config.transactions.log_store.transactions (Public javadocs 2016.8.1 API)</title>
<meta name="date" content="2016-08-16">
<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="Uses of Package org.wildfly.swarm.config.transactions.log_store.transactions (Public javadocs 2016.8.1 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><a href="package-summary.html">Package</a></li>
<li>Class</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 class="aboutLanguage">WildFly Swarm API, 2016.8.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/transactions/log_store/transactions/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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="Uses of Package org.wildfly.swarm.config.transactions.log_store.transactions" class="title">Uses of Package<br>org.wildfly.swarm.config.transactions.log_store.transactions</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/package-summary.html">org.wildfly.swarm.config.transactions.log_store.transactions</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.wildfly.swarm.config.transactions.log_store">org.wildfly.swarm.config.transactions.log_store</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.transactions.log_store.transactions">org.wildfly.swarm.config.transactions.log_store.transactions</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.transactions.log_store">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/package-summary.html">org.wildfly.swarm.config.transactions.log_store.transactions</a> used by <a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/package-summary.html">org.wildfly.swarm.config.transactions.log_store</a></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="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/Participants.html#org.wildfly.swarm.config.transactions.log_store">Participants</a>
<div class="block">The resources that did work in a transaction.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/ParticipantsConsumer.html#org.wildfly.swarm.config.transactions.log_store">ParticipantsConsumer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/ParticipantsSupplier.html#org.wildfly.swarm.config.transactions.log_store">ParticipantsSupplier</a> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.transactions.log_store.transactions">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/package-summary.html">org.wildfly.swarm.config.transactions.log_store.transactions</a> used by <a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/package-summary.html">org.wildfly.swarm.config.transactions.log_store.transactions</a></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="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/Participants.html#org.wildfly.swarm.config.transactions.log_store.transactions">Participants</a>
<div class="block">The resources that did work in a transaction.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/Participants.Status.html#org.wildfly.swarm.config.transactions.log_store.transactions">Participants.Status</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/class-use/ParticipantsConsumer.html#org.wildfly.swarm.config.transactions.log_store.transactions">ParticipantsConsumer</a> </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><a href="package-summary.html">Package</a></li>
<li>Class</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 class="aboutLanguage">WildFly Swarm API, 2016.8.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/transactions/log_store/transactions/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.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 © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2016.8.1/apidocs/org/wildfly/swarm/config/transactions/log_store/transactions/package-use.html
|
HTML
|
apache-2.0
| 8,911
|
/*
* Copyright 2002-2015 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 org.springframework.context.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import example.profilescan.ProfileAnnotatedComponent;
import example.scannable.AutowiredQualifierFooService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @author Sam Brannen
*/
public class ComponentScanParserTests {
private ClassPathXmlApplicationContext loadContext(String path) {
return new ClassPathXmlApplicationContext(path, getClass());
}
@Test
public void aspectjTypeFilter() {
ClassPathXmlApplicationContext context = loadContext("aspectjTypeFilterTests.xml");
assertTrue(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("stubFooDao"));
assertFalse(context.containsBean("scopedProxyTestBean"));
context.close();
}
@Test
public void aspectjTypeFilterWithPlaceholders() {
System.setProperty("basePackage", "example.scannable, test");
System.setProperty("scanInclude", "example.scannable.FooService+");
System.setProperty("scanExclude", "example..Scoped*Test*");
try {
ClassPathXmlApplicationContext context = loadContext("aspectjTypeFilterTestsWithPlaceholders.xml");
assertTrue(context.containsBean("fooServiceImpl"));
assertTrue(context.containsBean("stubFooDao"));
assertFalse(context.containsBean("scopedProxyTestBean"));
context.close();
}
finally {
System.clearProperty("basePackage");
System.clearProperty("scanInclude");
System.clearProperty("scanExclude");
}
}
@Test
public void nonMatchingResourcePattern() {
ClassPathXmlApplicationContext context = loadContext("nonMatchingResourcePatternTests.xml");
assertFalse(context.containsBean("fooServiceImpl"));
context.close();
}
@Test
public void matchingResourcePattern() {
ClassPathXmlApplicationContext context = loadContext("matchingResourcePatternTests.xml");
assertTrue(context.containsBean("fooServiceImpl"));
context.close();
}
@Test
public void componentScanWithAutowiredQualifier() {
ClassPathXmlApplicationContext context = loadContext("componentScanWithAutowiredQualifierTests.xml");
AutowiredQualifierFooService fooService = (AutowiredQualifierFooService) context.getBean("fooService");
assertTrue(fooService.isInitCalled());
assertEquals("bar", fooService.foo(123));
context.close();
}
@Test
public void customAnnotationUsedForBothComponentScanAndQualifier() {
ClassPathXmlApplicationContext context = loadContext("customAnnotationUsedForBothComponentScanAndQualifierTests.xml");
KustomAnnotationAutowiredBean testBean = (KustomAnnotationAutowiredBean) context.getBean("testBean");
assertNotNull(testBean.getDependency());
context.close();
}
@Test
public void customTypeFilter() {
ClassPathXmlApplicationContext context = loadContext("customTypeFilterTests.xml");
KustomAnnotationAutowiredBean testBean = (KustomAnnotationAutowiredBean) context.getBean("testBean");
assertNotNull(testBean.getDependency());
context.close();
}
@Test
public void componentScanRespectsProfileAnnotation() {
String xmlLocation = "org/springframework/context/annotation/componentScanRespectsProfileAnnotationTests.xml";
{ // should exclude the profile-annotated bean if active profiles remains unset
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load(xmlLocation);
context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false));
context.close();
}
{ // should include the profile-annotated bean with active profiles set
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
context.load(xmlLocation);
context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true));
context.close();
}
{ // ensure the same works for AbstractRefreshableApplicationContext impls too
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(new String[] { xmlLocation },
false);
context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true));
context.close();
}
}
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
}
/**
* Intentionally spelling "custom" with a "k" since there are numerous
* classes in this package named *Custom*.
*/
public static class KustomAnnotationAutowiredBean {
@Autowired
@CustomAnnotation
private KustomAnnotationDependencyBean dependency;
public KustomAnnotationDependencyBean getDependency() {
return this.dependency;
}
}
/**
* Intentionally spelling "custom" with a "k" since there are numerous
* classes in this package named *Custom*.
*/
@CustomAnnotation
public static class KustomAnnotationDependencyBean {
}
public static class CustomTypeFilter implements TypeFilter {
/**
* Intentionally spelling "custom" with a "k" since there are numerous
* classes in this package named *Custom*.
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
return metadataReader.getClassMetadata().getClassName().contains("Kustom");
}
}
}
|
shivpun/spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java
|
Java
|
apache-2.0
| 6,700
|
# frozen_string_literal: true
module Wings
# Stores a file and an associated Hyrax::FileMetadata
#
# @deprecated use `Hyrax.storage_adapter` instead
class FileMetadataBuilder
include Hyrax::Noid
attr_reader :storage_adapter, :persister
def initialize(storage_adapter:, persister:)
Deprecation.warn('This class is deprecated; use Wings::Valkyrie::Storage instead.')
@storage_adapter = storage_adapter
@persister = persister
end
# @param io_wrapper [JobIOWrapper] with details about the uploaded file
# @param file_metadata [Hyrax::FileMetadata] the metadata to represent the file
# @param file_set [Valkyrie::Resouce, Hydra::Works::FileSet] the associated FileSet # TODO: WINGS - Remove Hydra::Works::FileSet as a potential type when valkyrization is complete.
# @return [Hyrax::FileMetadata] the persisted metadata file_metadata that represents the file
#
# @deprecated use `Hyrax.storage_adapter` instead
def create(io_wrapper:, file_metadata:, file_set:)
Deprecation.warn('Use storage_adapter.upload, Fedora creates a `FileMetadata` (describedBy) implictly. ' \
'Query it with Hyrax.custom_queries.find_file_metadata_by(id: stored_file.id).')
io_wrapper = build_file(io_wrapper, file_metadata.type)
stored_file = storage_adapter.upload(file: io_wrapper,
original_filename: io_wrapper.original_filename,
content_type: io_wrapper.content_type,
resource: file_set,
use: Array(file_metadata.type).first,
id_hint: assign_id)
Hyrax.custom_queries.find_file_metadata_by(id: stored_file.id)
end
# @param file_metadata [Hyrax::FileMetadata] the metadata to represent the file
# @param file_set [Valkyrie::Resouce, Hydra::Works::FileSet] the associated FileSet # TODO: WINGS - Remove Hydra::Works::FileSet as a potential type when valkyrization is complete.
# @return [Hyrax::FileMetadata] the persisted metadata file_metadata that represents the file
def attach_file_metadata(file_metadata:, file_set:)
file_set.is_a?(::Valkyrie::Resource) ? attach_file_metadata_to_valkyrie_file_set(file_metadata, file_set) : file_metadata
end
private
##
# @api private
def attach_file_metadata_to_valkyrie_file_set(file_metadata, file_set)
# This is for storage adapters other than wings. The wings storage adapter already attached the file to the file_set.
# This process is a no-op for wings. # TODO: WINGS - May need to verify this is a no-op for wings once file_set is passed in as a resource.
# TODO: WINGS - Need to test this against other adapters once they are available for use.
existing_file_metadata = current_original_file(file_set) || file_metadata
file_metadata = existing_file_metadata.new(file_metadata.to_h.except(:id))
saved_file_metadata = persister.save(resource: file_metadata)
file_set.file_ids = [saved_file_metadata.id]
persister.save(resource: file_set)
saved_file_metadata
end
##
# @api private
# @return [Hyrax::FileMetadata, nil]
def current_original_file(file_set)
Hyrax.custom_queries.find_original_file(file_set: file_set)
rescue ::Valkyrie::Persistence::ObjectNotFoundError
nil
end
# Class for wrapping the file being ingested
class IoDecorator < SimpleDelegator
attr_reader :original_filename, :content_type, :length, :use, :tempfile
# @param [IO] io stream for the file content
# @param [String] original_filename
# @param [String] content_type
# @param [RDF::URI] use the URI for the PCDM predicate indicating the use for this resource
def initialize(io, original_filename, content_type, content_length, use)
@original_filename = original_filename
@content_type = content_type
@length = content_length
@use = use
@tempfile = io
super(io)
end
end
# Constructs the IoDecorator for ingesting the intermediate file
# @param [JobIOWrapper] io wrapper with details about the uploaded file
# @param [RDF::URI] use the URI for the PCDM predicate indicating the use for this resource
def build_file(io_wrapper, use)
IoDecorator.new(io_wrapper.file, io_wrapper.original_name, io_wrapper.mime_type, io_wrapper.size, use)
end
end
end
|
samvera/hyrax
|
lib/wings/services/file_metadata_builder.rb
|
Ruby
|
apache-2.0
| 4,551
|
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="@{Application.index()}" style="padding:3px;">&{'backend.title'}</a>
</div>
|
xandradx/ovirt-engine-disaster-recovery
|
app/views/tags/navigationheader.html
|
HTML
|
apache-2.0
| 427
|
/**
* 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.
*/
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { useParams, Link, useHistory } from 'react-router-dom';
import { t, styled, SupersetClient } from '@superset-ui/core';
import moment from 'moment';
import rison from 'rison';
import ActionsBar, { ActionProps } from 'src/components/ListView/ActionsBar';
import Button from 'src/components/Button';
import ConfirmStatusChange from 'src/components/ConfirmStatusChange';
import DeleteModal from 'src/components/DeleteModal';
import ListView, { ListViewProps } from 'src/components/ListView';
import SubMenu, { SubMenuProps } from 'src/components/Menu/SubMenu';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import { useListViewResource } from 'src/views/CRUD/hooks';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { AnnotationObject } from './types';
import AnnotationModal from './AnnotationModal';
const PAGE_SIZE = 25;
interface AnnotationListProps {
addDangerToast: (msg: string) => void;
addSuccessToast: (msg: string) => void;
}
function AnnotationList({
addDangerToast,
addSuccessToast,
}: AnnotationListProps) {
const { annotationLayerId }: any = useParams();
const {
state: {
loading,
resourceCount: annotationsCount,
resourceCollection: annotations,
bulkSelectEnabled,
},
fetchData,
refreshData,
toggleBulkSelect,
} = useListViewResource<AnnotationObject>(
`annotation_layer/${annotationLayerId}/annotation`,
t('annotation'),
addDangerToast,
false,
);
const [annotationModalOpen, setAnnotationModalOpen] = useState<boolean>(
false,
);
const [annotationLayerName, setAnnotationLayerName] = useState<string>('');
const [
currentAnnotation,
setCurrentAnnotation,
] = useState<AnnotationObject | null>(null);
const [
annotationCurrentlyDeleting,
setAnnotationCurrentlyDeleting,
] = useState<AnnotationObject | null>(null);
const handleAnnotationEdit = (annotation: AnnotationObject | null) => {
setCurrentAnnotation(annotation);
setAnnotationModalOpen(true);
};
const fetchAnnotationLayer = useCallback(
async function fetchAnnotationLayer() {
try {
const response = await SupersetClient.get({
endpoint: `/api/v1/annotation_layer/${annotationLayerId}`,
});
setAnnotationLayerName(response.json.result.name);
} catch (response) {
await getClientErrorObject(response).then(({ error }: any) => {
addDangerToast(error.error || error.statusText || error);
});
}
},
[annotationLayerId],
);
const handleAnnotationDelete = ({ id, short_descr }: AnnotationObject) => {
SupersetClient.delete({
endpoint: `/api/v1/annotation_layer/${annotationLayerId}/annotation/${id}`,
}).then(
() => {
refreshData();
setAnnotationCurrentlyDeleting(null);
addSuccessToast(t('Deleted: %s', short_descr));
},
createErrorHandler(errMsg =>
addDangerToast(
t('There was an issue deleting %s: %s', short_descr, errMsg),
),
),
);
};
const handleBulkAnnotationsDelete = (
annotationsToDelete: AnnotationObject[],
) => {
SupersetClient.delete({
endpoint: `/api/v1/annotation_layer/${annotationLayerId}/annotation/?q=${rison.encode(
annotationsToDelete.map(({ id }) => id),
)}`,
}).then(
({ json = {} }) => {
refreshData();
addSuccessToast(json.message);
},
createErrorHandler(errMsg =>
addDangerToast(
t('There was an issue deleting the selected annotations: %s', errMsg),
),
),
);
};
// get the Annotation Layer
useEffect(() => {
fetchAnnotationLayer();
}, [fetchAnnotationLayer]);
const initialSort = [{ id: 'short_descr', desc: true }];
const columns = useMemo(
() => [
{
accessor: 'short_descr',
Header: t('Label'),
},
{
accessor: 'long_descr',
Header: t('Description'),
},
{
Cell: ({
row: {
original: { start_dttm: startDttm },
},
}: any) => moment(new Date(startDttm)).format('ll'),
Header: t('Start'),
accessor: 'start_dttm',
},
{
Cell: ({
row: {
original: { end_dttm: endDttm },
},
}: any) => moment(new Date(endDttm)).format('ll'),
Header: t('End'),
accessor: 'end_dttm',
},
{
Cell: ({ row: { original } }: any) => {
const handleEdit = () => handleAnnotationEdit(original);
const handleDelete = () => setAnnotationCurrentlyDeleting(original);
const actions = [
{
label: 'edit-action',
tooltip: t('Edit annotation'),
placement: 'bottom',
icon: 'Edit',
onClick: handleEdit,
},
{
label: 'delete-action',
tooltip: t('Delete annotation'),
placement: 'bottom',
icon: 'Trash',
onClick: handleDelete,
},
];
return <ActionsBar actions={actions as ActionProps[]} />;
},
Header: t('Actions'),
id: 'actions',
disableSortBy: true,
},
],
[true, true],
);
const subMenuButtons: SubMenuProps['buttons'] = [];
subMenuButtons.push({
name: (
<>
<i className="fa fa-plus" /> {t('Annotation')}
</>
),
buttonStyle: 'primary',
onClick: () => {
handleAnnotationEdit(null);
},
});
subMenuButtons.push({
name: t('Bulk select'),
onClick: toggleBulkSelect,
buttonStyle: 'secondary',
'data-test': 'annotation-bulk-select',
});
const StyledHeader = styled.div`
display: flex;
flex-direction: row;
a,
Link {
margin-left: 16px;
font-size: 12px;
font-weight: normal;
text-decoration: underline;
}
`;
let hasHistory = true;
try {
useHistory();
} catch (err) {
// If error is thrown, we know not to use <Link> in render
hasHistory = false;
}
const EmptyStateButton = (
<Button
buttonStyle="primary"
onClick={() => {
handleAnnotationEdit(null);
}}
>
<>
<i className="fa fa-plus" /> {t('Annotation')}
</>
</Button>
);
const emptyState = {
message: t('No annotation yet'),
slot: EmptyStateButton,
};
return (
<>
<SubMenu
name={
<StyledHeader>
<span>{t(`Annotation Layer ${annotationLayerName}`)}</span>
<span>
{hasHistory ? (
<Link to="/annotationlayermodelview/list/">Back to all</Link>
) : (
<a href="/annotationlayermodelview/list/">Back to all</a>
)}
</span>
</StyledHeader>
}
buttons={subMenuButtons}
/>
<AnnotationModal
addDangerToast={addDangerToast}
addSuccessToast={addSuccessToast}
annotation={currentAnnotation}
show={annotationModalOpen}
onAnnotationAdd={() => refreshData()}
annnotationLayerId={annotationLayerId}
onHide={() => setAnnotationModalOpen(false)}
/>
{annotationCurrentlyDeleting && (
<DeleteModal
description={t(
`Are you sure you want to delete ${annotationCurrentlyDeleting?.short_descr}?`,
)}
onConfirm={() => {
if (annotationCurrentlyDeleting) {
handleAnnotationDelete(annotationCurrentlyDeleting);
}
}}
onHide={() => setAnnotationCurrentlyDeleting(null)}
open
title={t('Delete Annotation?')}
/>
)}
<ConfirmStatusChange
title={t('Please confirm')}
description={t(
'Are you sure you want to delete the selected annotations?',
)}
onConfirm={handleBulkAnnotationsDelete}
>
{confirmDelete => {
const bulkActions: ListViewProps['bulkActions'] = [
{
key: 'delete',
name: t('Delete'),
onSelect: confirmDelete,
type: 'danger',
},
];
return (
<ListView<AnnotationObject>
className="annotations-list-view"
bulkActions={bulkActions}
bulkSelectEnabled={bulkSelectEnabled}
columns={columns}
count={annotationsCount}
data={annotations}
disableBulkSelect={toggleBulkSelect}
emptyState={emptyState}
fetchData={fetchData}
initialSort={initialSort}
loading={loading}
pageSize={PAGE_SIZE}
/>
);
}}
</ConfirmStatusChange>
</>
);
}
export default withToasts(AnnotationList);
|
mistercrunch/panoramix
|
superset-frontend/src/views/CRUD/annotation/AnnotationList.tsx
|
TypeScript
|
apache-2.0
| 9,886
|
<?php
namespace CultuurNet\UDB3\Event\Events;
use CultuurNet\UDB3\Event\ValueObjects\Audience;
use CultuurNet\UDB3\Offer\Events\AbstractEvent;
final class AudienceUpdated extends AbstractEvent
{
/**
* @var Audience
*/
private $audience;
public function __construct(
string $itemId,
Audience $audience
) {
parent::__construct($itemId);
$this->audience = $audience;
}
public function getAudience(): Audience
{
return $this->audience;
}
public function serialize(): array
{
return parent::serialize() + [
'audience' => $this->audience->serialize(),
];
}
public static function deserialize(array $data): AudienceUpdated
{
return new self(
$data['item_id'],
Audience::deserialize($data['audience'])
);
}
}
|
cultuurnet/udb3-php
|
src/Event/Events/AudienceUpdated.php
|
PHP
|
apache-2.0
| 882
|
/*
* Copyright (c) 2012-2015, b3log.org
*
* 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 org.b3log.symphony.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.service.ArticleQueryService;
import org.b3log.symphony.service.TagQueryService;
import org.json.JSONObject;
/**
* Article processor.
*
* <ul>
* <li>Gets articles with the specified tags (/apis/articles?tags=tag1,tag2&p=1&size=10), GET</li>
* </ul>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.0, Oct 19, 2014
* @since 0.2.5
*/
@RequestProcessor
public class ArticleProcessor {
/**
* Tag query service.
*/
@Inject
private TagQueryService tagQueryService;
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* Gets articles.with the specified tags.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/apis/articles", method = HTTPRequestMethod.GET)
public void getTagsArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final JSONRenderer renderer = new JSONRenderer().setJSONP(true);
context.setRenderer(renderer);
String callback = request.getParameter("callback");
if (Strings.isEmptyOrNull(callback)) {
callback = "callback";
}
renderer.setCallback(callback);
final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final String pageSizeStr = request.getParameter("size");
if (Strings.isEmptyOrNull(pageSizeStr) || !Strings.isNumeric(pageSizeStr)) {
pageNumStr = "10";
}
final String tagsStr = request.getParameter("tags");
final String[] tagTitles = tagsStr.split(",");
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Integer.valueOf(pageSizeStr);
final List<JSONObject> tagList = new ArrayList<JSONObject>();
for (int i = 0; i < tagTitles.length; i++) {
final String tagTitle = tagTitles[i];
final JSONObject tag = tagQueryService.getTagByTitle(tagTitle);
if (null == tag) {
continue;
}
tagList.add(tag);
}
if (tagList.isEmpty()) {
ret.put(Article.ARTICLES, Collections.emptyList());
return;
}
final Map<String, Class<?>> articleFields = new HashMap<String, Class<?>>();
articleFields.put(Article.ARTICLE_TITLE, String.class);
articleFields.put(Article.ARTICLE_PERMALINK, String.class);
articleFields.put(Article.ARTICLE_CREATE_TIME, Long.class);
final List<JSONObject> articles = articleQueryService.getArticlesByTags(pageNum, pageSize,
articleFields, tagList.toArray(new JSONObject[0]));
for (final JSONObject article : articles) {
article.remove(Article.ARTICLE_T_PARTICIPANTS);
article.remove(Article.ARTICLE_T_PARTICIPANT_NAME);
article.remove(Article.ARTICLE_T_PARTICIPANT_THUMBNAIL_URL);
article.remove(Article.ARTICLE_LATEST_CMT_TIME);
article.remove(Article.ARTICLE_UPDATE_TIME);
article.put(Article.ARTICLE_CREATE_TIME, ((Date) article.get(Article.ARTICLE_CREATE_TIME)).getTime());
}
ret.put(Article.ARTICLES, articles);
}
}
|
leontius/symphony
|
src/main/java/org/b3log/symphony/api/ArticleProcessor.java
|
Java
|
apache-2.0
| 4,961
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.Data.Linq;
using Cassandra.Mapping;
using Cassandra.Tasks;
using Cassandra.Tests.Mapping.Pocos;
using Cassandra.Tests.Mapping.TestData;
using Moq;
using NUnit.Framework;
namespace Cassandra.Tests.Mapping.Linq
{
public class LinqMappingUnitTests : MappingTestBase
{
private ISession GetSession(RowSet result)
{
var clusterMock = new Mock<ICluster>();
clusterMock.Setup(c => c.Configuration).Returns(new Configuration());
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<IStatement>()))
.Returns(TestHelper.DelayedTask(result, 200))
.Verifiable();
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<IStatement>(), It.IsAny<string>()))
.Returns(TestHelper.DelayedTask(result, 200))
.Verifiable();
sessionMock.Setup(s => s.PrepareAsync(It.IsAny<string>())).Returns(TaskHelper.ToTask(GetPrepared("Mock query")));
sessionMock.Setup(s => s.BinaryProtocolVersion).Returns(2);
sessionMock.Setup(s => s.Cluster).Returns(clusterMock.Object);
return sessionMock.Object;
}
[Test]
public void Linq_CqlQueryBase_Execute_Empty_RowSet()
{
var table = GetSession(new RowSet()).GetTable<PlainUser>();
var entities = table.Where(a => a.UserId == Guid.Empty).Execute();
Assert.AreEqual(0, entities.Count());
}
[Test]
public void Linq_CqlQueryBase_Execute_Maps_Rows()
{
var usersExpected = TestDataHelper.GetUserList();
var table = new Table<PlainUser>(GetSession(TestDataHelper.GetUsersRowSet(usersExpected)));
var users = table.Execute().ToList();
CollectionAssert.AreEqual(usersExpected, users, new TestHelper.PropertyComparer());
}
[Test]
public void Linq_CqlQueryBase_Execute_SingleColumn_Rows()
{
var table = new Table<int>(GetSession(TestDataHelper.GetSingleValueRowSet("int_val", 1)));
var result = table.Execute().ToList();
CollectionAssert.AreEqual(new[] { 1 }, result.ToArray(), new TestHelper.PropertyComparer());
}
[Test]
public void Linq_CqlQueryBase_Execute_Anonymous_Type()
{
var table = GetSession(TestDataHelper.CreateMultipleValuesRowSet(new[] { "IntValue", "Int64Value" }, new[] { 25, 1000 })).GetTable<AllTypesEntity>();
var result = (from e in table select new { user_age = e.IntValue, identifier = e.Int64Value }).Execute().ToList();
Assert.AreEqual(1000L, result[0].identifier);
Assert.AreEqual(25, result[0].user_age);
}
[Test]
public void Linq_CqlQueryBase_Execute_Anonymous_Single_Value_Type()
{
//It does not have much sense to use an anonymous type with a single value but here it goes!
var table = GetSession(TestDataHelper.CreateMultipleValuesRowSet(new[] { "intvalue" }, new[] { 25 })).GetTable<AllTypesEntity>();
var result = (from e in table select new { user_age = e.IntValue }).Execute().ToList();
Assert.AreEqual(25, result[0].user_age);
}
[Test]
public void Linq_CqlQueryBase_Execute_NoDefaultConstructor()
{
var table = GetSession(TestDataHelper.CreateMultipleValuesRowSet(new[] { "intvalue", "int64value" }, new[] { 25, 1000 })).GetTable<AllTypesEntity>();
var result = (from e in table select new Tuple<int, long>(e.IntValue, e.Int64Value)).Execute().ToList();
Assert.AreEqual(25, result[0].Item1);
Assert.AreEqual(1000L, result[0].Item2);
}
[Test]
public void Linq_CqlQuery_ExecutePaged_Maps_Rows()
{
var usersExpected = TestDataHelper.GetUserList();
var rs = TestDataHelper.GetUsersRowSet(usersExpected);
rs.AutoPage = false;
rs.PagingState = new byte[] { 1, 2, 3 };
var table = new Table<PlainUser>(GetSession(rs));
IPage<PlainUser> users = table.ExecutePaged();
//It was executed without paging state
Assert.Null(users.CurrentPagingState);
Assert.NotNull(users.PagingState);
CollectionAssert.AreEqual(rs.PagingState, users.PagingState);
CollectionAssert.AreEqual(usersExpected, users, new TestHelper.PropertyComparer());
}
[Test]
public void Linq_CqlQuery_ExecutePaged_Maps_SingleValues()
{
var rs = TestDataHelper.GetSingleColumnRowSet("int_val", new[] { 100, 200, 300 });
rs.AutoPage = false;
rs.PagingState = new byte[] { 2, 2, 2 };
var table = new Table<int>(GetSession(rs));
IPage<int> page = table.SetPagingState(new byte[] { 1, 1, 1 }).ExecutePaged();
CollectionAssert.AreEqual(table.PagingState, page.CurrentPagingState);
CollectionAssert.AreEqual(rs.PagingState, page.PagingState);
CollectionAssert.AreEqual(new[] { 100, 200, 300 }, page.ToArray(), new TestHelper.PropertyComparer());
}
[Test]
public void Linq_CqlQuery_Automatically_Pages()
{
const int pageLength = 100;
var clusterMock = new Mock<ICluster>();
clusterMock.Setup(c => c.Configuration).Returns(new Configuration());
var rs = TestDataHelper.GetSingleColumnRowSet("int_val", Enumerable.Repeat(1, pageLength).ToArray());
BoundStatement stmt = null;
var sessionMock = new Mock<ISession>(MockBehavior.Strict);
sessionMock.Setup(s => s.Cluster).Returns(clusterMock.Object);
sessionMock.Setup(s => s.Keyspace).Returns<string>(null);
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>()))
.Returns(TestHelper.DelayedTask(rs))
.Callback<IStatement>(s => stmt = (BoundStatement)s)
.Verifiable();
sessionMock
.Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>()))
.Returns(TestHelper.DelayedTask(rs))
.Callback<IStatement, string>((s, profile) => stmt = (BoundStatement)s)
.Verifiable();
sessionMock.Setup(s => s.PrepareAsync(It.IsAny<string>())).Returns(TaskHelper.ToTask(GetPrepared("Mock query")));
sessionMock.Setup(s => s.BinaryProtocolVersion).Returns(2);
rs.AutoPage = true;
rs.PagingState = new byte[] { 0, 0, 0 };
var counter = 0;
rs.SetFetchNextPageHandler(state =>
{
var rs2 = TestDataHelper.GetSingleColumnRowSet("int_val", Enumerable.Repeat(1, pageLength).ToArray());
if (++counter < 2)
{
rs2.PagingState = new byte[] { 0, 0, (byte)counter };
}
return Task.FromResult(rs2);
}, int.MaxValue);
var table = new Table<int>(sessionMock.Object);
IEnumerable<int> results = table.Execute();
Assert.True(stmt.AutoPage);
Assert.AreEqual(0, counter);
Assert.AreEqual(pageLength * 3, results.Count());
Assert.AreEqual(2, counter);
}
}
}
|
mintsoft/csharp-driver
|
src/Cassandra.Tests/Mapping/Linq/LinqMappingUnitTests.cs
|
C#
|
apache-2.0
| 7,650
|
# -*- coding: utf-8 -*-
"""
gspread
~~~~~~~
Google Spreadsheets client library.
"""
__version__ = '0.2.1'
__author__ = 'Anton Burnashev'
from .client import Client, login
from .models import Spreadsheet, Worksheet, Cell
from .exceptions import (GSpreadException, AuthenticationError,
SpreadsheetNotFound, NoValidUrlKeyFound,
IncorrectCellLabel, WorksheetNotFound,
UpdateCellError, RequestError)
|
CPedrini/TateTRES
|
gspread/__init__.py
|
Python
|
apache-2.0
| 475
|
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>Model Abstracts with Biological Entities (English) - 75 Topics / Sub-Topic Model 01 - 15 Topics</title>
<style>
table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2;}
tr:hover {background-color: #ddd;}
th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #0099FF;
color: white;
}
</style>
</head>
<body>
<h2>Model Abstracts with Biological Entities (English) - 75 Topics / Sub-Topic Model 01 - 15 Topics</h2>
<ul>
<li> <a href="pyldavis_text-ents-en-75-t01_15.html" target="_blank">Topic Visualization</a>
<li> <a href="relevant_terms.html" target="_blank">Relevant Terms</a>
<li> <a href="#trends">Topic Trends</a>
</ul>
<h3>Summary</h3>
<ul>
<li><em>Corpus Name:</em> Abstracts with Biological Entities (English) - 75 Topics / Sub-Topic Model 01
<li><em>Number of Topics:</em> 15
<li><em>Original Corpus Size:</em> 478
<li><em>Total Unique Documents:</em> 473
<li><em>Documents Repeated Across Topics:</em> 223
<li><em>Documents Mentioning COVID-19 (or Coronavirus):</em> 8
<li><em>Dataset:</em> 2020-04-24-v9
<li><em>Corpus ID:</em> text-ents-en-75-t01
</ul>
<h3>Overview</h3><p/>
<div><table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th><a href="relevant_terms.html" target="_blank">Relevant Terms</a></th>
<th>Documents</th>
<th>Abstract Mentions COVID-19</th>
</tr>
<tr>
<th>topic</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>t01</th>
<td>chapter, research, process, important, based, results, paper, information, study, potential</td>
<td><a href="Topic_01.html" target="_blank">228</a></td>
<td>4</td>
</tr>
<tr>
<th>t02</th>
<td>viruses, host(s), viral, virus, evolutionary, evolution, genetic, genomes, parasites</td>
<td><a href="Topic_02.html" target="_blank">78</a></td>
<td>0</td>
</tr>
<tr>
<th>t03</th>
<td>disease(s), infectious, epidemiological, infectious_disease(s), epidemic(s), outbreaks, infections</td>
<td><a href="Topic_03.html" target="_blank">43</a></td>
<td>3</td>
</tr>
<tr>
<th>t04</th>
<td>global, governance, health, china, regional, kong, airport, urban, space, hong</td>
<td><a href="Topic_04.html" target="_blank">37</a></td>
<td>0</td>
</tr>
<tr>
<th>t05</th>
<td>care, health, patient(s), ethical, hospital, choices, illness, transfusion, blood</td>
<td><a href="Topic_05.html" target="_blank">45</a></td>
<td>1</td>
</tr>
<tr>
<th>t06</th>
<td>network(s), pattern, tfs, multipartitism, individuals, interaction, complexes, antibodies, amino</td>
<td><a href="Topic_06.html" target="_blank">32</a></td>
<td>1</td>
</tr>
<tr>
<th>t07</th>
<td>membrane, protein(s), cell(s), ribosome, mrna, lipids, surface, transport</td>
<td><a href="Topic_07.html" target="_blank">35</a></td>
<td>0</td>
</tr>
<tr>
<th>t08</th>
<td>disaster(s), security, climate, hazards, climate_change, change, EWS, green, human</td>
<td><a href="Topic_08.html" target="_blank">35</a></td>
<td>0</td>
</tr>
<tr>
<th>t09</th>
<td>science, life, labour, definitions, solar, rosen, terminologies, rules, compounds, solar_system</td>
<td><a href="Topic_09.html" target="_blank">29</a></td>
<td>0</td>
</tr>
<tr>
<th>t10</th>
<td>species, niche, habitat, abundance, invasions, trait, forest, crocodilians, community, commercial</td>
<td><a href="Topic_10.html" target="_blank">16</a></td>
<td>0</td>
</tr>
<tr>
<th>t11</th>
<td>recombination, RNA, DNA, taxonomy, rdrp, HPV, sequencing, taxonomic, ACE2, fidelity</td>
<td><a href="Topic_11.html" target="_blank">24</a></td>
<td>1</td>
</tr>
<tr>
<th>t12</th>
<td>attack, influenza, biological, disorders, microglia, domestication, GOF, pneumonia, biological_agents, FIPV</td>
<td><a href="Topic_12.html" target="_blank">28</a></td>
<td>0</td>
</tr>
<tr>
<th>t13</th>
<td>SARS, nurses, trna(s), outbreak, respiratory, 2003, adolescents, acute_respiratory_syndrome, ebola</td>
<td><a href="Topic_13.html" target="_blank">22</a></td>
<td>1</td>
</tr>
<tr>
<th>t14</th>
<td>experimental, learning, >, primer, probe, divergence, 3′-end, cell_culture, designs, PCR</td>
<td><a href="Topic_14.html" target="_blank">23</a></td>
<td>1</td>
</tr>
<tr>
<th>t15</th>
<td>bat(s), maintenance, buildings, ⁎, waste, treatments, wine, LRDI, ebolaviruses</td>
<td><a href="Topic_15.html" target="_blank">21</a></td>
<td>0</td>
</tr>
</tbody>
</table></div>
<h3 id="trends">Trends</h3>
<img src="topic_trends.png" border="1" width="1200px">
</body>
</html>
|
roaminsight/roamresearch
|
docs/CORD19_topics/cord19-2020-04-24-v9/text-ents-en-75-t01-15/index.html
|
HTML
|
apache-2.0
| 5,291
|
<html>
<head>
<title>Diff Speed Test</title>
</head>
<body>
<h1>Diff Speed Test</h1>
<FORM action="#" onsubmit="return false">
<TABLE WIDTH="100%"><TR>
<TD WIDTH="50%">
<H3>Text Version 1:</H3>
<TEXTAREA ID="text1" STYLE="width: 100%" ROWS=10>This is a '''list of newspapers published by [[Journal Register Company]]'''.
The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]] and [[Pennsylvania]], organized in six geographic "clusters":<ref>[http://www.journalregister.com/newspapers.html Journal Register Company: Our Newspapers], accessed February 10, 2008.</ref>
== Capital-Saratoga ==
Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com].
* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]]
* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]]
* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]]
* Weeklies:
** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]]
** ''Rome Observer'' of [[Rome, New York]]
** ''Life & Times of Utica'' of [[Utica, New York]]
== Connecticut ==
Five dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com].
* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]]
* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]]
* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]]
* [[New Haven Register#Competitors|Elm City Newspapers]] {{WS|ctcentral.com}}
** ''The Advertiser'' of [[East Haven, Connecticut|East Haven]]
** ''Hamden Chronicle'' of [[Hamden, Connecticut|Hamden]]
** ''Milford Weekly'' of [[Milford, Connecticut|Milford]]
** ''The Orange Bulletin'' of [[Orange, Connecticut|Orange]]
** ''The Post'' of [[North Haven, Connecticut|North Haven]]
** ''Shelton Weekly'' of [[Shelton, Connecticut|Shelton]]
** ''The Stratford Bard'' of [[Stratford, Connecticut|Stratford]]
** ''Wallingford Voice'' of [[Wallingford, Connecticut|Wallingford]]
** ''West Haven News'' of [[West Haven, Connecticut|West Haven]]
* Housatonic Publications
** ''The New Milford Times'' {{WS|newmilfordtimes.com}} of [[New Milford, Connecticut|New Milford]]
** ''The Brookfield Journal'' of [[Brookfield, Connecticut|Brookfield]]
** ''The Kent Good Times Dispatch'' of [[Kent, Connecticut|Kent]]
** ''The Bethel Beacon'' of [[Bethel, Connecticut|Bethel]]
** ''The Litchfield Enquirer'' of [[Litchfield, Connecticut|Litchfield]]
** ''Litchfield County Times'' of [[Litchfield, Connecticut|Litchfield]]
* Imprint Newspapers {{WS|imprintnewspapers.com}}
** ''West Hartford News'' of [[West Hartford, Connecticut|West Hartford]]
** ''Windsor Journal'' of [[Windsor, Connecticut|Windsor]]
** ''Windsor Locks Journal'' of [[Windsor Locks, Connecticut|Windsor Locks]]
** ''Avon Post'' of [[Avon, Connecticut|Avon]]
** ''Farmington Post'' of [[Farmington, Connecticut|Farmington]]
** ''Simsbury Post'' of [[Simsbury, Connecticut|Simsbury]]
** ''Tri-Town Post'' of [[Burlington, Connecticut|Burlington]], [[Canton, Connecticut|Canton]] and [[Harwinton, Connecticut|Harwinton]]
* Minuteman Publications
** ''[[Fairfield Minuteman]]'' of [[Fairfield, Connecticut|Fairfield]]
** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]]
* Shoreline Newspapers weeklies:
** ''Branford Review'' of [[Branford, Connecticut|Branford]]
** ''Clinton Recorder'' of [[Clinton, Connecticut|Clinton]]
** ''The Dolphin'' of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]]
** ''Main Street News'' {{WS|ctmainstreetnews.com}} of [[Essex, Connecticut|Essex]]
** ''Pictorial Gazette'' of [[Old Saybrook, Connecticut|Old Saybrook]]
** ''Regional Express'' of [[Colchester, Connecticut|Colchester]]
** ''Regional Standard'' of [[Colchester, Connecticut|Colchester]]
** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]]
** ''Shore View East'' of [[Madison, Connecticut|Madison]]
** ''Shore View West'' of [[Guilford, Connecticut|Guilford]]
* Other weeklies:
** ''Registro'' {{WS|registroct.com}} of [[New Haven, Connecticut|New Haven]]
** ''Thomaston Express'' {{WS|thomastownexpress.com}} of [[Thomaston, Connecticut|Thomaston]]
** ''Foothills Traders'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton
== Michigan ==
Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com]
* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]]
* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]]
* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]]
* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]]
* Heritage Newspapers {{WS|heritage.com}}
** ''Belleville View''
** ''Ile Camera''
** ''Monroe Guardian''
** ''Ypsilanti Courier''
** ''News-Herald''
** ''Press & Guide''
** ''Chelsea Standard & Dexter Leader''
** ''Manchester Enterprise''
** ''Milan News-Leader''
** ''Saline Reporter''
* Independent Newspapers {{WS|sourcenewspapers.com}}
** ''Advisor''
** ''Source''
* Morning Star {{WS|morningstarpublishing.com}}
** ''Alma Reminder''
** ''Alpena Star''
** ''Antrim County News''
** ''Carson City Reminder''
** ''The Leader & Kalkaskian''
** ''Ogemaw/Oscoda County Star''
** ''Petoskey/Charlevoix Star''
** ''Presque Isle Star''
** ''Preview Community Weekly''
** ''Roscommon County Star''
** ''St. Johns Reminder''
** ''Straits Area Star''
** ''The (Edmore) Advertiser''
* Voice Newspapers {{WS|voicenews.com}}
** ''Armada Times''
** ''Bay Voice''
** ''Blue Water Voice''
** ''Downriver Voice''
** ''Macomb Township Voice''
** ''North Macomb Voice''
** ''Weekend Voice''
** ''Suburban Lifestyles'' {{WS|suburbanlifestyles.com}}
== Mid-Hudson ==
One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com].
* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]]
== Ohio ==
Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com].
* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]]
* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]]
== Philadelphia area ==
Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com].
* ''The Daily Local'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]]
* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos
* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]]
* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania|Phoenixville]]
* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]]
* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]]
* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]]
* Weeklies
** ''El Latino Expreso'' of [[Trenton, New Jersey]]
** ''La Voz'' of [[Norristown, Pennsylvania]]
** ''The Village News'' of [[Downingtown, Pennsylvania]]
** ''The Times Record'' of [[Kennett Square, Pennsylvania]]
** ''The Tri-County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]]
** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}}of [[Havertown, Pennsylvania]]
** ''Main Line Times'' {{WS|mainlinetimes.com}}of [[Ardmore, Pennsylvania]]
** ''Penny Pincher'' of [[Pottstown, Pennsylvania]]
** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]]
* Chesapeake Publishing {{WS|pa8newsgroup.com}}
** ''Solanco Sun Ledger'' of [[Quarryville, Pennsylvania]]
** ''Columbia Ledger'' of [[Columbia, Pennsylvania]]
** ''Coatesville Ledger'' of [[Downingtown, Pennsylvania]]
** ''Parkesburg Post Ledger'' of [[Quarryville, Pennsylvania]]
** ''Downingtown Ledger'' of [[Downingtown, Pennsylvania]]
** ''The Kennett Paper'' of [[Kennett Square, Pennsylvania]]
** ''Avon Grove Sun'' of [[West Grove, Pennsylvania]]
** ''Oxford Tribune'' of [[Oxford, Pennsylvania]]
** ''Elizabethtown Chronicle'' of [[Elizabethtown, Pennsylvania]]
** ''Donegal Ledger'' of [[Donegal, Pennsylvania]]
** ''Chadds Ford Post'' of [[Chadds Ford, Pennsylvania]]
** ''The Central Record'' of [[Medford, New Jersey]]
** ''Maple Shade Progress'' of [[Maple Shade, New Jersey]]
* Intercounty Newspapers {{WS|buckslocalnews.com}}
** ''The Review'' of Roxborough, Pennsylvania
** ''The Recorder'' of [[Conshohocken, Pennsylvania]]
** ''The Leader'' of [[Mount Airy, Pennsylvania|Mount Airy]] and West Oak Lake, Pennsylvania
** ''The Pennington Post'' of [[Pennington, New Jersey]]
** ''The Bristol Pilot'' of [[Bristol, Pennsylvania]]
** ''Yardley News'' of [[Yardley, Pennsylvania]]
** ''New Hope Gazette'' of [[New Hope, Pennsylvania]]
** ''Doylestown Patriot'' of [[Doylestown, Pennsylvania]]
** ''Newtown Advance'' of [[Newtown, Pennsylvania]]
** ''The Plain Dealer'' of [[Williamstown, New Jersey]]
** ''News Report'' of [[Sewell, New Jersey]]
** ''Record Breeze'' of [[Berlin, New Jersey]]
** ''Newsweekly'' of [[Moorestown, New Jersey]]
** ''Haddon Herald'' of [[Haddonfield, New Jersey]]
** ''New Egypt Press'' of [[New Egypt, New Jersey]]
** ''Community News'' of [[Pemberton, New Jersey]]
** ''Plymouth Meeting Journal'' of [[Plymouth Meeting, Pennsylvania]]
** ''Lafayette Hill Journal'' of [[Lafayette Hill, Pennsylvania]]
* Montgomery Newspapers {{WS|montgomerynews.com}}
** ''Ambler Gazette'' of [[Ambler, Pennsylvania]]
** ''Central Bucks Life'' of [[Bucks County, Pennsylvania]]
** ''The Colonial'' of [[Plymouth Meeting, Pennsylvania]]
** ''Glenside News'' of [[Glenside, Pennsylvania]]
** ''The Globe'' of [[Lower Moreland Township, Pennsylvania]]
** ''Main Line Life'' of [[Ardmore, Pennsylvania]]
** ''Montgomery Life'' of [[Fort Washington, Pennsylvania]]
** ''North Penn Life'' of [[Lansdale, Pennsylvania]]
** ''Perkasie News Herald'' of [[Perkasie, Pennsylvania]]
** ''Public Spirit'' of [[Hatboro, Pennsylvania]]
** ''Souderton Independent'' of [[Souderton, Pennsylvania]]
** ''Springfield Sun'' of [[Springfield, Pennsylvania]]
** ''Spring-Ford Reporter'' of [[Royersford, Pennsylvania]]
** ''Times Chronicle'' of [[Jenkintown, Pennsylvania]]
** ''Valley Item'' of [[Perkiomenville, Pennsylvania]]
** ''Willow Grove Guide'' of [[Willow Grove, Pennsylvania]]
* News Gleaner Publications (closed December 2008) {{WS|newsgleaner.com}}
** ''Life Newspapers'' of [[Philadelphia, Pennsylvania]]
* Suburban Publications
** ''The Suburban & Wayne Times'' {{WS|waynesuburban.com}} of [[Wayne, Pennsylvania]]
** ''The Suburban Advertiser'' of [[Exton, Pennsylvania]]
** ''The King of Prussia Courier'' of [[King of Prussia, Pennsylvania]]
* Press Newspapers {{WS|countypressonline.com}}
** ''County Press'' of [[Newtown Square, Pennsylvania]]
** ''Garnet Valley Press'' of [[Glen Mills, Pennsylvania]]
** ''Haverford Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009)
** ''Hometown Press'' of [[Glen Mills, Pennsylvania]] (closed January 2009)
** ''Media Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009)
** ''Springfield Press'' of [[Springfield, Pennsylvania]]
* Berks-Mont Newspapers {{WS|berksmontnews.com}}
** ''The Boyertown Area Times'' of [[Boyertown, Pennsylvania]]
** ''The Kutztown Area Patriot'' of [[Kutztown, Pennsylvania]]
** ''The Hamburg Area Item'' of [[Hamburg, Pennsylvania]]
** ''The Southern Berks News'' of [[Exeter Township, Berks County, Pennsylvania]]
** ''The Free Press'' of [[Quakertown, Pennsylvania]]
** ''The Saucon News'' of [[Quakertown, Pennsylvania]]
** ''Westside Weekly'' of [[Reading, Pennsylvania]]
* Magazines
** ''Bucks Co. Town & Country Living''
** ''Chester Co. Town & Country Living''
** ''Montomgery Co. Town & Country Living''
** ''Garden State Town & Country Living''
** ''Montgomery Homes''
** ''Philadelphia Golfer''
** ''Parents Express''
** ''Art Matters''
{{JRC}}
==References==
<references />
[[Category:Journal Register publications|*]]
</TEXTAREA></TD>
<TD WIDTH="50%">
<H3>Text Version 2:</H3>
<TEXTAREA ID="text2" STYLE="width: 100%" ROWS=10>This is a '''list of newspapers published by [[Journal Register Company]]'''.
The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]], [[Pennsylvania]] and [[New Jersey]], organized in six geographic "clusters":<ref>[http://www.journalregister.com/publications.html Journal Register Company: Our Publications], accessed April 21, 2010.</ref>
== Capital-Saratoga ==
Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com].
* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]]
* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]]
* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]]
* Weeklies:
** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]]
** ''Rome Observer'' {{WS|romeobserver.com}} of [[Rome, New York]]
** ''WG Life '' {{WS|saratogian.com/wglife/}} of [[Wilton, New York]]
** ''Ballston Spa Life '' {{WS|saratogian.com/bspalife}} of [[Ballston Spa, New York]]
** ''Greenbush Life'' {{WS|troyrecord.com/greenbush}} of [[Troy, New York]]
** ''Latham Life'' {{WS|troyrecord.com/latham}} of [[Latham, New York]]
** ''River Life'' {{WS|troyrecord.com/river}} of [[Troy, New York]]
== Connecticut ==
Three dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com].
* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]]
* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]]
* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]]
* Housatonic Publications
** ''The Housatonic Times'' {{WS|housatonictimes.com}} of [[New Milford, Connecticut|New Milford]]
** ''Litchfield County Times'' {{WS|countytimes.com}} of [[Litchfield, Connecticut|Litchfield]]
* Minuteman Publications
** ''[[Fairfield Minuteman]]'' {{WS|fairfieldminuteman.com}}of [[Fairfield, Connecticut|Fairfield]]
** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]]
* Shoreline Newspapers
** ''The Dolphin'' {{WS|dolphin-news.com}} of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]]
** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]]
* Foothills Media Group {{WS|foothillsmediagroup.com}}
** ''Thomaston Express'' {{WS|thomastonexpress.com}} of [[Thomaston, Connecticut|Thomaston]]
** ''Good News About Torrington'' {{WS|goodnewsabouttorrington.com}} of [[Torrington, Connecticut|Torrington]]
** ''Granby News'' {{WS|foothillsmediagroup.com/granby}} of [[Granby, Connecticut|Granby]]
** ''Canton News'' {{WS|foothillsmediagroup.com/canton}} of [[Canton, Connecticut|Canton]]
** ''Avon News'' {{WS|foothillsmediagroup.com/avon}} of [[Avon, Connecticut|Avon]]
** ''Simsbury News'' {{WS|foothillsmediagroup.com/simsbury}} of [[Simsbury, Connecticut|Simsbury]]
** ''Litchfield News'' {{WS|foothillsmediagroup.com/litchfield}} of [[Litchfield, Connecticut|Litchfield]]
** ''Foothills Trader'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton
* Other weeklies
** ''The Milford-Orange Bulletin'' {{WS|ctbulletin.com}} of [[Orange, Connecticut|Orange]]
** ''The Post-Chronicle'' {{WS|ctpostchronicle.com}} of [[North Haven, Connecticut|North Haven]]
** ''West Hartford News'' {{WS|westhartfordnews.com}} of [[West Hartford, Connecticut|West Hartford]]
* Magazines
** ''The Connecticut Bride'' {{WS|connecticutmag.com}}
** ''Connecticut Magazine'' {{WS|theconnecticutbride.com}}
** ''Passport Magazine'' {{WS|passport-mag.com}}
== Michigan ==
Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com]
* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]]
* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]]
* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]]
* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]]
* Heritage Newspapers {{WS|heritage.com}}
** ''Belleville View'' {{WS|bellevilleview.com}}
** ''Ile Camera'' {{WS|thenewsherald.com/ile_camera}}
** ''Monroe Guardian'' {{WS|monreguardian.com}}
** ''Ypsilanti Courier'' {{WS|ypsilanticourier.com}}
** ''News-Herald'' {{WS|thenewsherald.com}}
** ''Press & Guide'' {{WS|pressandguide.com}}
** ''Chelsea Standard & Dexter Leader'' {{WS|chelseastandard.com}}
** ''Manchester Enterprise'' {{WS|manchesterguardian.com}}
** ''Milan News-Leader'' {{WS|milannews.com}}
** ''Saline Reporter'' {{WS|salinereporter.com}}
* Independent Newspapers
** ''Advisor'' {{WS|sourcenewspapers.com}}
** ''Source'' {{WS|sourcenewspapers.com}}
* Morning Star {{WS|morningstarpublishing.com}}
** ''The Leader & Kalkaskian'' {{WS|leaderandkalkaskian.com}}
** ''Grand Traverse Insider'' {{WS|grandtraverseinsider.com}}
** ''Alma Reminder''
** ''Alpena Star''
** ''Ogemaw/Oscoda County Star''
** ''Presque Isle Star''
** ''St. Johns Reminder''
* Voice Newspapers {{WS|voicenews.com}}
** ''Armada Times''
** ''Bay Voice''
** ''Blue Water Voice''
** ''Downriver Voice''
** ''Macomb Township Voice''
** ''North Macomb Voice''
** ''Weekend Voice''
== Mid-Hudson ==
One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com].
* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]]
* ''Las Noticias'' {{WS|lasnoticiasny.com}} of [[Kingston, New York]]
== Ohio ==
Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com].
* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]]
* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]]
* ''El Latino Expreso'' {{WS|lorainlatino.com}} of [[Lorain, Ohio|Lorain]]
== Philadelphia area ==
Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com].
* ''[[The Daily Local News]]'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]]
* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos [[Upper Darby Township, Pennsylvania]]
* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]]
* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]]
* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]]
* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]]
* Weeklies
* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania]]
** ''El Latino Expreso'' {{WS|njexpreso.com}} of [[Trenton, New Jersey]]
** ''La Voz'' {{WS|lavozpa.com}} of [[Norristown, Pennsylvania]]
** ''The Tri County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]]
** ''Penny Pincher'' {{WS|pennypincherpa.com}}of [[Pottstown, Pennsylvania]]
* Chesapeake Publishing {{WS|southernchestercountyweeklies.com}}
** ''The Kennett Paper'' {{WS|kennettpaper.com}} of [[Kennett Square, Pennsylvania]]
** ''Avon Grove Sun'' {{WS|avongrovesun.com}} of [[West Grove, Pennsylvania]]
** ''The Central Record'' {{WS|medfordcentralrecord.com}} of [[Medford, New Jersey]]
** ''Maple Shade Progress'' {{WS|mapleshadeprogress.com}} of [[Maple Shade, New Jersey]]
* Intercounty Newspapers {{WS|buckslocalnews.com}} {{WS|southjerseylocalnews.com}}
** ''The Pennington Post'' {{WS|penningtonpost.com}} of [[Pennington, New Jersey]]
** ''The Bristol Pilot'' {{WS|bristolpilot.com}} of [[Bristol, Pennsylvania]]
** ''Yardley News'' {{WS|yardleynews.com}} of [[Yardley, Pennsylvania]]
** ''Advance of Bucks County'' {{WS|advanceofbucks.com}} of [[Newtown, Pennsylvania]]
** ''Record Breeze'' {{WS|recordbreeze.com}} of [[Berlin, New Jersey]]
** ''Community News'' {{WS|sjcommunitynews.com}} of [[Pemberton, New Jersey]]
* Montgomery Newspapers {{WS|montgomerynews.com}}
** ''Ambler Gazette'' {{WS|amblergazette.com}} of [[Ambler, Pennsylvania]]
** ''The Colonial'' {{WS|colonialnews.com}} of [[Plymouth Meeting, Pennsylvania]]
** ''Glenside News'' {{WS|glensidenews.com}} of [[Glenside, Pennsylvania]]
** ''The Globe'' {{WS|globenewspaper.com}} of [[Lower Moreland Township, Pennsylvania]]
** ''Montgomery Life'' {{WS|montgomerylife.com}} of [[Fort Washington, Pennsylvania]]
** ''North Penn Life'' {{WS|northpennlife.com}} of [[Lansdale, Pennsylvania]]
** ''Perkasie News Herald'' {{WS|perkasienewsherald.com}} of [[Perkasie, Pennsylvania]]
** ''Public Spirit'' {{WS|thepublicspirit.com}} of [[Hatboro, Pennsylvania]]
** ''Souderton Independent'' {{WS|soudertonindependent.com}} of [[Souderton, Pennsylvania]]
** ''Springfield Sun'' {{WS|springfieldsun.com}} of [[Springfield, Pennsylvania]]
** ''Spring-Ford Reporter'' {{WS|springfordreporter.com}} of [[Royersford, Pennsylvania]]
** ''Times Chronicle'' {{WS|thetimeschronicle.com}} of [[Jenkintown, Pennsylvania]]
** ''Valley Item'' {{WS|valleyitem.com}} of [[Perkiomenville, Pennsylvania]]
** ''Willow Grove Guide'' {{WS|willowgroveguide.com}} of [[Willow Grove, Pennsylvania]]
** ''The Review'' {{WS|roxreview.com}} of [[Roxborough, Philadelphia, Pennsylvania]]
* Main Line Media News {{WS|mainlinemedianews.com}}
** ''Main Line Times'' {{WS|mainlinetimes.com}} of [[Ardmore, Pennsylvania]]
** ''Main Line Life'' {{WS|mainlinelife.com}} of [[Ardmore, Pennsylvania]]
** ''The King of Prussia Courier'' {{WS|kingofprussiacourier.com}} of [[King of Prussia, Pennsylvania]]
* Delaware County News Network {{WS|delconewsnetwork.com}}
** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}} of [[Havertown, Pennsylvania]]
** ''County Press'' {{WS|countypressonline.com}} of [[Newtown Square, Pennsylvania]]
** ''Garnet Valley Press'' {{WS|countypressonline.com}} of [[Glen Mills, Pennsylvania]]
** ''Springfield Press'' {{WS|countypressonline.com}} of [[Springfield, Pennsylvania]]
** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]]
* Berks-Mont Newspapers {{WS|berksmontnews.com}}
** ''The Boyertown Area Times'' {{WS|berksmontnews.com/boyertown_area_times}} of [[Boyertown, Pennsylvania]]
** ''The Kutztown Area Patriot'' {{WS|berksmontnews.com/kutztown_area_patriot}} of [[Kutztown, Pennsylvania]]
** ''The Hamburg Area Item'' {{WS|berksmontnews.com/hamburg_area_item}} of [[Hamburg, Pennsylvania]]
** ''The Southern Berks News'' {{WS|berksmontnews.com/southern_berks_news}} of [[Exeter Township, Berks County, Pennsylvania]]
** ''Community Connection'' {{WS|berksmontnews.com/community_connection}} of [[Boyertown, Pennsylvania]]
* Magazines
** ''Bucks Co. Town & Country Living'' {{WS|buckscountymagazine.com}}
** ''Parents Express'' {{WS|parents-express.com}}
** ''Real Men, Rednecks'' {{WS|realmenredneck.com}}
{{JRC}}
==References==
<references />
[[Category:Journal Register publications|*]]
</TEXTAREA></TD>
</TR></TABLE>
<P><INPUT TYPE="button" ID="launch" VALUE="Compute Diff"></P>
</FORM>
<DIV ID="outputdiv">Error: Dart is not running.</DIV>
<script type="text/javascript" src="Speedtest.dart.app.js"></script>
</body>
</html>
|
bystep15/google-diff-match-patch
|
speedtest/dart/Speedtest.html
|
HTML
|
apache-2.0
| 25,605
|
package com.jess.arms.common.photo;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageUtils {
// 获得bitmp的方法
public static Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}
public static Drawable BitmapToDrawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
}
/**
* 获取保存图片的目录
*
* @return
*/
public static File getAlbumDir() {
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getAlbumName());
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
/**
* 根据路径获得突破并压缩返回bitmap用于显示
*
* @param filePath
* @return
*/
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Config.RGB_565;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
/**
* 获取保存 隐患检查的图片文件夹名称
*
* @return
*/
public static String getAlbumName() {
return "bealinks";
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int h = options.outHeight;
int w = options.outWidth;
int inSampleSize = 0;
if (h > reqHeight || w > reqWidth) {
float ratioW = (float) w / reqWidth;
float ratioH = (float) h / reqHeight;
inSampleSize = (int) Math.min(ratioH, ratioW);
}
inSampleSize = Math.max(1, inSampleSize);
return inSampleSize;
}
public static String revitionImageSize(String path) {
File f = new File(path);
Bitmap bitmap = getSmallBitmap(path);
File file = new File(getAlbumDir(), "small_" + f.getName());
if (file.exists()) {
file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (bitmap == null) {
return file.getAbsolutePath();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file.getAbsolutePath();
}
// /**
// * bitmap-->byte[]
// * @return
// */
// public static byte[] bitmap2Bytes(Bitmap bm) {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
// return baos.toByteArray();
// }
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
}
|
lujianzhao/MVPArmsCopy
|
arms/src/main/java/com/jess/arms/common/photo/ImageUtils.java
|
Java
|
apache-2.0
| 9,599
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>advcl</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-en">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/_en/dep/advcl.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2><code>advcl</code>: adverbial clause modifier</h2>
<p>An adverbial clause modifier is a clause which modifies a verb or other predicate (adjective, etc.), as a modifier not as a core complement. This includes things such as a temporal clause, consequence, conditional clause, purpose
clause, etc. The dependent must be clausal (or else it is an <a href="">advmod</a>) and the dependent is the main predicate of the clause.</p>
<pre><code class="language-sdparse">The accident happened as the night was falling
advcl(happened, falling)
</code></pre>
<pre><code class="language-sdparse">If you know who did it , you should tell the teacher
advcl(tell, know)
</code></pre>
<pre><code class="language-sdparse">He talked to him in order to secure the account
advcl(talked, secure)
</code></pre>
<pre><code class="language-sdparse">He was upset when I talked to him
advcl(upset, talked)
</code></pre>
<pre><code class="language-sdparse">They heard about you missing classes.
advcl(heard, missing)
</code></pre>
<pre><code class="language-sdparse">With the kids in school , I have plenty of free time
advcl(have, school)
mark(school, With)
nsubj(school, kids)
case(school, in)
</code></pre>
<!-- Interlanguage links updated St lis 3 20:58:34 CET 2021 -->
<!-- "in other languages" links -->
<hr/>
advcl in other languages:
[<a href="../../bej/dep/advcl.html">bej</a>]
[<a href="../../bg/dep/advcl.html">bg</a>]
[<a href="../../bm/dep/advcl.html">bm</a>]
[<a href="../../cop/dep/advcl.html">cop</a>]
[<a href="../../cs/dep/advcl.html">cs</a>]
[<a href="../../de/dep/advcl.html">de</a>]
[<a href="../../el/dep/advcl.html">el</a>]
[<a href="../../en/dep/advcl.html">en</a>]
[<a href="../../es/dep/advcl.html">es</a>]
[<a href="../../et/dep/advcl.html">et</a>]
[<a href="../../eu/dep/advcl.html">eu</a>]
[<a href="../../fi/dep/advcl.html">fi</a>]
[<a href="../../fr/dep/advcl.html">fr</a>]
[<a href="../../fro/dep/advcl.html">fro</a>]
[<a href="../../ga/dep/advcl.html">ga</a>]
[<a href="../../gsw/dep/advcl.html">gsw</a>]
[<a href="../../hy/dep/advcl.html">hy</a>]
[<a href="../../it/dep/advcl.html">it</a>]
[<a href="../../ja/dep/advcl.html">ja</a>]
[<a href="../../kk/dep/advcl.html">kk</a>]
[<a href="../../no/dep/advcl.html">no</a>]
[<a href="../../pcm/dep/advcl.html">pcm</a>]
[<a href="../../pt/dep/advcl.html">pt</a>]
[<a href="../../ro/dep/advcl.html">ro</a>]
[<a href="../../ru/dep/advcl.html">ru</a>]
[<a href="../../sv/dep/advcl.html">sv</a>]
[<a href="../../swl/dep/advcl.html">swl</a>]
[<a href="../../tr/dep/advcl.html">tr</a>]
[<a href="../../u/dep/advcl.html">u</a>]
[<a href="../../urj/dep/advcl.html">urj</a>]
[<a href="../../yue/dep/advcl.html">yue</a>]
[<a href="../../zh/dep/advcl.html">zh</a>]
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = 'en';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
|
UniversalDependencies/universaldependencies.github.io
|
en/dep/advcl.html
|
HTML
|
apache-2.0
| 8,780
|
// Copyright 2016 Mirantis
//
// 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 integration
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestNetwork(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Network")
}
|
AlexeyKasatkin/k8s-externalipcontroller
|
test/integration/network_suite_test.go
|
GO
|
apache-2.0
| 773
|
/*
* Copyright 2009-2011 Red Hat, 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.
*/
// condor includes
#include "condor_common.h"
#include "condor_config.h"
#include "condor_attributes.h"
#include "condor_debug.h"
#include "condor_qmgr.h"
#include "../condor_schedd.V6/scheduler.h"
// local includes
#include "AviaryUtils.h"
#include "AviaryConversionMacros.h"
#include "SchedulerObject.h"
#include "Codec.h"
// Global Scheduler object, used for needReschedule
extern Scheduler scheduler;
extern char * Name;
using namespace aviary::job;
using namespace aviary::util;
using namespace aviary::codec;
SchedulerObject* SchedulerObject::m_instance = NULL;
SchedulerObject::SchedulerObject()
{
m_pool = getPoolName();
m_name = getScheddName();
m_codec = new BaseCodec();
}
SchedulerObject::~SchedulerObject()
{
delete m_codec;
}
SchedulerObject* SchedulerObject::getInstance()
{
if (!m_instance) {
m_instance = new SchedulerObject();
}
return m_instance;
}
void
SchedulerObject::update(const ClassAd &ad)
{
MGMT_DECLARATIONS;
m_stats.Pool = getPoolName();
STRING(CondorPlatform);
STRING(CondorVersion);
TIME_INTEGER(DaemonStartTime);
TIME_INTEGER(JobQueueBirthdate);
STRING(Machine);
INTEGER(MaxJobsRunning);
INTEGER(MonitorSelfAge);
DOUBLE(MonitorSelfCPUUsage);
DOUBLE(MonitorSelfImageSize);
INTEGER(MonitorSelfRegisteredSocketCount);
INTEGER(MonitorSelfResidentSetSize);
TIME_INTEGER(MonitorSelfTime);
STRING(MyAddress);
//TIME_INTEGER(MyCurrentTime);
STRING(Name);
INTEGER(NumUsers);
STRING(MyAddress);
INTEGER(TotalHeldJobs);
INTEGER(TotalIdleJobs);
INTEGER(TotalJobAds);
INTEGER(TotalRemovedJobs);
INTEGER(TotalRunningJobs);
m_stats.System = m_stats.Machine;
// debug
if (IsFulldebug(D_FULLDEBUG)) {
const_cast<ClassAd*>(&ad)->dPrint(D_FULLDEBUG|D_NOHEADER);
}
}
bool
SchedulerObject::submit(AttributeMapType &jobAdMap, std::string &id, std::string &text)
{
int cluster;
int proc;
if (!m_codec) {
text = "Codec has not been initialized";
return false;
}
// our mandatory set of attributes for a submit
const char* required[] = {
ATTR_JOB_CMD,
ATTR_REQUIREMENTS,
ATTR_OWNER,
ATTR_JOB_IWD,
NULL
};
// 1. Create transaction
BeginTransaction();
// 2. Create cluster
if (-1 == (cluster = NewCluster())) {
AbortTransaction();
text = "Failed to create new cluster";
return false;
}
// 3. Create proc
if (-1 == (proc = NewProc(cluster))) {
AbortTransaction();
text = "Failed to create new proc";
return false;
}
// 4. Submit job ad
// Schema: (vanilla job)
// Schedd demands - Owner, JobUniverse
// To run - JobStatus, Requirements
// Schedd excepts if no Owner
// Schedd prunes on startup if no Owner or JobUniverse
// Schedd won't run job without JobStatus
// Job cannot match without Requirements
// Shadow rejects jobs without an Iwd
// Shadow: Job has no CondorVersion, assuming pre version 6.3.3
// Shadow: Unix Vanilla job is pre version 6.3.3, setting 'TransferFiles = "NEVER"'
// Starter won't run job without Cmd
// Starter needs a valid Owner (local account name) if not using nobody
// condor_q requires ClusterId (int), ProcId (int), QDate (int), RemoteUserCpu (float), JobStatus (int), JobPrio (int), ImageSize (int), Owner (str) and Cmd (str)
// Schema: (vm job)
// ShouldTransferFiles - unset by default, must be set
ClassAd ad;
int universe;
// ShouldTransferFiles - unset by default, must be set
// shadow will try to setup local transfer sandbox otherwise
// without good priv
ad.Assign(ATTR_SHOULD_TRANSFER_FILES, "NO");
if (!m_codec->mapToClassAd(jobAdMap, ad, text)) {
AbortTransaction();
return false;
}
std::string missing;
if (!checkRequiredAttrs(ad, required, missing)) {
AbortTransaction();
text = "Job ad is missing required attributes: " + missing;
return false;
}
// EARLY SET: These attribute are set early so the incoming ad
// has a change to override them.
::SetAttribute(cluster, proc, ATTR_JOB_STATUS, "1"); // 1 = idle
// Junk that condor_q wants, but really shouldn't be necessary
::SetAttribute(cluster, proc, ATTR_JOB_REMOTE_USER_CPU, "0.0"); // float
::SetAttribute(cluster, proc, ATTR_JOB_PRIO, "0"); // int
::SetAttribute(cluster, proc, ATTR_IMAGE_SIZE, "0"); // int
if (!ad.LookupInteger(ATTR_JOB_UNIVERSE, universe)) {
char* uni_str = param("DEFAULT_UNIVERSE");
if (!uni_str) {
universe = CONDOR_UNIVERSE_VANILLA;
}
else {
universe = CondorUniverseNumber(uni_str);
}
::SetAttributeInt(cluster, proc, ATTR_JOB_UNIVERSE, universe );
}
// more stuff - without these our idle stats are whack
if ( universe != CONDOR_UNIVERSE_MPI && universe != CONDOR_UNIVERSE_PVM ) {
::SetAttribute(cluster, proc, ATTR_MAX_HOSTS, "1"); // int
::SetAttribute(cluster, proc, ATTR_MIN_HOSTS, "1"); // int
}
::SetAttribute(cluster, proc, ATTR_CURRENT_HOSTS, "0"); // int
ExprTree *expr;
const char *name;
std::string value;
ad.ResetExpr();
while (ad.NextExpr(name,expr)) {
// All these extra lookups are horrible. They have to
// be there because the ClassAd may have multiple
// copies of the same attribute name! This means that
// the last attribute with a given name will set the
// value, but the last attribute tends to be the
// attribute with the oldest (wrong) value. How
// annoying is that!
if (!(expr = ad.Lookup(name))) {
dprintf(D_ALWAYS, "Failed to lookup %s\n", name);
AbortTransaction();
text = "Failed to parse job ad attribute";
return false;
}
value = ExprTreeToString(expr);
::SetAttribute(cluster, proc, name, value.c_str());
}
// LATE SET: These attributes are set late, after the incoming
// ad, so they override whatever the incoming ad set.
char buf[22]; // 22 is max size for an id, 2^32 + . + 2^32 + \0
snprintf(buf, 22, "%d", cluster);
::SetAttribute(cluster, proc, ATTR_CLUSTER_ID, buf);
snprintf(buf, 22, "%d", proc);
::SetAttribute(cluster, proc, ATTR_PROC_ID, buf);
snprintf(buf, 22, "%d", time(NULL));
::SetAttribute(cluster, proc, ATTR_Q_DATE, buf);
// Could check for some invalid attributes, e.g
// JobUniverse <= CONDOR_UNIVERSE_MIN or >= CONDOR_UNIVERSE_MAX
// 5. Commit transaction
CommitTransaction();
// 6. Reschedule
scheduler.needReschedule();
// 7. Return identifier
// TODO: dag ids?
MyString tmp;
//tmp.sprintf("%s#%d.%d", Name, cluster, proc);
// we have other API compositions for job id and submission id
// so let's return raw cluster.proc
tmp.sprintf("%d.%d", cluster, proc);
id = tmp.Value();
return true;
}
bool
SchedulerObject::setAttribute(std::string key,
std::string name,
std::string value,
std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (isSubmissionChange(name.c_str())) {
text = "Changes to submission name not allowed";
return false;
}
if (isKeyword(name.c_str())) {
text = "Attribute name is reserved: " + name;
return false;
}
if (!isValidAttributeName(name,text)) {
return false;
}
// All values are strings in the eyes of
// ::SetAttribute. Their type is inferred when read from
// the ClassAd log. It is important that the incoming
// value is properly quoted to differentiate between EXPR
// and STRING.
if (::SetAttribute(id.cluster,
id.proc,
name.c_str(),
value.c_str())) {
text = "Failed to set attribute " + name + " to " + value;
return false;
}
return true;
}
bool
SchedulerObject::hold(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
bool
SchedulerObject::release(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!releaseJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
false, // Do not email the user about this action
false // Do not email admin about this action
)) {
text = "Failed to release job";
return false;
}
return true;
}
bool
SchedulerObject::remove(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!abortJob(id.cluster,
id.proc,
reason.c_str(),
true // Always perform within a transaction
)) {
text = "Failed to remove job";
return false;
}
return true;
}
bool
SchedulerObject::suspend(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true);
return true;
}
bool
SchedulerObject::_continue(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true);
return true;
}
|
bbockelm/condor-network-accounting
|
src/condor_contrib/aviary/src/SchedulerObject.cpp
|
C++
|
apache-2.0
| 10,772
|
package org.ray.runtime;
import java.util.concurrent.atomic.AtomicInteger;
import org.ray.api.id.JobId;
import org.ray.api.id.UniqueId;
import org.ray.runtime.config.RayConfig;
import org.ray.runtime.context.LocalModeWorkerContext;
import org.ray.runtime.object.LocalModeObjectStore;
import org.ray.runtime.task.LocalModeTaskExecutor;
import org.ray.runtime.task.LocalModeTaskSubmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RayDevRuntime extends AbstractRayRuntime {
private static final Logger LOGGER = LoggerFactory.getLogger(RayDevRuntime.class);
private AtomicInteger jobCounter = new AtomicInteger(0);
public RayDevRuntime(RayConfig rayConfig) {
super(rayConfig);
if (rayConfig.getJobId().isNil()) {
rayConfig.setJobId(nextJobId());
}
taskExecutor = new LocalModeTaskExecutor(this);
workerContext = new LocalModeWorkerContext(rayConfig.getJobId());
objectStore = new LocalModeObjectStore(workerContext);
taskSubmitter = new LocalModeTaskSubmitter(this, (LocalModeObjectStore) objectStore,
rayConfig.numberExecThreadsForDevRuntime);
((LocalModeObjectStore) objectStore).addObjectPutCallback(
objectId -> ((LocalModeTaskSubmitter) taskSubmitter).onObjectPut(objectId));
}
@Override
public void shutdown() {
if (taskSubmitter != null) {
((LocalModeTaskSubmitter) taskSubmitter).shutdown();
taskSubmitter = null;
}
taskExecutor = null;
}
@Override
public void setResource(String resourceName, double capacity, UniqueId nodeId) {
LOGGER.error("Not implemented under SINGLE_PROCESS mode.");
}
private JobId nextJobId() {
return JobId.fromInt(jobCounter.getAndIncrement());
}
}
|
ujvl/ray-ng
|
java/runtime/src/main/java/org/ray/runtime/RayDevRuntime.java
|
Java
|
apache-2.0
| 1,727
|
using System;
using PeNet.FileParser;
namespace PeNet.Header.Pe
{
/// <summary>
/// Represents the optional header in
/// the NT header.
/// </summary>
public class ImageOptionalHeader : AbstractStructure
{
private readonly bool _is64Bit;
/// <summary>
/// The Data Directories.
/// </summary>
public readonly ImageDataDirectory[] DataDirectory;
/// <summary>
/// Create a new ImageOptionalHeader object.
/// </summary>
/// <param name="peFile">A PE file.</param>
/// <param name="offset">Raw offset to the optional header.</param>
/// <param name="is64Bit">Set to true, if header is for a x64 application.</param>
public ImageOptionalHeader(IRawFile peFile, long offset, bool is64Bit)
: base(peFile, offset)
{
_is64Bit = is64Bit;
DataDirectory = new ImageDataDirectory[16];
for (uint i = 0; i < 16; i++)
{
if (!_is64Bit)
DataDirectory[i] = new ImageDataDirectory(peFile, offset + 0x60 + i*0x8);
else
DataDirectory[i] = new ImageDataDirectory(peFile, offset + 0x70 + i*0x8);
}
}
/// <summary>
/// Flag if the file is x32, x64 or a ROM image.
/// </summary>
public MagicType Magic
{
get => (MagicType) PeFile.ReadUShort(Offset);
set => PeFile.WriteUShort(Offset, (ushort) value);
}
/// <summary>
/// Major linker version.
/// </summary>
public byte MajorLinkerVersion
{
get => PeFile.ReadByte(Offset + 0x2);
set => PeFile.WriteByte(Offset + 0x2, value);
}
/// <summary>
/// Minor linker version.
/// </summary>
public byte MinorLinkerVersion
{
get => PeFile.ReadByte(Offset + 0x3);
set => PeFile.WriteByte(Offset + 03, value);
}
/// <summary>
/// Size of all code sections together.
/// </summary>
public uint SizeOfCode
{
get => PeFile.ReadUInt(Offset + 0x4);
set => PeFile.WriteUInt(Offset + 0x4, value);
}
/// <summary>
/// Size of all initialized data sections together.
/// </summary>
public uint SizeOfInitializedData
{
get => PeFile.ReadUInt(Offset + 0x8);
set => PeFile.WriteUInt(Offset + 0x8, value);
}
/// <summary>
/// Size of all uninitialized data sections together.
/// </summary>
public uint SizeOfUninitializedData
{
get => PeFile.ReadUInt(Offset + 0xC);
set => PeFile.WriteUInt(Offset + 0xC, value);
}
/// <summary>
/// RVA of the entry point function.
/// </summary>
public uint AddressOfEntryPoint
{
get => PeFile.ReadUInt(Offset + 0x10);
set => PeFile.WriteUInt(Offset + 0x10, value);
}
/// <summary>
/// RVA to the beginning of the code section.
/// </summary>
public uint BaseOfCode
{
get => PeFile.ReadUInt(Offset + 0x14);
set => PeFile.WriteUInt(Offset + 0x14, value);
}
/// <summary>
/// RVA to the beginning of the data section.
/// </summary>
public uint BaseOfData
{
get => _is64Bit ? 0 : PeFile.ReadUInt(Offset + 0x18);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x18, value);
else
throw new Exception("ImageOptionalHeader->BaseOfCode does not exist in 64 bit applications.");
}
}
/// <summary>
/// Preferred address of the image when it's loaded to memory.
/// </summary>
public ulong ImageBase
{
get =>
_is64Bit
? PeFile.ReadULong(Offset + 0x18)
: PeFile.ReadUInt(Offset + 0x1C);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x1C, (uint) value);
else
PeFile.WriteULong(Offset + 0x18, value);
}
}
/// <summary>
/// Section alignment in memory in bytes. Must be greater or equal to the file alignment.
/// </summary>
public uint SectionAlignment
{
get => PeFile.ReadUInt(Offset + 0x20);
set => PeFile.WriteUInt(Offset + 0x20, value);
}
/// <summary>
/// File alignment of the raw data of the sections in bytes.
/// </summary>
public uint FileAlignment
{
get => PeFile.ReadUInt(Offset + 0x24);
set => PeFile.WriteUInt(Offset + 0x24, value);
}
/// <summary>
/// Major operation system version to run the file.
/// </summary>
public ushort MajorOperatingSystemVersion
{
get => PeFile.ReadUShort(Offset + 0x28);
set => PeFile.WriteUShort(Offset + 0x28, value);
}
/// <summary>
/// Minor operation system version to run the file.
/// </summary>
public ushort MinorOperatingSystemVersion
{
get => PeFile.ReadUShort(Offset + 0x2A);
set => PeFile.WriteUShort(Offset + 0x2A, value);
}
/// <summary>
/// Major image version.
/// </summary>
public ushort MajorImageVersion
{
get => PeFile.ReadUShort(Offset + 0x2C);
set => PeFile.WriteUShort(Offset + 0x2C, value);
}
/// <summary>
/// Minor image version.
/// </summary>
public ushort MinorImageVersion
{
get => PeFile.ReadUShort(Offset + 0x2E);
set => PeFile.WriteUShort(Offset + 0x2E, value);
}
/// <summary>
/// Major version of the subsystem.
/// </summary>
public ushort MajorSubsystemVersion
{
get => PeFile.ReadUShort(Offset + 0x30);
set => PeFile.WriteUShort(Offset + 0x30, value);
}
/// <summary>
/// Minor version of the subsystem.
/// </summary>
public ushort MinorSubsystemVersion
{
get => PeFile.ReadUShort(Offset + 0x32);
set => PeFile.WriteUShort(Offset + 0x32, value);
}
/// <summary>
/// Reserved and must be 0.
/// </summary>
public uint Win32VersionValue
{
get => PeFile.ReadUInt(Offset + 0x34);
set => PeFile.WriteUInt(Offset + 0x34, value);
}
/// <summary>
/// Size of the image including all headers in bytes. Must be a multiple of
/// the section alignment.
/// </summary>
public uint SizeOfImage
{
get => PeFile.ReadUInt(Offset + 0x38);
set => PeFile.WriteUInt(Offset + 0x38, value);
}
/// <summary>
/// Sum of the e_lfanwe from the DOS header, the 4 byte signature, size of
/// the file header, size of the optional header and size of all section.
/// Rounded to the next file alignment.
/// </summary>
public uint SizeOfHeaders
{
get => PeFile.ReadUInt(Offset + 0x3C);
set => PeFile.WriteUInt(Offset + 0x3C, value);
}
/// <summary>
/// Image checksum validated at runtime for drivers, DLLs loaded at boot time and
/// DLLs loaded into a critical system.
/// </summary>
public uint CheckSum
{
get => PeFile.ReadUInt(Offset + 0x40);
set => PeFile.WriteUInt(Offset + 0x40, value);
}
/// <summary>
/// The subsystem required to run the image e.g., Windows GUI, XBOX etc.
/// </summary>
public SubsystemType Subsystem
{
get => (SubsystemType) PeFile.ReadUShort(Offset + 0x44);
set => PeFile.WriteUShort(Offset + 0x44, (ushort) value);
}
/// <summary>
/// Subsystem resolved to a readable string.
/// </summary>
public string SubsystemResolved => ResolveSubsystem(Subsystem);
/// <summary>
/// DLL characteristics of the image.
/// </summary>
public DllCharacteristicsType DllCharacteristics
{
get => (DllCharacteristicsType) PeFile.ReadUShort(Offset + 0x46);
set => PeFile.WriteUShort(Offset + 0x46, (ushort) value);
}
/// <summary>
/// Size of stack reserve in bytes.
/// </summary>
public ulong SizeOfStackReserve
{
get =>
_is64Bit
? PeFile.ReadULong(Offset + 0x48)
: PeFile.ReadUInt(Offset + 0x48);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x48, (uint) value);
else
PeFile.WriteULong(Offset + 0x48, value);
}
}
/// <summary>
/// Size of bytes committed for the stack in bytes.
/// </summary>
public ulong SizeOfStackCommit
{
get =>
_is64Bit
? PeFile.ReadULong(Offset + 0x50)
: PeFile.ReadUInt(Offset + 0x4C);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x4C, (uint) value);
else
PeFile.WriteULong(Offset + 0x50, value);
}
}
/// <summary>
/// Size of the heap to reserve in bytes.
/// </summary>
public ulong SizeOfHeapReserve
{
get =>
_is64Bit
? PeFile.ReadULong(Offset + 0x58)
: PeFile.ReadUInt(Offset + 0x50);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x50, (uint) value);
else
PeFile.WriteULong(Offset + 0x58, value);
}
}
/// <summary>
/// Size of the heap commit in bytes.
/// </summary>
public ulong SizeOfHeapCommit
{
get =>
_is64Bit
? PeFile.ReadULong(Offset + 0x60)
: PeFile.ReadUInt(Offset + 0x54);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x54, (uint) value);
else
PeFile.WriteULong(Offset + 0x60, value);
}
}
/// <summary>
/// Obsolete
/// </summary>
public uint LoaderFlags
{
get =>
_is64Bit
? PeFile.ReadUInt(Offset + 0x68)
: PeFile.ReadUInt(Offset + 0x58);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x58, value);
else
PeFile.WriteUInt(Offset + 0x68, value);
}
}
/// <summary>
/// Number of directory entries in the remainder of the optional header.
/// </summary>
public uint NumberOfRvaAndSizes
{
get =>
_is64Bit
? PeFile.ReadUInt(Offset + 0x6C)
: PeFile.ReadUInt(Offset + 0x5C);
set
{
if (!_is64Bit)
PeFile.WriteUInt(Offset + 0x5C, value);
else
PeFile.WriteUInt(Offset + 0x6C, value);
}
}
/// <summary>
/// Resolve the subsystem attribute to a human readable string.
/// </summary>
/// <param name="subsystem">Subsystem attribute.</param>
/// <returns>Subsystem as readable string.</returns>
public static string ResolveSubsystem(SubsystemType subsystem)
=> subsystem switch
{
SubsystemType.Unknown => "Unknown Subsystem",
SubsystemType.Native => "Native",
SubsystemType.WindowsGui => "Windows GUI",
SubsystemType.WindowsCui => "Windows CUI",
SubsystemType.Os2Cui => "OS/2 CUI",
SubsystemType.PosixCui => "POSIX CUI",
SubsystemType.WindowsCeGui => "Windows CE CUI",
SubsystemType.EfiApplication => "EFI application",
SubsystemType.EfiBootServiceDriver => "EFI boot service driver",
SubsystemType.EfiRuntimeDriver => "EFI runtime service driver",
SubsystemType.EfiRom => "EFI ROM image",
SubsystemType.Xbox => "XBox",
SubsystemType.WindowsBootApplication => "Windows boot application",
_ => "Unknown Subsystem"
};
}
/// <summary>
/// Subsystem of the image.
/// </summary>
public enum SubsystemType : ushort
{
Unknown = 0,
Native = 1,
WindowsGui = 2,
WindowsCui = 3,
Os2Cui = 5,
PosixCui = 7,
WindowsCeGui = 9,
EfiApplication = 10,
EfiBootServiceDriver = 11,
EfiRuntimeDriver = 12,
EfiRom = 13,
Xbox = 14,
WindowsBootApplication = 16
}
/// <summary>
/// Constants for the Optional header DllCharacteristics
/// property.
/// </summary>
[Flags]
public enum DllCharacteristicsType : ushort
{
/// <summary>
/// DLL can be relocated at load time.
/// </summary>
DynamicBase = 0x40,
/// <summary>
/// Enforces integrity checks.
/// </summary>
ForceIntegrity = 0x80,
/// <summary>
/// Image is compatible with Data Execution Prevention (DEP).
/// </summary>
NxCompat = 0x100,
/// <summary>
/// Image is isolation aware but should not be isolated.
/// </summary>
NoIsolation = 0x200,
/// <summary>
/// No Secure Exception Handling (SEH)
/// </summary>
NoSeh = 0x400,
/// <summary>
/// Do not bind the image.
/// </summary>
NoBind,
/// <summary>
/// Image is a WDM driver.
/// </summary>
WdmDriver = 0x2000,
/// <summary>
/// Terminal server aware.
/// </summary>
TerminalServerAware = 0x8000
}
/// <summary>
/// Constants for the Optional header magic property.
/// </summary>
[Flags]
public enum MagicType : ushort
{
/// <summary>
/// The file is an 32 bit executable.
/// </summary>
Bit32 = 0x10b,
/// <summary>
/// The file is an 64 bit executable.
/// </summary>
Bit64 = 0x20b,
/// <summary>
/// The file is a ROM image.
/// </summary>
Rom = 0x107
}
}
|
secana/PeNet
|
src/PeNet/Header/Pe/ImageOptionalHeader.cs
|
C#
|
apache-2.0
| 15,465
|
<!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_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_33327_good
</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_15.html?line=19501#src-19501" >testAbaNumberCheck_33327_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:38
</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_33327_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=36753#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></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_15_testAbaNumberCheck_33327_good_scx.html
|
HTML
|
apache-2.0
| 9,181
|
<!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_11.html">Class Test_AbaRouteValidator_11</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_24765_good
</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_11.html?line=55624#src-55624" >testAbaNumberCheck_24765_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:40:36
</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_24765_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=24077#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></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_11_testAbaNumberCheck_24765_good_ikt.html
|
HTML
|
apache-2.0
| 9,181
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
include TwitterCldr::Localized
describe LocalizedArray do
describe '#code_points_to_string' do
it 'transforms an array of code points into a string' do
[0x74, 0x77, 0x69, 0x74, 0x74, 0x65, 0x72].localize.code_points_to_string.should == 'twitter'
end
end
describe 'strings sorting' do
let(:locale) { :da }
let(:array) { %w[bca aaa abc] }
let(:sorted) { %w[aaa abc bca] }
let(:localized) { array.localize(locale) }
before(:each) { mock(TwitterCldr::Collation::Collator).new(locale) { FakeCollator.new } }
describe '#sort' do
it 'returns a new LocalizedArray' do
localized.sort.should be_instance_of(LocalizedArray)
end
it 'does not change the original array' do
lambda { localized.sort }.should_not change { localized.base_obj }
end
it 'sorts strings in the array with corresponding collator' do
localized.sort.base_obj.should == sorted
end
end
describe '#sort!' do
it 'returns self' do
localized.sort!.object_id.should == localized.object_id
end
it 'sorts the array in-place' do
localized.sort!.base_obj.should == sorted
end
end
end
describe "#each" do
it "should iterate over the items in the array and yield each one" do
arr = [1, 2, 3]
index = 0
arr.localize.each do |item|
arr[index].should == item
index += 1
end
end
it "should support a few of the other methods in Enumerable" do
[1, 2, 3].localize.inject(0) { |sum, num| sum += num; sum }.should == 6
[1, 2, 3].localize.map { |item| item + 1 }.should == [2, 3, 4]
end
end
describe "#to_yaml" do
it "should be able to successfully roundtrip the array" do
arr = [:foo, "bar", Object.new]
result = YAML.load(arr.localize.to_yaml)
result[0].should == :foo
result[1].should == "bar"
result[2].should be_a(Object)
end
end
end
class FakeCollator
def sort(array)
array.sort
end
def sort!(array)
array.sort!
end
end
|
1974kpkpkp/twitter-cldr-rb
|
spec/localized/localized_array_spec.rb
|
Ruby
|
apache-2.0
| 2,193
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.cmcti.cmts.domain.model.impl;
import com.cmcti.cmts.domain.model.Option;
import com.cmcti.cmts.domain.model.OptionModel;
import com.cmcti.cmts.domain.model.OptionSoap;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSON;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;
import java.io.Serializable;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The base model implementation for the Option service. Represents a row in the "CMTS_Option" database table, with each column mapped to a property of this class.
*
* <p>
* This implementation and its corresponding interface {@link com.cmcti.cmts.domain.model.OptionModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link OptionImpl}.
* </p>
*
* @author richard
* @see OptionImpl
* @see com.cmcti.cmts.domain.model.Option
* @see com.cmcti.cmts.domain.model.OptionModel
* @generated
*/
@JSON(strict = true)
public class OptionModelImpl extends BaseModelImpl<Option>
implements OptionModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. All methods that expect a option model instance should use the {@link com.cmcti.cmts.domain.model.Option} interface instead.
*/
public static final String TABLE_NAME = "CMTS_Option";
public static final Object[][] TABLE_COLUMNS = {
{ "optionId", Types.BIGINT },
{ "groupId", Types.BIGINT },
{ "companyId", Types.BIGINT },
{ "userId", Types.BIGINT },
{ "userName", Types.VARCHAR },
{ "createDate", Types.TIMESTAMP },
{ "modifiedDate", Types.TIMESTAMP },
{ "optionType", Types.VARCHAR },
{ "optionKey", Types.VARCHAR },
{ "optionValue", Types.VARCHAR },
{ "description", Types.VARCHAR }
};
public static final String TABLE_SQL_CREATE = "create table CMTS_Option (optionId LONG not null primary key,groupId LONG,companyId LONG,userId LONG,userName VARCHAR(75) null,createDate DATE null,modifiedDate DATE null,optionType VARCHAR(75) null,optionKey VARCHAR(75) null,optionValue VARCHAR(75) null,description VARCHAR(75) null)";
public static final String TABLE_SQL_DROP = "drop table CMTS_Option";
public static final String ORDER_BY_JPQL = " ORDER BY option.optionId ASC";
public static final String ORDER_BY_SQL = " ORDER BY CMTS_Option.optionId ASC";
public static final String DATA_SOURCE = "liferayDataSource";
public static final String SESSION_FACTORY = "liferaySessionFactory";
public static final String TX_MANAGER = "liferayTransactionManager";
public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.entity.cache.enabled.com.cmcti.cmts.domain.model.Option"),
true);
public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.finder.cache.enabled.com.cmcti.cmts.domain.model.Option"),
true);
public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.column.bitmask.enabled.com.cmcti.cmts.domain.model.Option"),
true);
public static long OPTIONKEY_COLUMN_BITMASK = 1L;
public static long OPTIONTYPE_COLUMN_BITMASK = 2L;
public static long USERID_COLUMN_BITMASK = 4L;
public static long OPTIONID_COLUMN_BITMASK = 8L;
/**
* Converts the soap model instance into a normal model instance.
*
* @param soapModel the soap model instance to convert
* @return the normal model instance
*/
public static Option toModel(OptionSoap soapModel) {
if (soapModel == null) {
return null;
}
Option model = new OptionImpl();
model.setOptionId(soapModel.getOptionId());
model.setGroupId(soapModel.getGroupId());
model.setCompanyId(soapModel.getCompanyId());
model.setUserId(soapModel.getUserId());
model.setUserName(soapModel.getUserName());
model.setCreateDate(soapModel.getCreateDate());
model.setModifiedDate(soapModel.getModifiedDate());
model.setOptionType(soapModel.getOptionType());
model.setOptionKey(soapModel.getOptionKey());
model.setOptionValue(soapModel.getOptionValue());
model.setDescription(soapModel.getDescription());
return model;
}
/**
* Converts the soap model instances into normal model instances.
*
* @param soapModels the soap model instances to convert
* @return the normal model instances
*/
public static List<Option> toModels(OptionSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<Option> models = new ArrayList<Option>(soapModels.length);
for (OptionSoap soapModel : soapModels) {
models.add(toModel(soapModel));
}
return models;
}
public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get(
"lock.expiration.time.com.cmcti.cmts.domain.model.Option"));
public OptionModelImpl() {
}
@Override
public long getPrimaryKey() {
return _optionId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setOptionId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _optionId;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long)primaryKeyObj).longValue());
}
@Override
public Class<?> getModelClass() {
return Option.class;
}
@Override
public String getModelClassName() {
return Option.class.getName();
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("optionId", getOptionId());
attributes.put("groupId", getGroupId());
attributes.put("companyId", getCompanyId());
attributes.put("userId", getUserId());
attributes.put("userName", getUserName());
attributes.put("createDate", getCreateDate());
attributes.put("modifiedDate", getModifiedDate());
attributes.put("optionType", getOptionType());
attributes.put("optionKey", getOptionKey());
attributes.put("optionValue", getOptionValue());
attributes.put("description", getDescription());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long optionId = (Long)attributes.get("optionId");
if (optionId != null) {
setOptionId(optionId);
}
Long groupId = (Long)attributes.get("groupId");
if (groupId != null) {
setGroupId(groupId);
}
Long companyId = (Long)attributes.get("companyId");
if (companyId != null) {
setCompanyId(companyId);
}
Long userId = (Long)attributes.get("userId");
if (userId != null) {
setUserId(userId);
}
String userName = (String)attributes.get("userName");
if (userName != null) {
setUserName(userName);
}
Date createDate = (Date)attributes.get("createDate");
if (createDate != null) {
setCreateDate(createDate);
}
Date modifiedDate = (Date)attributes.get("modifiedDate");
if (modifiedDate != null) {
setModifiedDate(modifiedDate);
}
String optionType = (String)attributes.get("optionType");
if (optionType != null) {
setOptionType(optionType);
}
String optionKey = (String)attributes.get("optionKey");
if (optionKey != null) {
setOptionKey(optionKey);
}
String optionValue = (String)attributes.get("optionValue");
if (optionValue != null) {
setOptionValue(optionValue);
}
String description = (String)attributes.get("description");
if (description != null) {
setDescription(description);
}
}
@JSON
@Override
public long getOptionId() {
return _optionId;
}
@Override
public void setOptionId(long optionId) {
_optionId = optionId;
}
@JSON
@Override
public long getGroupId() {
return _groupId;
}
@Override
public void setGroupId(long groupId) {
_groupId = groupId;
}
@JSON
@Override
public long getCompanyId() {
return _companyId;
}
@Override
public void setCompanyId(long companyId) {
_companyId = companyId;
}
@JSON
@Override
public long getUserId() {
return _userId;
}
@Override
public void setUserId(long userId) {
_columnBitmask |= USERID_COLUMN_BITMASK;
if (!_setOriginalUserId) {
_setOriginalUserId = true;
_originalUserId = _userId;
}
_userId = userId;
}
@Override
public String getUserUuid() throws SystemException {
return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
}
@Override
public void setUserUuid(String userUuid) {
_userUuid = userUuid;
}
public long getOriginalUserId() {
return _originalUserId;
}
@JSON
@Override
public String getUserName() {
if (_userName == null) {
return StringPool.BLANK;
}
else {
return _userName;
}
}
@Override
public void setUserName(String userName) {
_userName = userName;
}
@JSON
@Override
public Date getCreateDate() {
return _createDate;
}
@Override
public void setCreateDate(Date createDate) {
_createDate = createDate;
}
@JSON
@Override
public Date getModifiedDate() {
return _modifiedDate;
}
@Override
public void setModifiedDate(Date modifiedDate) {
_modifiedDate = modifiedDate;
}
@JSON
@Override
public String getOptionType() {
if (_optionType == null) {
return StringPool.BLANK;
}
else {
return _optionType;
}
}
@Override
public void setOptionType(String optionType) {
_columnBitmask |= OPTIONTYPE_COLUMN_BITMASK;
if (_originalOptionType == null) {
_originalOptionType = _optionType;
}
_optionType = optionType;
}
public String getOriginalOptionType() {
return GetterUtil.getString(_originalOptionType);
}
@JSON
@Override
public String getOptionKey() {
if (_optionKey == null) {
return StringPool.BLANK;
}
else {
return _optionKey;
}
}
@Override
public void setOptionKey(String optionKey) {
_columnBitmask |= OPTIONKEY_COLUMN_BITMASK;
if (_originalOptionKey == null) {
_originalOptionKey = _optionKey;
}
_optionKey = optionKey;
}
public String getOriginalOptionKey() {
return GetterUtil.getString(_originalOptionKey);
}
@JSON
@Override
public String getOptionValue() {
if (_optionValue == null) {
return StringPool.BLANK;
}
else {
return _optionValue;
}
}
@Override
public void setOptionValue(String optionValue) {
_optionValue = optionValue;
}
@JSON
@Override
public String getDescription() {
if (_description == null) {
return StringPool.BLANK;
}
else {
return _description;
}
}
@Override
public void setDescription(String description) {
_description = description;
}
public long getColumnBitmask() {
return _columnBitmask;
}
@Override
public ExpandoBridge getExpandoBridge() {
return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(),
Option.class.getName(), getPrimaryKey());
}
@Override
public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
ExpandoBridge expandoBridge = getExpandoBridge();
expandoBridge.setAttributes(serviceContext);
}
@Override
public Option toEscapedModel() {
if (_escapedModel == null) {
_escapedModel = (Option)ProxyUtil.newProxyInstance(_classLoader,
_escapedModelInterfaces, new AutoEscapeBeanHandler(this));
}
return _escapedModel;
}
@Override
public Object clone() {
OptionImpl optionImpl = new OptionImpl();
optionImpl.setOptionId(getOptionId());
optionImpl.setGroupId(getGroupId());
optionImpl.setCompanyId(getCompanyId());
optionImpl.setUserId(getUserId());
optionImpl.setUserName(getUserName());
optionImpl.setCreateDate(getCreateDate());
optionImpl.setModifiedDate(getModifiedDate());
optionImpl.setOptionType(getOptionType());
optionImpl.setOptionKey(getOptionKey());
optionImpl.setOptionValue(getOptionValue());
optionImpl.setDescription(getDescription());
optionImpl.resetOriginalValues();
return optionImpl;
}
@Override
public int compareTo(Option option) {
long primaryKey = option.getPrimaryKey();
if (getPrimaryKey() < primaryKey) {
return -1;
}
else if (getPrimaryKey() > primaryKey) {
return 1;
}
else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Option)) {
return false;
}
Option option = (Option)obj;
long primaryKey = option.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
}
else {
return false;
}
}
@Override
public int hashCode() {
return (int)getPrimaryKey();
}
@Override
public void resetOriginalValues() {
OptionModelImpl optionModelImpl = this;
optionModelImpl._originalUserId = optionModelImpl._userId;
optionModelImpl._setOriginalUserId = false;
optionModelImpl._originalOptionType = optionModelImpl._optionType;
optionModelImpl._originalOptionKey = optionModelImpl._optionKey;
optionModelImpl._columnBitmask = 0;
}
@Override
public CacheModel<Option> toCacheModel() {
OptionCacheModel optionCacheModel = new OptionCacheModel();
optionCacheModel.optionId = getOptionId();
optionCacheModel.groupId = getGroupId();
optionCacheModel.companyId = getCompanyId();
optionCacheModel.userId = getUserId();
optionCacheModel.userName = getUserName();
String userName = optionCacheModel.userName;
if ((userName != null) && (userName.length() == 0)) {
optionCacheModel.userName = null;
}
Date createDate = getCreateDate();
if (createDate != null) {
optionCacheModel.createDate = createDate.getTime();
}
else {
optionCacheModel.createDate = Long.MIN_VALUE;
}
Date modifiedDate = getModifiedDate();
if (modifiedDate != null) {
optionCacheModel.modifiedDate = modifiedDate.getTime();
}
else {
optionCacheModel.modifiedDate = Long.MIN_VALUE;
}
optionCacheModel.optionType = getOptionType();
String optionType = optionCacheModel.optionType;
if ((optionType != null) && (optionType.length() == 0)) {
optionCacheModel.optionType = null;
}
optionCacheModel.optionKey = getOptionKey();
String optionKey = optionCacheModel.optionKey;
if ((optionKey != null) && (optionKey.length() == 0)) {
optionCacheModel.optionKey = null;
}
optionCacheModel.optionValue = getOptionValue();
String optionValue = optionCacheModel.optionValue;
if ((optionValue != null) && (optionValue.length() == 0)) {
optionCacheModel.optionValue = null;
}
optionCacheModel.description = getDescription();
String description = optionCacheModel.description;
if ((description != null) && (description.length() == 0)) {
optionCacheModel.description = null;
}
return optionCacheModel;
}
@Override
public String toString() {
StringBundler sb = new StringBundler(23);
sb.append("{optionId=");
sb.append(getOptionId());
sb.append(", groupId=");
sb.append(getGroupId());
sb.append(", companyId=");
sb.append(getCompanyId());
sb.append(", userId=");
sb.append(getUserId());
sb.append(", userName=");
sb.append(getUserName());
sb.append(", createDate=");
sb.append(getCreateDate());
sb.append(", modifiedDate=");
sb.append(getModifiedDate());
sb.append(", optionType=");
sb.append(getOptionType());
sb.append(", optionKey=");
sb.append(getOptionKey());
sb.append(", optionValue=");
sb.append(getOptionValue());
sb.append(", description=");
sb.append(getDescription());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(37);
sb.append("<model><model-name>");
sb.append("com.cmcti.cmts.domain.model.Option");
sb.append("</model-name>");
sb.append(
"<column><column-name>optionId</column-name><column-value><![CDATA[");
sb.append(getOptionId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupId</column-name><column-value><![CDATA[");
sb.append(getGroupId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>companyId</column-name><column-value><![CDATA[");
sb.append(getCompanyId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userId</column-name><column-value><![CDATA[");
sb.append(getUserId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userName</column-name><column-value><![CDATA[");
sb.append(getUserName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>createDate</column-name><column-value><![CDATA[");
sb.append(getCreateDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>modifiedDate</column-name><column-value><![CDATA[");
sb.append(getModifiedDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>optionType</column-name><column-value><![CDATA[");
sb.append(getOptionType());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>optionKey</column-name><column-value><![CDATA[");
sb.append(getOptionKey());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>optionValue</column-name><column-value><![CDATA[");
sb.append(getOptionValue());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>description</column-name><column-value><![CDATA[");
sb.append(getDescription());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private static ClassLoader _classLoader = Option.class.getClassLoader();
private static Class<?>[] _escapedModelInterfaces = new Class[] { Option.class };
private long _optionId;
private long _groupId;
private long _companyId;
private long _userId;
private String _userUuid;
private long _originalUserId;
private boolean _setOriginalUserId;
private String _userName;
private Date _createDate;
private Date _modifiedDate;
private String _optionType;
private String _originalOptionType;
private String _optionKey;
private String _originalOptionKey;
private String _optionValue;
private String _description;
private long _columnBitmask;
private Option _escapedModel;
}
|
nms-htc/cmts-mo-portlet
|
docroot/WEB-INF/src/com/cmcti/cmts/domain/model/impl/OptionModelImpl.java
|
Java
|
apache-2.0
| 19,290
|
# opendataflow
An open, extendable framework to build data pipelines
## Concepts
When working on data projects there is a big divide between
big companies and smaller ones. Big companies have usually
multiple teams to work in operations, development, testing.
In smaller companies, it's often one person who does pretty
much all the above.
The goal of this framework is to use abstraction to clearly
separate concerns - dev, test, operations - while being
fairly lightweight, that is, easy to learn and use.
We'd also like the data flows being self-documenting, 'forcing'
the developer to include a minimal amount of documentation.
We all have worked on a project written by somebody who didn't
comment his code and did not write documentation, don't be that
guy.
Also, we'd like to build reusable data components, an equivalent
of the 'library' in the data world. Once you have a number of
components, we'd like to be just able to compose them using
a configuration file, hence write new pipelines without
writing a line of programming language, but just a config
file, maybe even using a GUI, so non-programmers can
build, test and deploy pipelines, needing a developer only to
write new components.
So, the main concepts are:
- Pipeline Component (PComponent class): a generic data component,
that has an implementation and Connectors (both input and output).
in our library analogy, it's like a function with input and outputs
- AbstractData: a generic descripion of the data that a component
accepts and produces. In our analogy, this is the equivalent to a
type system. In the data world, we have a few things we want to cover.
First is bound/unbound data, that is, table or a stream. A stream is
unbound because we don't know its bounds.
- Composition: components can be assembled together in larger components.
a Pipeline is itself a component.
- ExecutionEngine: once we have the high level implementation of the
pipeline, it needs to be executed on an engine. The first implementation
will be with spark, but the idea is to be able to implement different
runners as needed.
|
opendataflow/opendataflow
|
README.md
|
Markdown
|
apache-2.0
| 2,112
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: MemorySizeTest.java,v 1.4 2010/01/04 15:51:05 cwl Exp $
*/
package com.sleepycat.je.rep.dual.tree;
public class MemorySizeTest extends com.sleepycat.je.tree.MemorySizeTest {
}
|
bjorndm/prebake
|
code/third_party/bdb/test/com/sleepycat/je/rep/dual/tree/MemorySizeTest.java
|
Java
|
apache-2.0
| 309
|
//// 0. Describe this demo
window.demoDescription = "Draw three kinds of grids: with fixed size cells, with flexible size cells, and with cell sizes based on grid's rows and columns. Resize the browser window to update grid layouts.";
//// 1. Define Space and Form
var colors = {
a1: "#ff2d5d", a2: "#42dc8e", a3: "#2e43eb", a4: "#ffe359",
b1: "#96bfed", b2: "#f5ead6", b3: "#f1f3f7", b4: "#e2e6ef"
};
var space = new CanvasSpace("pt").setup( {bgcolor: colors.a4} );
var form = new Form( space );
//// 2. Create Elements
// three kinds of grids
var grids = [
new Grid( space.size.$multiply( 0.1 ) ).to( space.size.$multiply(0.9, 0.3) ).init(50, 50, "fix", "fix"),
new Grid( space.size.$multiply( 0.1, 0.4 ) ).to( space.size.$multiply(0.9, 0.6 ) ).init( 50, 50, "flex", "flex"),
new Grid( space.size.$multiply( 0.1, 0.7 ) ).to( space.size.$multiply(0.9, 0.9 ) ).init( 5, 8, "stretch", "stretch")
];
// Use grid.generate() to specify a callback function to render each grid cell
for (var i=0; i<grids.length; i++) {
grids[i].generate( function ( size, position, row, column, type, isOccupied ) {
form.stroke( colors.b1 ).fill( false ).rect( new Rectangle( position ).resizeTo( size ) );
form.fill( colors.b1 ).font( 9 ).text( position.$add( 5, 12 ), row + ", " + column );
}.bind( grids[i] ) );
}
//// 3. Visualize, Animate, Interact
space.add({
animate: function(time, fps, context) {
for (var i = 0; i < grids.length; i++) {
form.fill( "#9ab" ).font( 12 );
form.text( grids[i].$subtract( 0, 15 ), ["Fix (50px by 50px cells)", "Flex (~50px by ~50px cells)", "Stretch (5 columns and 8 rows)"][i % 3] );
form.stroke( false ).fill( "#fff" ).rect( grids[i] ); // draw grid area
grids[i].create(); // draw grid cells (via generate() callback)
}
},
// callback to reset grid when space is resized
onSpaceResize: function(w, h) {
grids[0].set( space.size.$multiply( 0.1 ) ).to( space.size.$multiply( 0.9, 0.3 ) ).init( 50, 50, "fix", "fix" );
grids[1].set( space.size.$multiply( 0.1, 0.4 ) ).to( space.size.$multiply( 0.9, 0.6 ) ).init( 50, 50, "flex", "flex" );
grids[2].set( space.size.$multiply( 0.1, 0.7 ) ).to( space.size.$multiply( 0.9, 0.9 ) ).init( 5, 8, "stretch", "stretch" );
}
});
// 4. Start playing
space.bindMouse();
space.play();
|
williamngan/pt
|
demo/grid.generate.js
|
JavaScript
|
apache-2.0
| 2,324
|
var markers = [];
var marker_icons = [];
var lat_lon_to_marker = {};
var selected_marker_icons = [];
var selected_marker, selected_icon;
var map;
var start_date = 1850;
var end_date = 2000;
var FEEDBACK_URL = 'http://www.oldnyc.org/rec_feedback';
var mapPromise = $.Deferred();
function thumbnailImageUrl(photo_id) {
return 'http://oldnyc-assets.nypl.org/thumb/' + photo_id + '.jpg';
}
function expandedImageUrl(photo_id) {
return 'http://oldnyc-assets.nypl.org/600px/' + photo_id + '.jpg';
}
// lat_lon is a "lat,lon" string.
function makeStaticMapsUrl(lat_lon) {
url = 'http://maps.googleapis.com/maps/api/staticmap?center=' + lat_lon + '&zoom=15&size=150x150&maptype=roadmap&markers=color:red%7C' + lat_lon + '&style=' + STATIC_MAP_STYLE;
return url;
}
// Make the given marker the currently selected marker.
// This is purely UI code, it doesn't touch anything other than the marker.
function selectMarker(marker, numPhotos) {
var zIndex = 0;
if (selected_marker) {
zIndex = selected_marker.getZIndex();
selected_marker.setIcon(selected_icon);
}
if (marker) {
selected_marker = marker;
selected_icon = marker.getIcon();
marker.setIcon(selected_marker_icons[numPhotos > 100 ? 100 : numPhotos]);
marker.setZIndex(100000 + zIndex);
}
}
// The callback gets fired when the info for all lat/lons at this location
// become available (i.e. after the /info RPC returns).
function displayInfoForLatLon(lat_lon, marker, opt_selectCallback) {
selectMarker(marker, lat_lons[lat_lon]);
loadInfoForLatLon(lat_lon).done(function(photoIds) {
var selectedId = null;
if (photoIds.length <= 10) {
selectedId = photoIds[0];
}
showExpanded(lat_lon, photoIds, selectedId);
if (opt_selectCallback && selectedId) {
opt_selectCallback(selectedId);
}
}).fail(function() {
});
}
function handleClick(e) {
var lat_lon = e.latLng.lat().toFixed(6) + ',' + e.latLng.lng().toFixed(6)
var marker = lat_lon_to_marker[lat_lon];
displayInfoForLatLon(lat_lon, marker, function(photo_id) {
$(window).trigger('openPreviewPanel');
$(window).trigger('showPhotoPreview', photo_id);
});
$(window).trigger('showGrid', lat_lon);
}
function initialize_map() {
var latlng = new google.maps.LatLng(40.74421, -73.97370);
var opts = {
zoom: 15,
maxZoom: 18,
minZoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: true,
panControl: false,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
styles: MAP_STYLE
};
map = new google.maps.Map($('#map').get(0), opts);
// This shoves the navigation bits down by a CSS-specified amount
// (see the .spacer rule). This is surprisingly hard to do.
var map_spacer = $('<div/>').append($('<div/>').addClass('spacer')).get(0);
map_spacer.index = -1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(map_spacer);
// The OldSF UI just gets in the way of Street View.
// Even worse, it blocks the "exit" button!
var streetView = map.getStreetView();
google.maps.event.addListener(streetView, 'visible_changed',
function() {
$('.streetview-hide').toggle(!streetView.getVisible());
});
// Create marker icons for each number.
marker_icons.push(null); // it's easier to be 1-based.
selected_marker_icons.push(null);
for (var i = 0; i < 100; i++) {
var num = i + 1;
var size = (num == 1 ? 9 : 13);
var selectedSize = (num == 1 ? 15 : 21);
marker_icons.push(new google.maps.MarkerImage(
'images/sprite-2014-08-29.png',
new google.maps.Size(size, size),
new google.maps.Point((i%10)*39, Math.floor(i/10)*39),
new google.maps.Point((size - 1) / 2, (size - 1)/2)
));
selected_marker_icons.push(new google.maps.MarkerImage(
'images/selected-2014-08-29.png',
new google.maps.Size(selectedSize, selectedSize),
new google.maps.Point((i%10)*39, Math.floor(i/10)*39),
new google.maps.Point((selectedSize - 1) / 2, (selectedSize - 1)/2)
));
}
// Adding markers is expensive -- it's important to defer this when possible.
var idleListener = google.maps.event.addListener(map, 'idle', function() {
google.maps.event.removeListener(idleListener);
addNewlyVisibleMarkers();
mapPromise.resolve(map);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
addNewlyVisibleMarkers();
});
}
function addNewlyVisibleMarkers() {
var bounds = map.getBounds();
for (var lat_lon in lat_lons) {
if (lat_lon in lat_lon_to_marker) continue;
var pos = parseLatLon(lat_lon);
if (!bounds.contains(pos)) continue;
createMarker(lat_lon, pos);
}
}
function parseLatLon(lat_lon) {
var ll = lat_lon.split(",");
return new google.maps.LatLng(parseFloat(ll[0]), parseFloat(ll[1]));
}
function createMarker(lat_lon, latLng) {
var count = lat_lons[lat_lon];
var marker = new google.maps.Marker({
position: latLng,
map: map,
flat: true,
visible: true,
icon: marker_icons[Math.min(count, 100)],
title: lat_lon
});
markers.push(marker);
lat_lon_to_marker[lat_lon] = marker;
google.maps.event.addListener(marker, 'click', handleClick);
// trying to debug the friggin marker
// google.maps.event.addListener(marker, "rightclick", function(event) {
// console.log(event);
// });
return marker;
}
// NOTE: This can only be called when the info for all photo_ids at the current
// position have been loaded (in particular the image widths).
// key is used to construct URL fragments.
function showExpanded(key, photo_ids, opt_selected_id) {
hideAbout();
map.set('keyboardShortcuts', false);
$('#expanded').show().data('grid-key', key);
$('.location').text(nameForLatLon(key));
var images = $.map(photo_ids, function(photo_id, idx) {
var info = infoForPhotoId(photo_id);
return $.extend({
id: photo_id,
largesrc: expandedImageUrl(photo_id),
src: thumbnailImageUrl(photo_id),
width: 600, // these are fallbacks
height: 400
}, info);
});
$('#preview-map').attr('src', makeStaticMapsUrl(key));
$('#grid-container').expandableGrid({
rowHeight: 200,
speed: 200 /* ms for transitions */
}, images);
if (opt_selected_id) {
$('#grid-container').expandableGrid('select', opt_selected_id);
}
}
function hideExpanded() {
$('#expanded').hide();
$(document).unbind('keyup');
map.set('keyboardShortcuts', true);
}
// This fills out details for either a thumbnail or the expanded image pane.
function fillPhotoPane(photo_id, $pane) {
// This could be either a thumbnail on the right-hand side or an expanded
// image, front and center.
$('.description', $pane).html(descriptionForPhotoId(photo_id));
var info = infoForPhotoId(photo_id);
$('.library-link', $pane).attr('href', libraryUrlForPhotoId(photo_id));
var canonicalUrl = getCanonicalUrlForPhoto(photo_id);
var hasBack = photo_id.match('[0-9]f');
// OCR'd text
var ocr_url = '/ocr.html#' + photo_id;
if (info.text) {
var $text = $pane.find('.text');
$text.text(info.text.replace(/\n*$/, ''));
$text.append($('<i> Typos? Help <a target=_blank href>fix them</a>.</i>'));
$text.find('a').attr('href', ocr_url);
} else if (hasBack) {
var $more = $pane.find('.more-on-back');
$more.find('a.ocr-tool').attr('href', ocr_url);
$more.find('a.nypl').attr('href', libraryUrlForPhotoId(photo_id));
$more.show();
}
var $comments = $pane.find('.comments');
var width = $comments.parent().width();
$comments.empty().append(
$('<fb:comments numPosts="5" colorscheme="light"/>')
.attr('width', width)
.attr('href', canonicalUrl))
FB.XFBML.parse($comments.get(0));
// Social links
var client = new ZeroClipboard($pane.find('.share'));
client.on('ready', function() {
client.on('copy', function(event) {
var clipboard = event.clipboardData;
clipboard.setData('text/plain', window.location.href);
});
client.on( 'aftercopy', function( event ) {
var $btn = $(event.target);
$btn.css({width: $btn.get(0).offsetWidth}).addClass('clicked').text('Copied!');
});
});
twttr.widgets.createShareButton(
document.location.href,
$pane.find('.tweet').get(0), {
count: 'none',
text: (info.original_title || info.title) + ' - ' + info.date,
via: 'Old_NYC @NYPL'
});
var $fb_holder = $pane.find('.facebook-holder');
$fb_holder.empty().append($('<fb:like>').attr({
'href': canonicalUrl,
'layout': 'button',
'action': 'like',
'show_faces': 'false',
'share': 'true'
}));
FB.XFBML.parse($fb_holder.get(0));
}
function photoIdFromATag(a) {
return $(a).attr('href').replace('/#', '');
}
function getPopularPhotoIds() {
return $('.popular-photo:visible a').map(function(_, a) {
return photoIdFromATag(a);
}).toArray();
}
// User selected a photo in the "popular" grid. Update the static map.
function updateStaticMapsUrl(photo_id) {
var key = 'New York City';
var lat_lon = findLatLonForPhoto(photo_id);
if (lat_lon) key = lat_lon;
$('#preview-map').attr('src', makeStaticMapsUrl(key));
}
function fillPopularImagesPanel() {
var makePanel = function(row) {
var $panel = $('#popular-photo-template').clone().removeAttr('id');
$panel.find('a').attr('href', '/#' + row.id);
$panel.find('img')
.attr('border', '0') // For IE8
.attr('data-src', expandedImageUrl(row.id))
.attr('height', row.height);
$panel.find('.desc').text(row.desc);
$panel.find('.loc').text(row.loc);
if (row.date) $panel.find('.date').text(' (' + row.date + ')');
return $panel.get(0);
};
var popularPhotos = $.map(popular_photos, makePanel);
$('#popular').append($(popularPhotos).show());
$(popularPhotos).appear({force_process:true});
$('#popular').on('appear', '.popular-photo', function() {
var $img = $(this).find('img[data-src]');
loadDeferredImage($img.get(0));
});
}
function loadDeferredImage(img) {
var $img = $(img);
if ($img.attr('src')) return;
$(img)
.attr('src', $(img).attr('data-src'))
.removeAttr('data-src');
}
function hidePopular() {
$('#popular').hide();
$('.popular-link').show();
}
function showPopular() {
$('#popular').show();
$('.popular-link').hide();
$('#popular').appear({force_process: true});
}
function showAbout() {
hideExpanded();
$('#about-page').show();
// Hack! There's probably a way to do this with CSS
var $container = $('#about-page .container');
var w = $container.width();
var mw = parseInt($container.css('max-width'), 0);
if (w < mw) {
$container.css('margin-left', '-' + (w / 2) + 'px');
}
}
function hideAbout() {
$('#about-page').hide();
}
function sendFeedback(photo_id, feedback_obj) {
ga('send', 'event', 'link', 'feedback', { 'page': '/#' + photo_id });
return $.ajax(FEEDBACK_URL, {
data: { 'id': photo_id, 'feedback': JSON.stringify(feedback_obj) },
method: 'post'
}).fail(function() {
console.warn('Unable to send feedback on', photo_id)
});
}
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
function setCookie(name, value) {
document.cookie = name + "=" + value + "; path=/";
}
$(function() {
// Clicks on the background or "exit" button should leave the slideshow.
$(document).on('click', '#expanded .curtains, #expanded .exit', function() {
hideExpanded();
$(window).trigger('hideGrid');
});
$('#grid-container, #expanded .header').on('click', function(e) {
if (e.target == this || $(e.target).is('.og-grid')) {
hideExpanded();
$(window).trigger('hideGrid');
}
});
// Fill in the expanded preview pane.
$('#grid-container').on('og-fill', 'li', function(e, div) {
var id = $(this).data('image-id');
$(div).empty().append(
$('#image-details-template').clone().removeAttr('id').show());
fillPhotoPane(id, $(div));
$(div).parent().find('.og-details-left').empty().append(
$('#image-details-left-template').clone().removeAttr('id').show());
var g = $('#expanded').data('grid-key');
if (g == 'pop') {
updateStaticMapsUrl(id);
}
})
.on('click', '.og-fullimg > img', function() {
var photo_id = $('#grid-container').expandableGrid('selectedId');
window.open(libraryUrlForPhotoId(photo_id), '_blank');
});
$('#grid-container').on('click', '.rotate-image-button', function(e) {
e.preventDefault();
var $img = $(this).closest('li').find('.og-fullimg > img');
var currentRotation = $img.data('rotate') || 0;
currentRotation += 90;
$img
.css('transform', 'rotate(' + currentRotation + 'deg)')
.data('rotate', currentRotation);
var photo_id = $('#grid-container').expandableGrid('selectedId');
ga('send', 'event', 'link', 'rotate', {
'page': '/#' + photo_id + '(' + currentRotation + ')'
});
sendFeedback(photo_id, {'rotate': currentRotation});
}).on('click', '.feedback-button', function(e) {
e.preventDefault();
$('#grid-container .details').fadeOut();
$('#grid-container .feedback').fadeIn();
}).on('click', 'a.back', function(e) {
e.preventDefault();
$('#grid-container .feedback').fadeOut();
$('#grid-container .details').fadeIn();
});
$(document).on('keyup', 'input, textarea', function(e) { e.stopPropagation(); });
$('#grid-container').on('click', 'a.email-share', function(e) {
var $social = $(this).parents('.social');
var $form = $social.find('.email-share-form');
$form.find('input').val(document.location.href);
$form.toggle();
$form.find('input').focus();
e.preventDefault();
}).on('click', '.email-share-form .close', function(e) {
var $form = $(this).parents('.email-share-form');
$form.toggle();
e.preventDefault();
});
$('.popular-photo').on('click', 'a', function(e) {
e.preventDefault();
var selectedPhotoId = photoIdFromATag(this);
loadInfoForLatLon('pop').done(function(photoIds) {
showExpanded('pop', photoIds, selectedPhotoId);
$(window).trigger('showGrid', 'pop');
$(window).trigger('openPreviewPanel');
$(window).trigger('showPhotoPreview', selectedPhotoId);
}).fail(function() {
});
});
// ... it's annoying that we have to do this. jquery.appear.js should work!
$('#popular').on('scroll', function() {
$(this).appear({force_process: true});
});
// Show/hide popular images
$('#popular .close').on('click', function() {
setCookie('nopop', '1');
hidePopular();
});
$('.popular-link a').on('click', function(e) {
showPopular();
deleteCookie('nopop');
e.preventDefault();
});
if (document.cookie.indexOf('nopop=') >= 0) {
hidePopular();
}
// Display the about page on top of the map.
$('#about a').on('click', function(e) {
e.preventDefault();
showAbout();
});
$('#about-page .curtains, #about-page .exit').on('click', function(e) {
hideAbout();
});
// Record feedback on images. Can have a parameter or not.
var thanks = function(button) {
return function() { $(button).text('Thanks!'); };
};
$('#grid-container').on('click', '.feedback button[feedback]', function() {
var $button = $(this);
var value = true;
if ($button.attr('feedback-param')) {
var $input = $button.siblings('input, textarea');
value = $input.val();
if (value == '') return;
$input.prop('disabled', true);
}
$button.prop('disabled', true);
var photo_id = $('#grid-container').expandableGrid('selectedId');
var obj = {}; obj[$button.attr('feedback')] = value;
sendFeedback(photo_id, obj).then(thanks($button.get(0)));
});
$('#grid-container').on('og-select', 'li', function() {
var photo_id = $(this).data('image-id')
$(window).trigger('showPhotoPreview', photo_id);
}).on('og-deselect', function() {
$(window).trigger('closePreviewPanel');
}).on('og-openpreview', function() {
$(window).trigger('openPreviewPanel');
});
});
|
luster/oldnyc
|
viewer/static/js/viewer.js
|
JavaScript
|
apache-2.0
| 16,202
|
package it.nicogiangregorio.core.impl;
import it.nicogiangregorio.core.ICaptchaAction;
import it.nicogiangregorio.utils.WebConstants;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Verify if the answer provided by client is correct or not and redirect to
* correct jsp
*
* @author nickg
*
*/
public class CaptchaVerifyAction implements ICaptchaAction {
@Override
public String process(HttpServletRequest request,
HttpServletResponse response) {
String hashCaptcha = request.getParameter(WebConstants.PARAM_CAPTCHA)
.substring(WebConstants.PARAM_CAPTCHA_SUBSTR.length());
String captchaAnswer = (String) request.getSession().getAttribute(
WebConstants.ATTR_CAPTCHA_ANSWER);
String result = "";
if (captchaAnswer.equals(hashCaptcha))
result = WebConstants.VERIFY_RESULT_SUCCESS;
else {
request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_CODES,
null);
request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_ANSWER,
null);
result = WebConstants.VERIFY_RESULT_FAILED;
}
request.getSession().setAttribute(WebConstants.VERIFY_RESULT, result);
return WebConstants.VERIFY_FORWARD_JSP;
}
}
|
nicogiangregorio/java-ajax-captcha
|
src/it/nicogiangregorio/core/impl/CaptchaVerifyAction.java
|
Java
|
apache-2.0
| 1,215
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h>
#include <aws/kinesisanalyticsv2/model/S3ContentBaseLocationUpdate.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace KinesisAnalyticsV2
{
namespace Model
{
/**
* <p>Updates to the configuration information required to deploy an Amazon Data
* Analytics Studio notebook as an application with durable state..</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/DeployAsApplicationConfigurationUpdate">AWS
* API Reference</a></p>
*/
class AWS_KINESISANALYTICSV2_API DeployAsApplicationConfigurationUpdate
{
public:
DeployAsApplicationConfigurationUpdate();
DeployAsApplicationConfigurationUpdate(Aws::Utils::Json::JsonView jsonValue);
DeployAsApplicationConfigurationUpdate& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline const S3ContentBaseLocationUpdate& GetS3ContentLocationUpdate() const{ return m_s3ContentLocationUpdate; }
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline bool S3ContentLocationUpdateHasBeenSet() const { return m_s3ContentLocationUpdateHasBeenSet; }
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline void SetS3ContentLocationUpdate(const S3ContentBaseLocationUpdate& value) { m_s3ContentLocationUpdateHasBeenSet = true; m_s3ContentLocationUpdate = value; }
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline void SetS3ContentLocationUpdate(S3ContentBaseLocationUpdate&& value) { m_s3ContentLocationUpdateHasBeenSet = true; m_s3ContentLocationUpdate = std::move(value); }
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline DeployAsApplicationConfigurationUpdate& WithS3ContentLocationUpdate(const S3ContentBaseLocationUpdate& value) { SetS3ContentLocationUpdate(value); return *this;}
/**
* <p>Updates to the location that holds the data required to specify an Amazon
* Data Analytics application.</p>
*/
inline DeployAsApplicationConfigurationUpdate& WithS3ContentLocationUpdate(S3ContentBaseLocationUpdate&& value) { SetS3ContentLocationUpdate(std::move(value)); return *this;}
private:
S3ContentBaseLocationUpdate m_s3ContentLocationUpdate;
bool m_s3ContentLocationUpdateHasBeenSet;
};
} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws
|
awslabs/aws-sdk-cpp
|
aws-cpp-sdk-kinesisanalyticsv2/include/aws/kinesisanalyticsv2/model/DeployAsApplicationConfigurationUpdate.h
|
C
|
apache-2.0
| 3,133
|
/**
* 2013-4-12
*/
package com.meteorite.core.parser.book;
import com.metaui.core.parser.book.IWebProduct;
import com.metaui.core.parser.book.OpenBookDataParser;
import com.metaui.core.parser.book.ProductPic;
import com.metaui.core.parser.book.SiteName;
import org.junit.Test;
import java.text.ParseException;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* @author wang_liang
* @Date 2013-4-12 下午01:28:52
* @since 1.0
*/
public class OpenBookDataTest {
@Test
public void testParser() throws Exception {
OpenBookDataParser parser = new OpenBookDataParser(3328918);
List<IWebProduct> list = parser.parse();
assertThat(list.size(), equalTo(1));
IWebProduct prod = list.get(0);
System.out.println(prod);
List<ProductPic> picList = prod.getProductPic();
assertThat(picList.size(), equalTo(1));
assertThat(picList.get(0).getUrl().toString(), equalTo("http://image-1.openbook.com.cn/BookCover/20140328/3324753.jpg"));
assertThat(prod.getSourceSite(), equalTo(SiteName.OPEN_BOOK_DATA.name()));
assertThat(prod.getName(), equalTo("记得自己:第四道传统精选"));
assertThat(prod.getAuthor(), equalTo("葛吉夫,邬斯宾斯基"));
assertThat(prod.getPrice(), equalTo("36.00"));
assertThat(prod.getPublishing(), equalTo("中央编译出版社"));
assertThat(prod.getPublishDate(), equalTo("2014-03"));
assertThat(prod.getIsbn(), equalTo("9787511720610"));
assertThat(prod.getBanci(), equalTo("第1版"));
assertThat(prod.getKaiben(), equalTo("16开"));
assertThat(prod.getPageNum(), equalTo("168"));
assertThat(prod.getPack(), equalTo("平装"));
assertThat(prod.getTranslator(), equalTo("王君永"));
assertThat(prod.getWordCount(), equalTo("123.0"));
String media = "传统之路,如佛教、基督教、伊斯兰教,以及印度教,已广为人知,世所公认。第四道作为一个古老的传统已经存在很久了,却鲜有人知,仅以外在形式被隐晦地表述过。所有这些道路都指往同一个方向:最终的觉醒, 禅境或悟道。我们对第四道了解越多,就越能认识和理解其它道路的内在意义。第四道在历史中的早期表述并不自称为“第四道”。葛吉夫为了与三种传统修行方式:苦行者,僧侣和瑜伽修行者(分别侧重于身体、情感和理智方面的发展)相区分,把他的介绍称为“第四道”。第四道是一种基于日常生活的修行体系,容纳了不同传统的秘义教学,并把当下的生活状况看作自我发展的平台;第四道是一条实用的道,人只有通过切身体验才能理解,并带来意识的真正改变。“记得自己”一词译自英文“Self-Remembering”,是第四道传统的核心观念及实践方法。记得自己是跨越知识和智慧的桥梁。这是一种在此刻觉察到自己的努力,脱离一个人在前一刻陷入的想象世界而回到现实。这是一种即刻的内在重组:将自己的机械念头和情感抛下,并使自己的高等自我显现——记得自己。 “第四道传统精选”是第四道精要作品的合集。作品摘选自五位第四道老师,他们从二十世纪初到现在一脉相承。因为第四道基于个人的验证、理解以及口传身教,每一位老师都以其独特的方式来阐释内在工作的本质。这也体现了第四道历久弥新。";
assertThat(prod.getMediaFeedback(), equalTo(media));
String content = "葛吉夫为了与三种传统修行方式——苦行者、僧侣和瑜伽修行者相区分,把自己的修行方式称之为“第四道”。第四道是一种基于日常生活的修行体系,容纳了不同传统的秘义教学,并把当下的生活状况看作自我发展的平台;人只有通过切身体验才能理解,并带来意识的真正改变。“记得自己”一词译自英文“Self-Remembering”,是第四道传统的核心观念及实践方法。 作为一个古老的传统已经存在很久, 所有这些道路都指往同一个方向:最终的觉醒, 禅境或悟道。本书是第四道精要作品的合集,作品摘选自葛吉夫及其追随者等人物的作品。";
assertThat(prod.getContent(), equalTo(content));
String author = "葛吉夫(G. I. Gurdjieff ,1866~ 1949),曾经游学许多古老密意知识流传的地域,包括印度、西藏、埃及、麦加、苏丹、伊拉克,前半生如同一阕隐讳的神谕,没有人知晓他的真实来历、修学背景。\r" +
" 1912年在莫斯科与圣彼得堡成立修行团体,1917年俄国大革命风暴席卷每一个地方,1920年葛吉夫率领弟子逃出俄国,暂时落脚在土耳其的君士坦丁堡,成立修行机构。 1922年 定居 法国巴黎 枫丹白露 。\r" +
" 葛吉夫宣称“第四道”并非他自己发明的,而是渊自久远的古老智慧。我们可以在第四道体系中看到有些理念脱胎于佛教、苏菲密教、基督教,有些理念则是原创性的 。葛吉夫博杂广大的密意知识经由大弟子邬斯宾斯基整理后, 体系更加条理分明。";
assertThat(prod.getAuthorIntro(), equalTo(author));
String dirctory = "目 录序一)葛吉夫的格言 葛吉夫简介 格言二)论记得自己——邬斯宾斯基思想集 邬斯宾斯基简介 第一章 我的第一次尝试第二章 游移在两岸间第三章 最有趣的观念第四章 定义不会有帮助第五章 意识到不记得第六章 机械的人第七章 辨别意识与功能第八章 记得自己就是做第九章 人是一个化学工厂第十章 开始看到第十一章 第四道,学校,和有意识的影响第十二章 我教你记得自己三)有意识的和谐——郎尼·克林书信摘选 克林简介 1.第四道 2.心理工作和内在努力的正确态度 3.培养真诚而善解的心 4.记得自己 5.障碍(自我重要感,想象,不必要的谈话和说谎,负面情绪) 6.消除障碍的方法(接受,不执着,转化痛苦) 7.代价 8.丙种影响 9.学校传统 10.教学 11.邬斯宾斯基与葛吉夫 12.死亡与转化 四)有意识教学的笔记 吉拉德简介 1.机器 2.群‘我' 3.活在当下五)每日一思 罗伯特简介第四道知识和素质低等自我(想象,本能中心,认同,负面情绪)努力控制激情分开注意力记得自己转化痛苦序列当下有意识的爱本质单纯时间死亡学校丙种影响词汇表读者反馈";
assertThat(prod.getCatalog(), equalTo(dirctory));
}
}
|
weijiancai/metaui
|
core/src/test/java/com/meteorite/core/parser/book/OpenBookDataTest.java
|
Java
|
apache-2.0
| 6,726
|
<emu-production name="TypeParameters">
<emu-rhs a="27ce0641">
<emu-t><</emu-t>
<emu-nt>TypeParameterList</emu-nt>
<emu-t>></emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TypeParameterList">
<emu-rhs a="49b4855e"><emu-nt>TypeParameter</emu-nt></emu-rhs>
<emu-rhs a="89045ccd">
<emu-nt>TypeParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>TypeParameter</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeParameter">
<emu-rhs a="94e4958a">
<emu-nt>Identifier</emu-nt>
<emu-nt optional>Constraint</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="Constraint">
<emu-rhs a="f5cc0152">
<emu-t>extends</emu-t>
<emu-nt>Type</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeArguments">
<emu-rhs a="8f8c81b6">
<emu-t><</emu-t>
<emu-nt>TypeArgumentList</emu-nt>
<emu-t>></emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TypeArgumentList">
<emu-rhs a="f89ea15f"><emu-nt>TypeArgument</emu-nt></emu-rhs>
<emu-rhs a="6ad31614">
<emu-nt>TypeArgumentList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>TypeArgument</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeArgument">
<emu-rhs a="3deb7456"><emu-nt>Type</emu-nt></emu-rhs>
</emu-production>
<emu-production name="Type">
<emu-rhs a="257564ec"><emu-nt>PrimaryOrUnionType</emu-nt></emu-rhs>
<emu-rhs a="e94e83ec"><emu-nt>FunctionType</emu-nt></emu-rhs>
<emu-rhs a="a468d46c"><emu-nt>ConstructorType</emu-nt></emu-rhs>
</emu-production>
<emu-production name="PrimaryOrUnionType">
<emu-rhs a="9713b445"><emu-nt>PrimaryType</emu-nt></emu-rhs>
<emu-rhs a="2cfef1bf"><emu-nt>UnionType</emu-nt></emu-rhs>
</emu-production>
<emu-production name="PrimaryType">
<emu-rhs a="ea3ff2ed"><emu-nt>ParenthesizedType</emu-nt></emu-rhs>
<emu-rhs a="aeee8ad9"><emu-nt>PredefinedType</emu-nt></emu-rhs>
<emu-rhs a="74e8bc50"><emu-nt>TypeReference</emu-nt></emu-rhs>
<emu-rhs a="34f1b931"><emu-nt>ObjectType</emu-nt></emu-rhs>
<emu-rhs a="77e0a11a"><emu-nt>ArrayType</emu-nt></emu-rhs>
<emu-rhs a="afea73f1"><emu-nt>TupleType</emu-nt></emu-rhs>
<emu-rhs a="924031c9"><emu-nt>TypeQuery</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ParenthesizedType">
<emu-rhs a="1ac8fd41">
<emu-t>(</emu-t>
<emu-nt>Type</emu-nt>
<emu-t>)</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="PredefinedType">
<emu-rhs a="8ca7f9b0"><emu-t>any</emu-t></emu-rhs>
<emu-rhs a="cf8fbef8"><emu-t>number</emu-t></emu-rhs>
<emu-rhs a="5e82704d"><emu-t>boolean</emu-t></emu-rhs>
<emu-rhs a="f5c10ab3"><emu-t>string</emu-t></emu-rhs>
<emu-rhs a="94b80d2f"><emu-t>void</emu-t></emu-rhs>
</emu-production>
<emu-production name="TypeReference">
<emu-rhs a="8035819d">
<emu-nt>TypeName</emu-nt>
<emu-gann>no <emu-nt>LineTerminator</emu-nt> here</emu-gann>
<emu-nt optional>TypeArguments</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeName">
<emu-rhs a="06b6ace8"><emu-nt>Identifier</emu-nt></emu-rhs>
<emu-rhs a="5a7de153">
<emu-nt>ModuleName</emu-nt>
<emu-t>.</emu-t>
<emu-nt>Identifier</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ModuleName">
<emu-rhs a="06b6ace8"><emu-nt>Identifier</emu-nt></emu-rhs>
<emu-rhs a="5a7de153">
<emu-nt>ModuleName</emu-nt>
<emu-t>.</emu-t>
<emu-nt>Identifier</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ObjectType">
<emu-rhs a="a7a8ac82">
<emu-t>{</emu-t>
<emu-nt optional>TypeBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TypeBody">
<emu-rhs a="bc262b5a">
<emu-nt>TypeMemberList</emu-nt>
<emu-t optional>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TypeMemberList">
<emu-rhs a="4e9429c1"><emu-nt>TypeMember</emu-nt></emu-rhs>
<emu-rhs a="1e7cb02e">
<emu-nt>TypeMemberList</emu-nt>
<emu-t>;</emu-t>
<emu-nt>TypeMember</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeMember">
<emu-rhs a="89003b98"><emu-nt>PropertySignature</emu-nt></emu-rhs>
<emu-rhs a="c1501895"><emu-nt>CallSignature</emu-nt></emu-rhs>
<emu-rhs a="56fc3592"><emu-nt>ConstructSignature</emu-nt></emu-rhs>
<emu-rhs a="0dd6b549"><emu-nt>IndexSignature</emu-nt></emu-rhs>
<emu-rhs a="52cd7cd6"><emu-nt>MethodSignature</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ArrayType">
<emu-rhs a="3cec7106">
<emu-nt>PrimaryType</emu-nt>
<emu-gann>no <emu-nt>LineTerminator</emu-nt> here</emu-gann>
<emu-t>[</emu-t>
<emu-t>]</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TupleType">
<emu-rhs a="5173d7d7">
<emu-t>[</emu-t>
<emu-nt>TupleElementTypes</emu-nt>
<emu-t>]</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="TupleElementTypes">
<emu-rhs a="eda6874c"><emu-nt>TupleElementType</emu-nt></emu-rhs>
<emu-rhs a="6bd6800d">
<emu-nt>TupleElementTypes</emu-nt>
<emu-t>,</emu-t>
<emu-nt>TupleElementType</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TupleElementType">
<emu-rhs a="3deb7456"><emu-nt>Type</emu-nt></emu-rhs>
</emu-production>
<emu-production name="UnionType">
<emu-rhs a="93d8bd25">
<emu-nt>PrimaryOrUnionType</emu-nt>
<emu-t>|</emu-t>
<emu-nt>PrimaryType</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="FunctionType">
<emu-rhs a="8f7a82e7">
<emu-nt optional>TypeParameters</emu-nt>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-t>=></emu-t>
<emu-nt>Type</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ConstructorType">
<emu-rhs a="4490a1b4">
<emu-t>new</emu-t>
<emu-nt optional>TypeParameters</emu-nt>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-t>=></emu-t>
<emu-nt>Type</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeQuery">
<emu-rhs a="7fdc10c8">
<emu-t>typeof</emu-t>
<emu-nt>TypeQueryExpression</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeQueryExpression">
<emu-rhs a="06b6ace8"><emu-nt>Identifier</emu-nt></emu-rhs>
<emu-rhs a="74ca3afb">
<emu-nt>TypeQueryExpression</emu-nt>
<emu-t>.</emu-t>
<emu-nt>IdentifierName</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="PropertySignature">
<emu-rhs a="45625f88">
<emu-nt>PropertyName</emu-nt>
<emu-t optional>?</emu-t>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="PropertyName">
<emu-rhs a="0ebb31e2"><emu-nt>IdentifierName</emu-nt></emu-rhs>
<emu-rhs a="5c74e54d"><emu-nt>StringLiteral</emu-nt></emu-rhs>
<emu-rhs a="a548b407"><emu-nt>NumericLiteral</emu-nt></emu-rhs>
</emu-production>
<emu-production name="CallSignature">
<emu-rhs a="480c0935">
<emu-nt optional>TypeParameters</emu-nt>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ParameterList">
<emu-rhs a="bf71dbf2"><emu-nt>RequiredParameterList</emu-nt></emu-rhs>
<emu-rhs a="9c07b35b"><emu-nt>OptionalParameterList</emu-nt></emu-rhs>
<emu-rhs a="8334dabd"><emu-nt>RestParameter</emu-nt></emu-rhs>
<emu-rhs a="c5f488db">
<emu-nt>RequiredParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>OptionalParameterList</emu-nt>
</emu-rhs>
<emu-rhs a="cea83933">
<emu-nt>RequiredParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>RestParameter</emu-nt>
</emu-rhs>
<emu-rhs a="7ecbaedf">
<emu-nt>OptionalParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>RestParameter</emu-nt>
</emu-rhs>
<emu-rhs a="7d876e16">
<emu-nt>RequiredParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>OptionalParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>RestParameter</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="RequiredParameterList">
<emu-rhs a="cb233da7"><emu-nt>RequiredParameter</emu-nt></emu-rhs>
<emu-rhs a="fc994f02">
<emu-nt>RequiredParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>RequiredParameter</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="RequiredParameter">
<emu-rhs a="6b890662">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
<emu-rhs a="e691ee59">
<emu-nt>Identifier</emu-nt>
<emu-t>:</emu-t>
<emu-nt>StringLiteral</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AccessibilityModifier">
<emu-rhs a="212f55e2"><emu-t>public</emu-t></emu-rhs>
<emu-rhs a="af3e0d5c"><emu-t>private</emu-t></emu-rhs>
<emu-rhs a="c1d398df"><emu-t>protected</emu-t></emu-rhs>
</emu-production>
<emu-production name="OptionalParameterList">
<emu-rhs a="12543786"><emu-nt>OptionalParameter</emu-nt></emu-rhs>
<emu-rhs a="2e0ba35a">
<emu-nt>OptionalParameterList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>OptionalParameter</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="OptionalParameter">
<emu-rhs a="f505d701">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-nt>Identifier</emu-nt>
<emu-t>?</emu-t>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
<emu-rhs a="370e9f41">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-nt>Initializer</emu-nt>
</emu-rhs>
<emu-rhs a="94975a30">
<emu-nt>Identifier</emu-nt>
<emu-t>?</emu-t>
<emu-t>:</emu-t>
<emu-nt>StringLiteral</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="RestParameter">
<emu-rhs a="40daecaf">
<emu-t>...</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ConstructSignature">
<emu-rhs a="cf9fd631">
<emu-t>new</emu-t>
<emu-nt optional>TypeParameters</emu-nt>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-nt optional>TypeAnnotation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="IndexSignature">
<emu-rhs a="a7214a14">
<emu-t>[</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>:</emu-t>
<emu-t>string</emu-t>
<emu-t>]</emu-t>
<emu-nt>TypeAnnotation</emu-nt>
</emu-rhs>
<emu-rhs a="b128da0b">
<emu-t>[</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>:</emu-t>
<emu-t>number</emu-t>
<emu-t>]</emu-t>
<emu-nt>TypeAnnotation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="MethodSignature">
<emu-rhs a="68389351">
<emu-nt>PropertyName</emu-nt>
<emu-t optional>?</emu-t>
<emu-nt>CallSignature</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeAliasDeclaration">
<emu-rhs a="86b51e79">
<emu-t>type</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>=</emu-t>
<emu-nt>Type</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="PropertyAssignment">
<emu-rhs a="f2d90b76">
<emu-nt>PropertyName</emu-nt>
<emu-t>:</emu-t>
<emu-nt>AssignmentExpression</emu-nt>
</emu-rhs>
<emu-rhs a="f47f84c4">
<emu-nt>PropertyName</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
<emu-rhs a="9467bae2"><emu-nt>GetAccessor</emu-nt></emu-rhs>
<emu-rhs a="72d41f73"><emu-nt>SetAccessor</emu-nt></emu-rhs>
</emu-production>
<emu-production name="GetAccessor">
<emu-rhs a="56ed38d2">
<emu-t>get</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-t>(</emu-t>
<emu-t>)</emu-t>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="SetAccessor">
<emu-rhs a="e450b10a">
<emu-t>set</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-t>(</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-t>)</emu-t>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="ElementList">
<emu-rhs a="d806b57a">
<emu-nt optional>Elision</emu-nt>
<emu-nt>AssignmentExpression</emu-nt>
</emu-rhs>
<emu-rhs a="141a73d1">
<emu-nt optional>Elision</emu-nt>
<emu-nt>SpreadElement</emu-nt>
</emu-rhs>
<emu-rhs a="fd2af9b1">
<emu-nt>ElementList</emu-nt>
<emu-t>,</emu-t>
<emu-nt optional>Elision</emu-nt>
<emu-nt>AssignmentExpression</emu-nt>
</emu-rhs>
<emu-rhs a="6a579a6a">
<emu-nt>ElementList</emu-nt>
<emu-t>,</emu-t>
<emu-nt optional>Elision</emu-nt>
<emu-nt>SpreadElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="SpreadElement">
<emu-rhs a="5bb8853e">
<emu-t>...</emu-t>
<emu-nt>AssignmentExpression</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="CallExpression">
<emu-rhs a="35d9ba9f">
<emu-t>super</emu-t>
<emu-t>(</emu-t>
<emu-nt optional>ArgumentList</emu-nt>
<emu-t>)</emu-t>
</emu-rhs>
<emu-rhs a="f690ec4a">
<emu-t>super</emu-t>
<emu-t>.</emu-t>
<emu-nt>IdentifierName</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="FunctionExpression">
<emu-rhs a="ac6ff6fe">
<emu-t>function</emu-t>
<emu-nt optional>Identifier</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AssignmentExpression">
<emu-rhs a="bead12de"><emu-nt>ArrowFunctionExpression</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ArrowFunctionExpression">
<emu-rhs a="55d6be67">
<emu-nt>ArrowFormalParameters</emu-nt>
<emu-t>=></emu-t>
<emu-nt>Block</emu-nt>
</emu-rhs>
<emu-rhs a="05b42266">
<emu-nt>ArrowFormalParameters</emu-nt>
<emu-t>=></emu-t>
<emu-nt>AssignmentExpression</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ArrowFormalParameters">
<emu-rhs a="c1501895"><emu-nt>CallSignature</emu-nt></emu-rhs>
<emu-rhs a="06b6ace8"><emu-nt>Identifier</emu-nt></emu-rhs>
</emu-production>
<emu-production name="Arguments">
<emu-rhs a="e7c468c3">
<emu-nt optional>TypeArguments</emu-nt>
<emu-t>(</emu-t>
<emu-nt optional>ArgumentList</emu-nt>
<emu-t>)</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="UnaryExpression">
<emu-rhs a="70eae169">
<emu-t><</emu-t>
<emu-nt>Type</emu-nt>
<emu-t>></emu-t>
<emu-nt>UnaryExpression</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="VariableDeclaration">
<emu-rhs a="2e75bf14"><emu-nt>SimpleVariableDeclaration</emu-nt></emu-rhs>
<emu-rhs a="eaa77664"><emu-nt>DestructuringVariableDeclaration</emu-nt></emu-rhs>
</emu-production>
<emu-production name="SimpleVariableDeclaration">
<emu-rhs a="d903f0bc">
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="TypeAnnotation">
<emu-rhs a="7d690620">
<emu-t>:</emu-t>
<emu-nt>Type</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="DestructuringVariableDeclaration">
<emu-rhs a="bc46404c">
<emu-nt>BindingPattern</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-nt>Initializer</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="BindingPattern">
<emu-rhs a="987dce43"><emu-nt>ObjectBindingPattern</emu-nt></emu-rhs>
<emu-rhs a="c638d53b"><emu-nt>ArrayBindingPattern</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ObjectBindingPattern">
<emu-rhs a="81ba5a4a">
<emu-t>{</emu-t>
<emu-t>}</emu-t>
</emu-rhs>
<emu-rhs a="f5bb9114">
<emu-t>{</emu-t>
<emu-nt>BindingPropertyList</emu-nt>
<emu-t optional>,</emu-t>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="BindingPropertyList">
<emu-rhs a="63dcfab3"><emu-nt>BindingProperty</emu-nt></emu-rhs>
<emu-rhs a="0730de3b">
<emu-nt>BindingPropertyList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>BindingProperty</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="BindingProperty">
<emu-rhs a="03059906">
<emu-nt>Identifier</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
<emu-rhs a="10e7598a">
<emu-nt>PropertyName</emu-nt>
<emu-t>:</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
<emu-rhs a="85bf9933">
<emu-nt>PropertyName</emu-nt>
<emu-t>:</emu-t>
<emu-nt>BindingPattern</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ArrayBindingPattern">
<emu-rhs a="3493053b">
<emu-t>[</emu-t>
<emu-nt optional>Elision</emu-nt>
<emu-nt optional>BindingRestElement</emu-nt>
<emu-t>]</emu-t>
</emu-rhs>
<emu-rhs a="1d096493">
<emu-t>[</emu-t>
<emu-nt>BindingElementList</emu-nt>
<emu-t>]</emu-t>
</emu-rhs>
<emu-rhs a="d766001e">
<emu-t>[</emu-t>
<emu-nt>BindingElementList</emu-nt>
<emu-t>,</emu-t>
<emu-nt optional>Elision</emu-nt>
<emu-nt optional>BindingRestElement</emu-nt>
<emu-t>]</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="BindingElementList">
<emu-rhs a="5a8f4d01">
<emu-nt optional>Elision</emu-nt>
<emu-nt>BindingElement</emu-nt>
</emu-rhs>
<emu-rhs a="4e199680">
<emu-nt>BindingElementList</emu-nt>
<emu-t>,</emu-t>
<emu-nt optional>Elision</emu-nt>
<emu-nt>BindingElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="BindingElement">
<emu-rhs a="03059906">
<emu-nt>Identifier</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
<emu-rhs a="6875fa94">
<emu-nt>BindingPattern</emu-nt>
<emu-nt optional>Initializer</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="BindingRestElement">
<emu-rhs a="ba1e81db">
<emu-t>...</emu-t>
<emu-nt>Identifier</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="FunctionDeclaration">
<emu-rhs a="9fb60434">
<emu-nt optional>FunctionOverloads</emu-nt>
<emu-nt>FunctionImplementation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="FunctionOverloads">
<emu-rhs a="0a661d5e"><emu-nt>FunctionOverload</emu-nt></emu-rhs>
<emu-rhs a="9866b7f2">
<emu-nt>FunctionOverloads</emu-nt>
<emu-nt>FunctionOverload</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="FunctionOverload">
<emu-rhs a="dea5cafe">
<emu-t>function</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="FunctionImplementation">
<emu-rhs a="44f98fb3">
<emu-t>function</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="InterfaceDeclaration">
<emu-rhs a="1cdcb447">
<emu-t>interface</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeParameters</emu-nt>
<emu-nt optional>InterfaceExtendsClause</emu-nt>
<emu-nt>ObjectType</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="InterfaceExtendsClause">
<emu-rhs a="5fa66fb1">
<emu-t>extends</emu-t>
<emu-nt>ClassOrInterfaceTypeList</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassOrInterfaceTypeList">
<emu-rhs a="cad70070"><emu-nt>ClassOrInterfaceType</emu-nt></emu-rhs>
<emu-rhs a="9cf0c139">
<emu-nt>ClassOrInterfaceTypeList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>ClassOrInterfaceType</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassOrInterfaceType">
<emu-rhs a="74e8bc50"><emu-nt>TypeReference</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ClassDeclaration">
<emu-rhs a="16f719aa">
<emu-t>class</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeParameters</emu-nt>
<emu-nt>ClassHeritage</emu-nt>
<emu-t>{</emu-t>
<emu-nt>ClassBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="ClassHeritage">
<emu-rhs a="24f0c615">
<emu-nt optional>ClassExtendsClause</emu-nt>
<emu-nt optional>ImplementsClause</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassExtendsClause">
<emu-rhs a="f9dd0dfb">
<emu-t>extends</emu-t>
<emu-nt>ClassType</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassType">
<emu-rhs a="74e8bc50"><emu-nt>TypeReference</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ImplementsClause">
<emu-rhs a="2a046db5">
<emu-t>implements</emu-t>
<emu-nt>ClassOrInterfaceTypeList</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassBody">
<emu-rhs a="b9f281b3"><emu-nt optional>ClassElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ClassElements">
<emu-rhs a="711bcbba"><emu-nt>ClassElement</emu-nt></emu-rhs>
<emu-rhs a="10ae112f">
<emu-nt>ClassElements</emu-nt>
<emu-nt>ClassElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ClassElement">
<emu-rhs a="7594963d"><emu-nt>ConstructorDeclaration</emu-nt></emu-rhs>
<emu-rhs a="322b3ffb"><emu-nt>PropertyMemberDeclaration</emu-nt></emu-rhs>
<emu-rhs a="9293a271"><emu-nt>IndexMemberDeclaration</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ConstructorDeclaration">
<emu-rhs a="99e2c89a">
<emu-nt optional>ConstructorOverloads</emu-nt>
<emu-nt>ConstructorImplementation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ConstructorOverloads">
<emu-rhs a="41a6177c"><emu-nt>ConstructorOverload</emu-nt></emu-rhs>
<emu-rhs a="2dbbf003">
<emu-nt>ConstructorOverloads</emu-nt>
<emu-nt>ConstructorOverload</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ConstructorOverload">
<emu-rhs a="fe883f7d">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t>constructor</emu-t>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="ConstructorImplementation">
<emu-rhs a="34afd5c4">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t>constructor</emu-t>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="PropertyMemberDeclaration">
<emu-rhs a="9c558c1b"><emu-nt>MemberVariableDeclaration</emu-nt></emu-rhs>
<emu-rhs a="e5bd8a89"><emu-nt>MemberFunctionDeclaration</emu-nt></emu-rhs>
<emu-rhs a="338d1587"><emu-nt>MemberAccessorDeclaration</emu-nt></emu-rhs>
</emu-production>
<emu-production name="MemberVariableDeclaration">
<emu-rhs a="cbfd2fee">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-nt optional>Initializer</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="MemberFunctionDeclaration">
<emu-rhs a="d9f4fd41">
<emu-nt optional>MemberFunctionOverloads</emu-nt>
<emu-nt>MemberFunctionImplementation</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="MemberFunctionOverloads">
<emu-rhs a="bac756b8"><emu-nt>MemberFunctionOverload</emu-nt></emu-rhs>
<emu-rhs a="c354b913">
<emu-nt>MemberFunctionOverloads</emu-nt>
<emu-nt>MemberFunctionOverload</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="MemberFunctionOverload">
<emu-rhs a="038c8b1f">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="MemberFunctionImplementation">
<emu-rhs a="8e940169">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>{</emu-t>
<emu-nt>FunctionBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="MemberAccessorDeclaration">
<emu-rhs a="38f5d586">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>GetAccessor</emu-nt>
</emu-rhs>
<emu-rhs a="bbe46c14">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>SetAccessor</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="IndexMemberDeclaration">
<emu-rhs a="526914fe">
<emu-nt>IndexSignature</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="EnumDeclaration">
<emu-rhs a="a70c06aa">
<emu-t optional>const</emu-t>
<emu-t>enum</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>{</emu-t>
<emu-nt optional>EnumBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="EnumBody">
<emu-rhs a="686fbeb1">
<emu-nt>EnumMemberList</emu-nt>
<emu-t optional>,</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="EnumMemberList">
<emu-rhs a="5459409c"><emu-nt>EnumMember</emu-nt></emu-rhs>
<emu-rhs a="ec39fe71">
<emu-nt>EnumMemberList</emu-nt>
<emu-t>,</emu-t>
<emu-nt>EnumMember</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="EnumMember">
<emu-rhs a="06660efb"><emu-nt>PropertyName</emu-nt></emu-rhs>
<emu-rhs a="e8638251">
<emu-nt>PropertyName</emu-nt>
<emu-t>=</emu-t>
<emu-nt>EnumValue</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="EnumValue">
<emu-rhs a="d4fc7da4"><emu-nt>AssignmentExpression</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ModuleDeclaration">
<emu-rhs a="0c1d8d8b">
<emu-t>module</emu-t>
<emu-nt>IdentifierPath</emu-nt>
<emu-t>{</emu-t>
<emu-nt>ModuleBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="IdentifierPath">
<emu-rhs a="06b6ace8"><emu-nt>Identifier</emu-nt></emu-rhs>
<emu-rhs a="3bb835f2">
<emu-nt>IdentifierPath</emu-nt>
<emu-t>.</emu-t>
<emu-nt>Identifier</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ModuleBody">
<emu-rhs a="fec4dc75"><emu-nt optional>ModuleElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ModuleElements">
<emu-rhs a="8d133973"><emu-nt>ModuleElement</emu-nt></emu-rhs>
<emu-rhs a="268b379e">
<emu-nt>ModuleElements</emu-nt>
<emu-nt>ModuleElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ModuleElement">
<emu-rhs a="a72ca256"><emu-nt>Statement</emu-nt></emu-rhs>
<emu-rhs a="34b71929">
<emu-t optional>export</emu-t>
<emu-nt>VariableDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="6abe6389">
<emu-t optional>export</emu-t>
<emu-nt>FunctionDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="a9b7ac21">
<emu-t optional>export</emu-t>
<emu-nt>ClassDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="fa4fbeee">
<emu-t optional>export</emu-t>
<emu-nt>InterfaceDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="34dc9187">
<emu-t optional>export</emu-t>
<emu-nt>TypeAliasDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="39d184a5">
<emu-t optional>export</emu-t>
<emu-nt>EnumDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="f8c9cef1">
<emu-t optional>export</emu-t>
<emu-nt>ModuleDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="d5fe2535">
<emu-t optional>export</emu-t>
<emu-nt>ImportDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="eae3e7f7">
<emu-t optional>export</emu-t>
<emu-nt>AmbientDeclaration</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ImportDeclaration">
<emu-rhs a="1aa6f78c">
<emu-t>import</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>=</emu-t>
<emu-nt>EntityName</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="EntityName">
<emu-rhs a="82949a8b"><emu-nt>ModuleName</emu-nt></emu-rhs>
<emu-rhs a="5a7de153">
<emu-nt>ModuleName</emu-nt>
<emu-t>.</emu-t>
<emu-nt>Identifier</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="SourceFile">
<emu-rhs a="b2ed1f42"><emu-nt>ImplementationSourceFile</emu-nt></emu-rhs>
<emu-rhs a="f2f895e8"><emu-nt>DeclarationSourceFile</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ImplementationSourceFile">
<emu-rhs a="c9861c0d"><emu-nt optional>ImplementationElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="ImplementationElements">
<emu-rhs a="d9a7edd0"><emu-nt>ImplementationElement</emu-nt></emu-rhs>
<emu-rhs a="99927227">
<emu-nt>ImplementationElements</emu-nt>
<emu-nt>ImplementationElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ImplementationElement">
<emu-rhs a="8d133973"><emu-nt>ModuleElement</emu-nt></emu-rhs>
<emu-rhs a="d0c90aa3"><emu-nt>ExportAssignment</emu-nt></emu-rhs>
<emu-rhs a="e0a1092c"><emu-nt>AmbientExternalModuleDeclaration</emu-nt></emu-rhs>
<emu-rhs a="a24c5f54">
<emu-t optional>export</emu-t>
<emu-nt>ExternalImportDeclaration</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="DeclarationSourceFile">
<emu-rhs a="38273fe5"><emu-nt optional>DeclarationElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="DeclarationElements">
<emu-rhs a="2cbc20a6"><emu-nt>DeclarationElement</emu-nt></emu-rhs>
<emu-rhs a="5cb364b5">
<emu-nt>DeclarationElements</emu-nt>
<emu-nt>DeclarationElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="DeclarationElement">
<emu-rhs a="d0c90aa3"><emu-nt>ExportAssignment</emu-nt></emu-rhs>
<emu-rhs a="e0a1092c"><emu-nt>AmbientExternalModuleDeclaration</emu-nt></emu-rhs>
<emu-rhs a="fa4fbeee">
<emu-t optional>export</emu-t>
<emu-nt>InterfaceDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="34dc9187">
<emu-t optional>export</emu-t>
<emu-nt>TypeAliasDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="d5fe2535">
<emu-t optional>export</emu-t>
<emu-nt>ImportDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="eae3e7f7">
<emu-t optional>export</emu-t>
<emu-nt>AmbientDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="a24c5f54">
<emu-t optional>export</emu-t>
<emu-nt>ExternalImportDeclaration</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="ExternalImportDeclaration">
<emu-rhs a="cf7ef861">
<emu-t>import</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>=</emu-t>
<emu-nt>ExternalModuleReference</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="ExternalModuleReference">
<emu-rhs a="ba0c8dfe">
<emu-t>require</emu-t>
<emu-t>(</emu-t>
<emu-nt>StringLiteral</emu-nt>
<emu-t>)</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="ExportAssignment">
<emu-rhs a="dad84a0d">
<emu-t>export</emu-t>
<emu-t>=</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientDeclaration">
<emu-rhs a="cb9ab148">
<emu-t>declare</emu-t>
<emu-nt>AmbientVariableDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="396404d7">
<emu-t>declare</emu-t>
<emu-nt>AmbientFunctionDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="4b890a8f">
<emu-t>declare</emu-t>
<emu-nt>AmbientClassDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="9e7af45a">
<emu-t>declare</emu-t>
<emu-nt>AmbientEnumDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="54ae2790">
<emu-t>declare</emu-t>
<emu-nt>AmbientModuleDeclaration</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AmbientVariableDeclaration">
<emu-rhs a="ebd60185">
<emu-t>var</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientFunctionDeclaration">
<emu-rhs a="dea5cafe">
<emu-t>function</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientClassDeclaration">
<emu-rhs a="932879ae">
<emu-t>class</emu-t>
<emu-nt>Identifier</emu-nt>
<emu-nt optional>TypeParameters</emu-nt>
<emu-nt>ClassHeritage</emu-nt>
<emu-t>{</emu-t>
<emu-nt>AmbientClassBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientClassBody">
<emu-rhs a="a3220708"><emu-nt optional>AmbientClassBodyElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="AmbientClassBodyElements">
<emu-rhs a="e310767b"><emu-nt>AmbientClassBodyElement</emu-nt></emu-rhs>
<emu-rhs a="17580f0a">
<emu-nt>AmbientClassBodyElements</emu-nt>
<emu-nt>AmbientClassBodyElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AmbientClassBodyElement">
<emu-rhs a="ebca2f4e"><emu-nt>AmbientConstructorDeclaration</emu-nt></emu-rhs>
<emu-rhs a="72bd6ea4"><emu-nt>AmbientPropertyMemberDeclaration</emu-nt></emu-rhs>
<emu-rhs a="0dd6b549"><emu-nt>IndexSignature</emu-nt></emu-rhs>
</emu-production>
<emu-production name="AmbientConstructorDeclaration">
<emu-rhs a="bc3a462d">
<emu-t>constructor</emu-t>
<emu-t>(</emu-t>
<emu-nt optional>ParameterList</emu-nt>
<emu-t>)</emu-t>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientPropertyMemberDeclaration">
<emu-rhs a="e222cf95">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-nt optional>TypeAnnotation</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
<emu-rhs a="038c8b1f">
<emu-nt optional>AccessibilityModifier</emu-nt>
<emu-t optional>static</emu-t>
<emu-nt>PropertyName</emu-nt>
<emu-nt>CallSignature</emu-nt>
<emu-t>;</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientEnumDeclaration">
<emu-rhs a="fa872359"><emu-nt>EnumDeclaration</emu-nt></emu-rhs>
</emu-production>
<emu-production name="AmbientModuleDeclaration">
<emu-rhs a="eacfc5ab">
<emu-t>module</emu-t>
<emu-nt>IdentifierPath</emu-nt>
<emu-t>{</emu-t>
<emu-nt>AmbientModuleBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientModuleBody">
<emu-rhs a="0199bc92"><emu-nt optional>AmbientModuleElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="AmbientModuleElements">
<emu-rhs a="6ae52e7f"><emu-nt>AmbientModuleElement</emu-nt></emu-rhs>
<emu-rhs a="f4bb9316">
<emu-nt>AmbientModuleElements</emu-nt>
<emu-nt>AmbientModuleElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AmbientModuleElement">
<emu-rhs a="bc5c0551">
<emu-t optional>export</emu-t>
<emu-nt>AmbientVariableDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="b4c71f06">
<emu-t optional>export</emu-t>
<emu-nt>AmbientFunctionDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="be77c07f">
<emu-t optional>export</emu-t>
<emu-nt>AmbientClassDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="fa4fbeee">
<emu-t optional>export</emu-t>
<emu-nt>InterfaceDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="75143f3f">
<emu-t optional>export</emu-t>
<emu-nt>AmbientEnumDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="4429ad19">
<emu-t optional>export</emu-t>
<emu-nt>AmbientModuleDeclaration</emu-nt>
</emu-rhs>
<emu-rhs a="d5fe2535">
<emu-t optional>export</emu-t>
<emu-nt>ImportDeclaration</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AmbientExternalModuleDeclaration">
<emu-rhs a="732b3abf">
<emu-t>declare</emu-t>
<emu-t>module</emu-t>
<emu-nt>StringLiteral</emu-nt>
<emu-t>{</emu-t>
<emu-nt>AmbientExternalModuleBody</emu-nt>
<emu-t>}</emu-t>
</emu-rhs>
</emu-production>
<emu-production name="AmbientExternalModuleBody">
<emu-rhs a="3ae25d56"><emu-nt optional>AmbientExternalModuleElements</emu-nt></emu-rhs>
</emu-production>
<emu-production name="AmbientExternalModuleElements">
<emu-rhs a="11089657"><emu-nt>AmbientExternalModuleElement</emu-nt></emu-rhs>
<emu-rhs a="e97b683d">
<emu-nt>AmbientExternalModuleElements</emu-nt>
<emu-nt>AmbientExternalModuleElement</emu-nt>
</emu-rhs>
</emu-production>
<emu-production name="AmbientExternalModuleElement">
<emu-rhs a="6ae52e7f"><emu-nt>AmbientModuleElement</emu-nt></emu-rhs>
<emu-rhs a="d0c90aa3"><emu-nt>ExportAssignment</emu-nt></emu-rhs>
<emu-rhs a="a24c5f54">
<emu-t optional>export</emu-t>
<emu-nt>ExternalImportDeclaration</emu-nt>
</emu-rhs>
</emu-production>
|
DanielRosenwasser/grammarkdown
|
tests/baselines/reference/[ECMarkup]typescript.grammar.emu.html
|
HTML
|
apache-2.0
| 40,759
|
$packageName = 'awscli'
$installerType = 'msi'
$silentArgs = '/quiet /qn /norestart'
$url = 'https://s3.amazonaws.com/aws-cli/AWSCLI32-1.14.35.msi'
$checksum = 'ae96bbfc750a124e9a16da3ca856b5395a5c53614989925164c277efe2c836d2'
$checksumType = 'sha256'
$url64 = 'https://s3.amazonaws.com/aws-cli/AWSCLI64-1.14.35.msi'
$checksum64 = '376957d0bdf18a6164cddbe4603461f64f73fb3e51f308c382f618c7613dd2d5'
$checksumType64 = 'sha256'
$validExitCodes = @(0)
Install-ChocolateyPackage -PackageName "$packageName" `
-FileType "$installerType" `
-SilentArgs "$silentArgs" `
-Url "$url" `
-Url64bit "$url64" `
-ValidExitCodes $validExitCodes `
-Checksum "$checksum" `
-ChecksumType "$checksumType" `
-Checksum64 "$checksum64" `
-ChecksumType64 "$checksumType64"
|
dtgm/chocolatey-packages
|
automatic/_output/awscli/1.14.35/tools/chocolateyInstall.ps1
|
PowerShell
|
apache-2.0
| 982
|
<!--
@license Apache-2.0
Copyright (c) 2018 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.
-->
# Epsilon
> Difference between one and the smallest value greater than one that can be represented as a [half-precision floating-point number][half-precision-floating-point-format].
<section class="intro">
[Epsilon][machine-epsilon] is defined as
<!-- <equation class="equation" label="eq:epsilon_float16" align="center" raw="\epsilon = b^{-(p-1)}" alt="Epsilon for a half-precision floating-point number."> -->
<div class="equation" align="center" data-raw-text="\epsilon = b^{-(p-1)}" data-equation="eq:epsilon_float16">
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@5d87cc7cb2c58aeb732872f89562d2c89571cc8a/lib/node_modules/@stdlib/constants/float16/eps/docs/img/equation_epsilon_float16.svg" alt="Epsilon for a half-precision floating-point number.">
<br>
</div>
<!-- </equation> -->
where `b` is the radix (base) and `p` is the precision (number of radix bits in the significand). For [half-precision floating-point numbers][half-precision-floating-point-format], `b` is `2` and `p` is `11`.
</section>
<!-- /.intro -->
<section class="usage">
## Usage
```javascript
var FLOAT16_EPSILON = require( '@stdlib/constants/float16/eps' );
```
#### FLOAT16_EPSILON
Difference between one and the smallest value greater than one that can be represented as a [half-precision floating-point number][half-precision-floating-point-format].
```javascript
var bool = ( FLOAT16_EPSILON === 0.0009765625 );
// returns true
```
</section>
<!-- /.usage -->
<section class="examples">
## Examples
<!-- eslint no-undef: "error" -->
```javascript
var abs = require( '@stdlib/math/base/special/abs' );
var maxabs = require( '@stdlib/math/base/special/maxabs' );
var randu = require( '@stdlib/random/base/randu' );
var FLOAT16_EPSILON = require( '@stdlib/constants/float16/eps' );
var bool;
var a;
var b;
var i;
function isApprox( a, b ) {
var delta;
var tol;
delta = abs( a - b );
tol = FLOAT16_EPSILON * maxabs( a, b );
return ( delta <= tol );
}
for ( i = 0; i < 100; i++ ) {
a = randu() * 10.0;
b = a + (randu()*2.0e-3) - 1.0e-3;
bool = isApprox( a, b );
console.log( '%d %s approximately equal to %d', a, ( bool ) ? 'is' : 'is not', b );
}
```
</section>
<!-- /.examples -->
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
<section class="related">
* * *
## See Also
- <span class="package-name">[`@stdlib/constants/float32/eps`][@stdlib/constants/float32/eps]</span><span class="delimiter">: </span><span class="description">difference between one and the smallest value greater than one that can be represented as a single-precision floating-point number.</span>
- <span class="package-name">[`@stdlib/constants/float64/eps`][@stdlib/constants/float64/eps]</span><span class="delimiter">: </span><span class="description">difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number.</span>
</section>
<!-- /.related -->
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
<section class="links">
[half-precision-floating-point-format]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
[machine-epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
<!-- <related-links> -->
[@stdlib/constants/float32/eps]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/constants/float32/eps
[@stdlib/constants/float64/eps]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/constants/float64/eps
<!-- </related-links> -->
</section>
<!-- /.links -->
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/constants/float16/eps/README.md
|
Markdown
|
apache-2.0
| 4,317
|
<?php
/**
* THE CODE IN THIS FILE WAS GENERATED FROM THE EBAY WSDL USING THE PROJECT:
*
* https://github.com/davidtsadler/ebay-api-sdk-php
*
* Copyright 2014 David T. Sadler
*
* 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.
*/
namespace DTS\eBaySDK\ResolutionCaseManagement\Types;
/**
*
* @property string $CaseGlobalId
* @property string $CaseId
* @property string $CaseStatus
* @property \DTS\eBaySDK\ResolutionCaseManagement\Enums\CaseType $CaseType
* @property \DateTime $CreationDate
* @property string $ExternalUserData
* @property string $ItemId
* @property \DTS\eBaySDK\ResolutionCaseManagement\Enums\NotificationEventNameType $NotificationEventName
* @property string $OtherPartyId
* @property \DTS\eBaySDK\ResolutionCaseManagement\Enums\CaseUserRoleType $OtherPartyRole
* @property string $RecipientUserID
* @property string $TransactionId
*/
class NotificationEventType extends \DTS\eBaySDK\Types\BaseType
{
/**
* @var array Properties belonging to objects of this class.
*/
private static $propertyTypes = array(
'CaseGlobalId' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'CaseGlobalId'
),
'CaseId' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'CaseId'
),
'CaseStatus' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'CaseStatus'
),
'CaseType' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'CaseType'
),
'CreationDate' => array(
'type' => 'DateTime',
'unbound' => false,
'attribute' => false,
'elementName' => 'CreationDate'
),
'ExternalUserData' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'ExternalUserData'
),
'ItemId' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'ItemId'
),
'NotificationEventName' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'NotificationEventName'
),
'OtherPartyId' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'OtherPartyId'
),
'OtherPartyRole' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'OtherPartyRole'
),
'RecipientUserID' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'RecipientUserID'
),
'TransactionId' => array(
'type' => 'string',
'unbound' => false,
'attribute' => false,
'elementName' => 'TransactionId'
)
);
/**
* @param array $values Optional properties and values to assign to the object.
*/
public function __construct(array $values = array())
{
list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);
parent::__construct($parentValues);
if (!array_key_exists(__CLASS__, self::$properties)) {
self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
}
if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
self::$xmlNamespaces[__CLASS__] = 'http://www.ebay.com/marketplace/resolution/v1/services';
}
$this->setValues(__CLASS__, $childValues);
}
}
|
davidtsadler/ebay-sdk-resolution-case-management
|
src/DTS/eBaySDK/ResolutionCaseManagement/Types/NotificationEventType.php
|
PHP
|
apache-2.0
| 4,550
|
package com.yems.painter.control;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.util.Log;
import android.view.SurfaceHolder;
import com.yems.painter.common.Commons;
import com.yems.painter.entity.BrushPreset;
import com.yems.painter.entity.UndoState;
import com.yems.painter.serializable.SerializablePaint;
import com.yems.painter.serializable.SerializablePath;
import com.yems.painter.serializable.ShapeRepositories;
/**
* @description: ¸ºÔð»°å»æÖƵÄÏß³Ì
* @date: 2015-3-11 ÏÂÎç4:47:19
* @author: yems
*/
public class PainterThreadControl extends Thread {
private String TAG = "PainterThread";
/** ¿ØÖÆsurfaceView½çÃæµÄÏÔʾ */
private SurfaceHolder mHolder;
/** ×Ô¶¨Ò廲¼ÊµÀý */
PainterCanvasControl mPainterCanvas;
/** »±ÊʵÀý¶ÔÏó */
public Paint mBrush;
/** »±Ê³ß´ç */
private float mBrushSize;
/** ¼Ç¼×îºó»±ÊXÖáλÖõ㣬ÓÃÀ´Ïû³ý¾â³Ý */
private int mLastBrushPointX;
/** ¼Ç¼×îºó»±ÊYÖáλÖõ㣬ÓÃÀ´Ïû³ý¾â³Ý */
private int mLastBrushPointY;
/** »²¼µÄ±³¾°É« */
private int mCanvasBgColor;
/** »æÖÆÍ¼Ðεϲ¼ */
private Canvas mCanvas;
/** ÓÃÓÚ»º´æ»²¼ÉÏ»æÖƵÄͼÐÎ */
private Bitmap mBitmap;
/** ±êʶµ±Ç°»æÖÆÏß³ÌÊÇ·ñ´¦ÓÚ¼¤»î״̬£¬tureÊÇ£»false·ñ */
private boolean mIsActive;
/** »±ÊµÄÔËÐÐ״̬£¨ÐÝÃß¡¢×¼±¸¡¢ÉèÖã© */
private int mStatus;
/** ³·ÏúͼÐβÙ×÷µÄ¶ÔÏó */
private UndoState mState;
/**
* @param surfaceHolder
* @param painterCanvas
*/
public PainterThreadControl(SurfaceHolder surfaceHolder,
PainterCanvasControl painterCanvas) {
// base data
mHolder = surfaceHolder;
this.mPainterCanvas = painterCanvas;
// defaults brush settings
mBrushSize = 2;
mBrush = new Paint();
mBrush.setAntiAlias(true);
mBrush.setColor(Color.rgb(0, 0, 0));
mBrush.setStrokeWidth(mBrushSize);
mBrush.setStrokeCap(Cap.ROUND);
Commons.currentColor = Color.rgb(0, 0, 0);
Commons.currentSize = 2;
// default canvas settings
mCanvasBgColor = Color.WHITE;
// set negative coordinates for reset last point
mLastBrushPointX = -1;
mLastBrushPointY = -1;
}
@Override
public void run() {
waitForBitmap();
while (isRun()) {
Canvas canvas = null;
try {
canvas = mHolder.lockCanvas();
synchronized (mHolder) {
switch (mStatus) {
case Commons.READY: {
if (canvas != null) {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
break;
}
case Commons.SETUP: {
if (canvas != null) {
canvas.drawColor(mCanvasBgColor);
canvas.drawLine(50,
(mBitmap.getHeight() / 100) * 35,
mBitmap.getWidth() - 50,
(mBitmap.getHeight() / 100) * 35, mBrush);
}
break;
}
}
}
} finally {
if (canvas != null) {
mHolder.unlockCanvasAndPost(canvas);
}
if (isFreeze()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* @return
* @description: »ñÈ¡µ±Ç°»±Ê
* @date: 2015-3-16 ÏÂÎç2:11:47
* @author: yems
*/
public Paint getmBrush() {
return mBrush;
}
/**
* @param bitmap
* Òª»¹Ôµ½»°åÉϵÄͼƬ
* @param matrix
* Я´ø×ÅbitmapÐýתµÄ½Ç¶ÈÖµ
* @description: »¹ÔÖ¸¶¨µÄbitmapͼƬµ½»°åÉÏ
* @date: 2015-3-16 ÏÂÎç2:12:02
* @author: yems
*/
public void restoreBitmap(Bitmap bitmap, Matrix matrix) {
mCanvas.drawBitmap(bitmap, matrix, new Paint(Paint.FILTER_BITMAP_FLAG));
}
/**
* @param preset
* @description: µ±»±ÊµÄÑÕÉ«¡¢³ß´ç¸Ä±äʱµ÷Óøú¯Êý
* @date: 2015-3-16 ÏÂÎç2:15:14
* @author: yems
*/
public void setPreset(BrushPreset preset) {
mBrush.setColor(preset.currentColor);
mBrushSize = preset.currentSize;
mBrush.setStrokeWidth(mBrushSize);
}
/**
*
* @description: ¿ªÊ¼»æÖÆÇ°£¬Çå³ýλÖõãµÄ±ê¼ÇÖµ
* @date: 2015-3-16 ÏÂÎç2:15:58
* @author: yems
*/
public void clearBrushPoint() {
mLastBrushPointX = -1;
mLastBrushPointY = -1;
}
/**
* @param x
* xÖá×ø±êÖµ
* @param y
* yÖá×ø±êÖµ
* @description: »æÖÆÍ¼ÐÎ
* @date: 2015-3-12 ÉÏÎç11:17:26
* @author£º yems
*/
public void draw(int x, int y) {
Log.i("paths", "mCanvas---" + mCanvas + ",mBrush--" + mBrush);
if (mLastBrushPointX > 0) {
if (mLastBrushPointX - x == 0 && mLastBrushPointY - y == 0) {
return;
}
if (mCanvas == null) {
// µÚÒ»´Î½øÈëAPP£¬ÓÉÓÚϵͳSurface´´½¨µÄÑÓʱÐÔ£¬´ËʱmCanvas»¹Î´ÊµÀý»¯Íê³É£¬·þÎñ¶Ë·¢Ë͹ýÀ´µÄÊý¾Ý²»ÄÜÂíÉÏ»æÖÆ
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mCanvas.drawLine(x, y, mLastBrushPointX, mLastBrushPointY,
mBrush);
} else {
mCanvas.drawLine(x, y, mLastBrushPointX, mLastBrushPointY,
mBrush);
}
} else {
if (mCanvas == null) {
// µÚÒ»´Î½øÈëAPP£¬ÓÉÓÚϵͳSurface´´½¨µÄÑÓʱÐÔ£¬´ËʱmCanvas»¹Î´ÊµÀý»¯Íê³É£¬·þÎñ¶Ë·¢Ë͹ýÀ´µÄÊý¾Ý²»ÄÜÂíÉÏ»æÖÆ
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mCanvas.drawCircle(x, y, mBrush.getStrokeWidth() * .5f, mBrush);
} else {
mCanvas.drawCircle(x, y, mBrush.getStrokeWidth() * .5f, mBrush);
}
}
mLastBrushPointX = x;
mLastBrushPointY = y;
}
/**
* @param bitmap
* Òª¼ÓÔØµÄ±³¾°Í¼
* @param clear
* true ±íʾÏÈÇå³ý»°åÔÚ¼ÓÔØ±³¾°Í¼£¬false±íʾֱ½Ó¼ÓÔØ±³¾°Í¼
* @description: ÉèÖõ±Ç°»°åµÄ±³¾°
* @date: 2015-3-16 ÏÂÎç2:19:11
* @author: yems
*/
public void setBitmap(Bitmap bitmap, boolean clear) {
mBitmap = bitmap;
if (clear) {
mBitmap.eraseColor(mCanvasBgColor);
}
mCanvas = new Canvas(mBitmap);
}
/**
*
* @description: Çå³ý»°åËùÓÐͼÐÎÊý¾Ý
* @date: 2015-3-16 ÏÂÎç2:19:25
* @author: yems
*/
public void clearBitmap() {
mBitmap.eraseColor(mCanvasBgColor);
if (ShapeRepositories.getInstance().getUndoCaches().size() != 0) {
ShapeRepositories.getInstance().getUndoCaches().clear();
}
Commons.lastLocalPath = null;
Commons.lastRemotePath = null;
}
/**
* @return
* @description: »ñÈ¡µ±Ç°»æÖƵÄͼÐÎ
* @date: 2015-3-16 ÏÂÎç2:19:48
* @author: yems
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
*
* @description: ±íʾ¿ªÆô»æÖÆÏß³Ì
* @date: 2015-3-16 ÏÂÎç2:23:24
* @author: yems
*/
public void on() {
mIsActive = true;
}
/**
*
* @description: ±íʾ¹Ø±Õ»æÖÆÏß³Ì
* @date: 2015-3-16 ÏÂÎç2:23:42
* @author: yems
*/
public void off() {
mIsActive = false;
}
/**
*
* @description: ±íʾÐÝÃߣ¨ÔÝÍ££©»æÖÆÏß³Ì
* @date: 2015-3-16 ÏÂÎç2:24:12
* @author: yems
*/
public void freeze() {
mStatus = Commons.SLEEP;
}
/**
*
* @description: ±íʾ»æÖÆÏß³ÌÒѾ׼±¸ºÃ£¬¿ÉÒÔ»æÖÆÁË
* @date: 2015-3-16 ÏÂÎç2:24:29
* @author: yems
*/
public void activate() {
mStatus = Commons.READY;
}
/**
*
* @description: »°å´¦ÓÚÉèÖû±Ê²ÎÊýµÄ״̬
* @date: 2015-3-16 ÏÂÎç2:25:26
* @author: yems
*/
public void setup() {
mStatus = Commons.SETUP;
}
/**
* @return
* @description: Åжϻ°åÊÇ·ñ´¦ÓÚ¶³½á£¨»æÖÆÏß³ÌÐÝÃߣ©µÄ״̬
* @date: 2015-3-16 ÏÂÎç2:26:08
* @author: yems
*/
public boolean isFreeze() {
return (mStatus == Commons.SLEEP);
}
/**
* @return
* @description: Åжϻ°åÊÇ·ñ´¦ÓÚÉèÖû±Ê²ÎÊýµÄ״̬
* @date: 2015-3-16 ÏÂÎç2:27:31
* @author: yems
*/
public boolean isSetup() {
return (mStatus == Commons.SETUP);
}
/**
* @return
* @description: Åжϻ°åÊÇ·ñ´¦ÓÚ×¼±¸ºÃ»æÖƵÄ״̬
* @date: 2015-3-16 ÏÂÎç2:27:34
* @author: yems
*/
public boolean isReady() {
return (mStatus == Commons.READY);
}
/**
* @return
* @description: ÅжϻæÖÆÏß³ÌÊÇ·ñ´¦ÓÚÆô¶¯µÄ״̬
* @date: 2015-3-16 ÏÂÎç2:27:36
* @author: yems
*/
public boolean isRun() {
return mIsActive;
}
/**
*
* @description: ³·Ïú²Ù×÷£¨»Ö¸´ÉÏÒ»´ÎµÄͼÐÎÊý¾Ý£©
* @date: 2015-3-12 ÏÂÎç12:53:39
* @author£º yems
*/
public void undo() {
int undoSize = ShapeRepositories.getInstance().getUndoCaches().size();
if (undoSize != 0) {
undoRepaint();
// »Ö¸´Ò»´ÎÀúÊ·Êý¾Ý£¬¶ÔÓ¦¼¯ºÏÀï±£´æµÄÊý¾Ý¾ÍÒªÒÆ³ýµô£¬±ÜÃâÏ´ÎÖ´Ðг·Ïú²Ù×÷ʱ£¬ÓÖ³öÏÖ¸ÃͼÐÎ
ShapeRepositories.getInstance().getUndoCaches()
.remove(undoSize - 1);
} else {
mBitmap.eraseColor(mCanvasBgColor);
mPainterCanvas.changed(false);
Commons.lastLocalPath = null;
Commons.lastRemotePath = null;
}
}
/**
*
* @description: ³·Ïú²Ù×÷ʱ£¬ÖØ»æÖÆÍ¼ÐÎ
* @date: 2015-3-12 ÏÂÎç4:44:39
* @author£º yems
*/
private void undoRepaint() {
mBitmap.eraseColor(mCanvasBgColor);
repaintAllShapes(ShapeRepositories.getInstance().getUndoCaches());
}
/**
* @return
* @description: »ñÈ¡»²¼µÄµ±Ç°±³¾°É«
* @date: 2015-3-16 ÏÂÎç2:32:51
* @author: yems
*/
public int getBackgroundColor() {
return mCanvasBgColor;
}
/**
* @param state
* @description: ÉèÖó·ÏúͼÐβÙ×÷µÄ¶ÔÏó
* @date: 2015-3-16 ÏÂÎç2:33:20
* @author: yems
*/
public void setState(UndoState state) {
this.mState = state;
}
/**
*
* @description: µÈ´ý»²¼±³¾°Í¼ÊµÀýµÄ´´½¨
* @date: 2015-3-16 ÏÂÎç2:35:01
* @author: yems
*/
private void waitForBitmap() {
while (mBitmap == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
*
* @description: Èç¹û¿Í»§¶ËÊǵÚÒ»´ÎÁ¬½Óµ½·þÎñ¶Ë£¬Ôò»æÖÆÈ«²¿Í¼ÐΣ»·ñÔòÖ»»æÖÆ×îºóÒ»¸ö
* @date: 2015-3-12 ÏÂÎç4:10:24
* @author£º yems
*/
public void repaintNewShape(List<SerializablePath> paths) {
int size = paths.size();
clearBrushPoint();
// »ñÈ¡¼¯ºÏÖÐ×îºóÒ»¸öͼÐÎÊý¾Ý£¨·þÎñ¶Ë´«¹ýÀ´µÄ×îÐÂͼÐÎÊý¾Ý£©
SerializablePath newSerializablePath = paths.get(size - 1);
float srcScreenWidth = newSerializablePath.getScreenWidth();
float srcScreenHeight = newSerializablePath.getScreenHeight();
SerializablePaint serializablePaint = newSerializablePath
.getSerializablePaint();
updatePaintParams(serializablePaint);
// ÔÚÆÁÄ»ÏñËØÏàͬµÄÉ豸ÉÏ»æÍ¼£¬²»ÓÃת»»×ø±êÖµ
if (checkScreenDisplay(srcScreenWidth, srcScreenHeight)) {
int pointCount = newSerializablePath.points.size(); // ÿһÌõ·¾¶µÄ×é³ÉµÄµãÊý
for (int j = 0; j < pointCount; j++) {
int x = (int) newSerializablePath.points.get(j).getX();
int y = (int) newSerializablePath.points.get(j).getY();
draw(x, y);
}
} else {
// ²»Í¬ÏñËØµÄÉ豸ÉÏ»æÍ¼£¬ÐèҪת»»×ø±êÖµ
int pointCount = newSerializablePath.points.size(); // ÿһÌõ·¾¶µÄ×é³ÉµÄµãÊý
for (int j = 0; j < pointCount; j++) {
int x = (int) newSerializablePath.points.get(j).getX();
int y = (int) newSerializablePath.points.get(j).getY();
draw((int) (x * (Commons.CURRENT_SCREEN_WIDTH / srcScreenWidth)),
(int) (y * (Commons.CURRENT_SCREEN_HEIGHT / srcScreenHeight)));
}
}
clearBrushPoint();
resetColorAndSize();
}
/**
* ÖØ»æÖÆËùÓеÄͼÐÎÊý¾Ý£¨µ±ÓÐÒ»¸öеĿͻ§¶ËºóÐø½ÓÈëͨµÀʱ£¬·þÎñ¶ËÔÓеÄͼÐÎÊý¾ÝÐèÒªÒ»´ÎÐÔÖØ»æÖƵ½¸Ãпͻ§¶Ë£©
*/
public void repaintAllShapes(List<SerializablePath> paths) {
// List<SerializablePath> paths = MetadataRepositories.getInstance()
// .getBufferShapes();
int size = paths.size();
Log.i("paths", "ÖØ»æÖÆËùÓеÄͼÐÎÊý¾Ý£¬Í¼ÐÎÊýĿΪ---" + size);
for (int i = 0; i < paths.size(); i++) {
clearBrushPoint();
// ±éÀú»ñÈ¡¼¯ºÏÖÐÿһ¸öͼÐÎÊý¾Ý£¨·þÎñ¶Ë´«¹ýÀ´µÄËùÓÐͼÐÎÊý¾Ý£©
SerializablePath serializablePath = paths.get(i);
float srcScreenWidth = serializablePath.getScreenWidth();
float srcScreenHeight = serializablePath.getScreenHeight();
SerializablePaint serializablePaint = serializablePath
.getSerializablePaint();
updatePaintParams(serializablePaint);
// ÔÚÆÁÄ»·Ö±æÂÊÏàͬµÄÉ豸ÉÏ»æÍ¼£¬²»ÓÃת»»×ø±êÖµ
if (checkScreenDisplay(srcScreenWidth, srcScreenHeight)) {
int pointCount = serializablePath.points.size(); // ÿһÌõ·¾¶µÄ×é³ÉµÄµãÊý
for (int j = 0; j < pointCount; j++) {
int x = (int) serializablePath.points.get(j).getX();
int y = (int) serializablePath.points.get(j).getY();
draw(x, y);
}
} else {
// ²»Í¬ÏñËØµÄÉ豸ÉÏ»æÍ¼£¬ÐèҪת»»×ø±êÖµ
int pointCount = serializablePath.points.size(); // ÿһÌõ·¾¶µÄ×é³ÉµÄµãÊý
for (int j = 0; j < pointCount; j++) {
int x = (int) serializablePath.points.get(j).getX();
int y = (int) serializablePath.points.get(j).getY();
draw((int) (x * (Commons.CURRENT_SCREEN_WIDTH / srcScreenWidth)),
(int) (y * (Commons.CURRENT_SCREEN_HEIGHT / srcScreenHeight)));
}
}
clearBrushPoint();
resetColorAndSize();
}
}
/**
* ¼ì²âÉ豸¼äµÄÆÁÄ»·Ö±æÂÊÊÇ·ñÏàͬ
*
* @param srcScreenWidth
* @param srcScreenHeight
* @return
*/
private boolean checkScreenDisplay(float srcScreenWidth,
float srcScreenHeight) {
return srcScreenWidth == Commons.CURRENT_SCREEN_WIDTH
&& srcScreenHeight == Commons.CURRENT_SCREEN_HEIGHT;
}
private void resetColorAndSize() {
mBrush.setStrokeWidth(Commons.currentSize);
mBrush.setColor(Commons.currentColor);
}
/**
* @param serializablePaint
* @description: ¸üл±ÊµÄ²ÎÊý£¨ÑÕÉ«¡¢³ß´ç£©
* @date: 2015-3-16 ÏÂÎç2:38:05
* @author: yems
*/
private void updatePaintParams(SerializablePaint serializablePaint) {
// ¼Ç¼µ±Ç°É豸»±ÊµÄ²ÎÊýÖµ£¬ÔÚ¶ą̀É豸¼ä
Commons.currentColor = mBrush.getColor();
Commons.currentSize = mBrush.getStrokeWidth();
mBrush.setStrokeWidth(serializablePaint.getSize());
mBrush.setColor(serializablePaint.getColor());
}
}
|
JAYAndroid/whiteboard
|
client/src/com/yems/painter/control/PainterThreadControl.java
|
Java
|
apache-2.0
| 13,389
|
/**
* 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.
*/
namespace FluentCassandra.Thrift.Protocol
{
internal static class TBase64Utils
{
internal const string ENCODE_TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
internal static void encode(byte[] src, int srcOff, int len, byte[] dst,
int dstOff)
{
dst[dstOff] = (byte)ENCODE_TABLE[(src[srcOff] >> 2) & 0x3F];
if (len == 3)
{
dst[dstOff + 1] =
(byte)ENCODE_TABLE[
((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)];
dst[dstOff + 2] =
(byte)ENCODE_TABLE[
((src[srcOff + 1] << 2) & 0x3C) | ((src[srcOff + 2] >> 6) & 0x03)];
dst[dstOff + 3] =
(byte)ENCODE_TABLE[src[srcOff + 2] & 0x3F];
}
else if (len == 2)
{
dst[dstOff + 1] =
(byte)ENCODE_TABLE[
((src[srcOff] << 4) & 0x30) | ((src[srcOff + 1] >> 4) & 0x0F)];
dst[dstOff + 2] =
(byte)ENCODE_TABLE[(src[srcOff + 1] << 2) & 0x3C];
}
else
{ // len == 1) {
dst[dstOff + 1] =
(byte)ENCODE_TABLE[(src[srcOff] << 4) & 0x30];
}
}
private static int[] DECODE_TABLE = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
};
internal static void decode(byte[] src, int srcOff, int len, byte[] dst,
int dstOff)
{
dst[dstOff] = (byte)
((DECODE_TABLE[src[srcOff] & 0x0FF] << 2) |
(DECODE_TABLE[src[srcOff + 1] & 0x0FF] >> 4));
if (len > 2)
{
dst[dstOff + 1] = (byte)
(((DECODE_TABLE[src[srcOff + 1] & 0x0FF] << 4) & 0xF0) |
(DECODE_TABLE[src[srcOff + 2] & 0x0FF] >> 2));
if (len > 3)
{
dst[dstOff + 2] = (byte)
(((DECODE_TABLE[src[srcOff + 2] & 0x0FF] << 6) & 0xC0) |
DECODE_TABLE[src[srcOff + 3] & 0x0FF]);
}
}
}
}
}
|
fluentcassandra/fluentcassandra
|
src/Thrift/Protocol/TBase64Utils.cs
|
C#
|
apache-2.0
| 3,287
|
/*
Copyright 2015 The QingYuan Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package fields implements a simple field system, parsing and matching
// selectors with sets of fields.
package fields
|
qingyuancloud/qingyuan
|
pkg/fields/doc.go
|
GO
|
apache-2.0
| 711
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "bgp/peer_close_manager.h"
#include <boost/foreach.hpp>
#include <list>
#include "base/task_annotations.h"
#include "base/timer.h"
#include "bgp/bgp_log.h"
#include "bgp/bgp_membership.h"
#include "bgp/bgp_peer_types.h"
#include "bgp/bgp_route.h"
#include "bgp/bgp_server.h"
#include "bgp/routing-instance/routing_instance.h"
#include "net/community_type.h"
#define PEER_CLOSE_MANAGER_LOG(msg) \
BGP_LOG_PEER(Event, peer_close_->peer(), SandeshLevel::SYS_INFO, \
BGP_LOG_FLAG_ALL, BGP_PEER_DIR_NA, \
"PeerCloseManager: State " << GetStateName(state_) << \
", MembershipState: " << GetMembershipStateName(membership_state_) << \
", MembershipReqPending: " << membership_req_pending_ << \
", CloseAgain?: " << (close_again_ ? "Yes" : "No") << ": " << msg);
#define PEER_CLOSE_MANAGER_TABLE_LOG(msg) \
BGP_LOG_PEER_TABLE(peer_close_->peer(), SandeshLevel::SYS_INFO, \
BGP_LOG_FLAG_ALL, table, \
"PeerCloseManager: State " << GetStateName(state_) << \
", MembershipState: " << GetMembershipStateName(membership_state_) << \
", MembershipReqPending: " << membership_req_pending_ << \
", CloseAgain?: " << (close_again_ ? "Yes" : "No") << ": " << msg);
#define MOVE_TO_STATE(state) \
do { \
assert(state_ != state); \
PEER_CLOSE_MANAGER_LOG("Move to state " << GetStateName(state)); \
state_ = state; \
} while (false)
// Create an instance of PeerCloseManager with back reference to parent IPeer
PeerCloseManager::PeerCloseManager(IPeerClose *peer_close,
boost::asio::io_service *io_service) :
peer_close_(peer_close), stale_timer_(NULL),
event_queue_(new WorkQueue<Event *>(
TaskScheduler::GetInstance()->GetTaskId(
peer_close_->GetTaskName()),
peer_close_->GetTaskInstance(),
boost::bind(&PeerCloseManager::EventCallback, this, _1))),
state_(NONE), close_again_(false), non_graceful_(false), gr_elapsed_(0),
llgr_elapsed_(0), membership_state_(MEMBERSHIP_NONE) {
stats_.init++;
membership_req_pending_ = 0;
stale_timer_ = TimerManager::CreateTimer(*io_service,
"Graceful Restart StaleTimer");
}
// Create an instance of PeerCloseManager with back reference to parent IPeer
PeerCloseManager::PeerCloseManager(IPeerClose *peer_close) :
peer_close_(peer_close), stale_timer_(NULL),
event_queue_(new WorkQueue<Event *>(
TaskScheduler::GetInstance()->GetTaskId(
peer_close_->GetTaskName()),
peer_close_->GetTaskInstance(),
boost::bind(&PeerCloseManager::EventCallback, this, _1))),
state_(NONE), close_again_(false), non_graceful_(false), gr_elapsed_(0),
llgr_elapsed_(0), membership_state_(MEMBERSHIP_NONE) {
stats_.init++;
membership_req_pending_ = 0;
if (peer_close->peer() && peer_close->peer()->server()) {
stale_timer_ =
TimerManager::CreateTimer(*peer_close->peer()->server()->ioservice(),
"Graceful Restart StaleTimer");
}
}
PeerCloseManager::~PeerCloseManager() {
event_queue_->Shutdown();
TimerManager::DeleteTimer(stale_timer_);
}
std::string PeerCloseManager::GetStateName(State state) const {
switch (state) {
case NONE:
return "NONE";
case GR_TIMER:
return "GR_TIMER";
case STALE:
return "STALE";
case LLGR_STALE:
return "LLGR_STALE";
case LLGR_TIMER:
return "LLGR_TIMER";
case SWEEP:
return "SWEEP";
case DELETE:
return "DELETE";
}
assert(false);
return "";
}
std::string PeerCloseManager::GetMembershipStateName(
MembershipState state) const {
switch (state) {
case MEMBERSHIP_NONE:
return "NONE";
case MEMBERSHIP_IN_USE:
return "IN_USE";
case MEMBERSHIP_IN_WAIT:
return "IN_WAIT";
}
assert(false);
return "";
}
std::string PeerCloseManager::GetEventName(EventType eventType) const {
switch (eventType) {
case EVENT_NONE:
return "NONE";
case CLOSE:
return "CLOSE";
case EOR_RECEIVED:
return "EOR_RECEIVED";
case MEMBERSHIP_REQUEST:
return "MEMBERSHIP_REQUEST";
case MEMBERSHIP_REQUEST_COMPLETE_CALLBACK:
return "MEMBERSHIP_REQUEST_COMPLETE_CALLBACK";
case TIMER_CALLBACK:
return "TIMER_CALLBACK";
}
return "";
}
void PeerCloseManager::EnqueueEvent(Event *event) {
PEER_CLOSE_MANAGER_LOG("Enqueued event " <<
GetEventName(event->event_type) <<
", non_graceful " << event->non_graceful <<
", family " << Address::FamilyToString(event->family));
event_queue_->Enqueue(event);
}
// Trigger closure of an IPeer
//
// Graceful close_state_: NONE
// RibIn Stale Marking and Ribout deletion close_state_: STALE
// StateMachine restart and GR timer start close_state_: GR_TIMER
//
// Peer IsReady() in GR timer callback (or via reception of all EoRs)
// RibIn Sweep and Ribout Generation close_state_: SWEEP
// MembershipRequestCallback close_state_: NONE
//
// Peer not IsReady() in GR timer callback
// If LLGR supported close_state_: LLGR_STALE
// RibIn Stale marking with LLGR_STALE community close_state_: LLGR_TIMER
//
// Peer not IsReady() in LLGR timer callback
// RibIn Delete close_state_: DELETE
// MembershipRequestCallback close_state_: NONE
//
// Peer IsReady() in LLGR timer callback (or via reception of all EoRs)
// RibIn Sweep close_state_: SWEEP
// MembershipRequestCallback close_state_: NONE
//
// If LLGR is not supported
// RibIn Delete close_state_: DELETE
// MembershipRequestCallback close_state_: NONE
//
// Close() call during any state other than NONE and DELETE
// Cancel GR timer and restart GR Closure all over again
//
// NonGraceful close_state_ = * (except DELETE)
// A. RibIn deletion and Ribout deletion close_state_ = DELETE
// B. MembershipRequestCallback => Peers delete/StateMachine restart
// close_state_ = NONE
//
// If Close is restarted, account for GR timer's elapsed time.
//
// Use non_graceful as true for non-graceful closure
void PeerCloseManager::Close(bool non_graceful) {
EnqueueEvent(new Event(CLOSE, non_graceful));
}
void PeerCloseManager::Close(Event *event) {
// Note down non-graceful close trigger. Once non-graceful closure is
// triggered, it should remain so until close process is complete. Further
// graceful closure calls until then should remain non-graceful.
non_graceful_ |= event->non_graceful;
CloseInternal();
}
void PeerCloseManager::CloseInternal() {
stats_.close++;
// Ignore nested closures
if (close_again_) {
PEER_CLOSE_MANAGER_LOG("Nested close calls ignored");
return;
}
switch (state_) {
case NONE:
ProcessClosure();
break;
case GR_TIMER:
PEER_CLOSE_MANAGER_LOG("Nested close: Restart GR");
close_again_ = true;
stats_.nested++;
gr_elapsed_ += stale_timer_->GetElapsedTime();
CloseComplete();
break;
case LLGR_TIMER:
PEER_CLOSE_MANAGER_LOG("Nested close: Restart LLGR");
close_again_ = true;
stats_.nested++;
llgr_elapsed_ += stale_timer_->GetElapsedTime();
CloseComplete();
break;
case STALE:
case LLGR_STALE:
case SWEEP:
case DELETE:
PEER_CLOSE_MANAGER_LOG("Nested close");
close_again_ = true;
stats_.nested++;
break;
}
}
void PeerCloseManager::ProcessEORMarkerReceived(Address::Family family) {
EnqueueEvent(new Event(EOR_RECEIVED, family));
}
void PeerCloseManager::ProcessEORMarkerReceived(Event *event) {
if ((state_ == GR_TIMER || state_ == LLGR_TIMER) && !families_.empty()) {
if (event->family == Address::UNSPEC) {
families_.clear();
} else {
families_.erase(event->family);
}
// Start the timer if all EORs have been received.
if (families_.empty())
StartRestartTimer(0);
}
}
// Process RibIn staling related activities during peer closure
// Return true if at least ome time is started, false otherwise
void PeerCloseManager::StartRestartTimer(int time) {
stale_timer_->Cancel();
PEER_CLOSE_MANAGER_LOG("GR Timer started to fire after " << time <<
" seconds");
stale_timer_->Start(time,
boost::bind(&PeerCloseManager::RestartTimerCallback, this));
}
bool PeerCloseManager::RestartTimerCallback() {
CHECK_CONCURRENCY("timer::TimerTask");
EnqueueEvent(new Event(TIMER_CALLBACK));
return false;
}
void PeerCloseManager::RestartTimerCallback(Event *event) {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
PEER_CLOSE_MANAGER_LOG("GR Timer callback started");
if (state_ != GR_TIMER && state_ != LLGR_TIMER)
return;
if (peer_close_->IsReady() && !families_.empty()) {
// Fake reception of all EORs.
for (IPeerClose::Families::iterator i = families_.begin(), next = i;
i != families_.end(); i = next) {
next++;
PEER_CLOSE_MANAGER_LOG("Simulate EoR reception for family " << *i);
peer_close_->ReceiveEndOfRIB(*i);
}
} else {
ProcessClosure();
}
}
// Route stale timer callback. If the peer has come back up, sweep routes for
// those address families that are still active. Delete the rest
void PeerCloseManager::ProcessClosure() {
// If the peer is back up and this address family is still supported,
// sweep old paths which may not have come back in the new session
switch (state_) {
case NONE:
if (non_graceful_ || !peer_close_->IsCloseGraceful()) {
MOVE_TO_STATE(DELETE);
stats_.deletes++;
} else {
MOVE_TO_STATE(STALE);
stats_.stale++;
StaleNotify();
return;
}
break;
case GR_TIMER:
if (peer_close_->IsReady()) {
MOVE_TO_STATE(SWEEP);
gr_elapsed_ = 0;
llgr_elapsed_ = 0;
stats_.sweep++;
break;
}
if (peer_close_->IsCloseLongLivedGraceful()) {
MOVE_TO_STATE(LLGR_STALE);
stats_.llgr_stale++;
peer_close_->LongLivedGracefulRestartStale();
break;
}
MOVE_TO_STATE(DELETE);
stats_.deletes++;
break;
case LLGR_TIMER:
if (peer_close_->IsReady()) {
MOVE_TO_STATE(SWEEP);
gr_elapsed_ = 0;
llgr_elapsed_ = 0;
stats_.sweep++;
break;
}
MOVE_TO_STATE(DELETE);
stats_.deletes++;
break;
case STALE:
case LLGR_STALE:
case SWEEP:
case DELETE:
assert(false);
return;
}
if (state_ == DELETE)
peer_close_->CustomClose();
MembershipRequest();
}
void PeerCloseManager::CloseComplete() {
MOVE_TO_STATE(NONE);
stale_timer_->Cancel();
families_.clear();
stats_.init++;
// Nested closures trigger fresh GR
if (close_again_) {
close_again_ = false;
CloseInternal();
}
}
bool PeerCloseManager::AssertSweepState(bool do_assert) {
bool check = (state_ == SWEEP);
if (do_assert)
assert(check);
return check;
}
bool PeerCloseManager::AssertMembershipManagerInUse(bool do_assert) {
bool check = false;
check |= (state_ == STALE || LLGR_STALE || state_ == SWEEP ||
state_ == DELETE);
check |= (membership_state_ == MEMBERSHIP_IN_USE);
check |= (membership_req_pending_ > 0);
if (do_assert)
assert(check);
return check;
}
bool PeerCloseManager::AssertMembershipState(bool do_assert) {
bool check = (membership_state_ != MEMBERSHIP_IN_USE);
if (do_assert)
assert(check);
return check;
}
bool PeerCloseManager::AssertMembershipReqCount(bool do_assert) {
bool check = !membership_req_pending_;
if (do_assert)
assert(check);
return check;
}
void PeerCloseManager::TriggerSweepStateActions() {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
if (!AssertSweepState())
return;
// Notify clients to trigger sweep as appropriate.
peer_close_->GracefulRestartSweep();
CloseComplete();
}
// Notify clients about entering Stale event.
void PeerCloseManager::StaleNotify() {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
peer_close_->GracefulRestartStale();
if (!AssertMembershipState())
return;
MembershipRequest(NULL);
}
bool PeerCloseManager::CanUseMembershipManager() const {
return peer_close_->peer()->CanUseMembershipManager();
}
void PeerCloseManager::GetRegisteredRibs(std::list<BgpTable *> *tables) {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
mgr->GetRegisteredRibs(peer_close_->peer(), tables);
}
bool PeerCloseManager::IsRegistered(BgpTable *table) const {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
return mgr->IsRegistered(peer_close_->peer(), table);
}
void PeerCloseManager::Unregister(BgpTable *table) {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
mgr->Unregister(peer_close_->peer(), table);
}
void PeerCloseManager::WalkRibIn(BgpTable *table) {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
mgr->WalkRibIn(peer_close_->peer(), table);
}
void PeerCloseManager::UnregisterRibOut(BgpTable *table) {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
mgr->UnregisterRibOut(peer_close_->peer(), table);
}
bool PeerCloseManager::IsRibInRegistered(BgpTable *table) const {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
return mgr->IsRibInRegistered(peer_close_->peer(), table);
}
void PeerCloseManager::UnregisterRibIn(BgpTable *table) {
BgpMembershipManager *mgr = peer_close_->peer()->server()->membership_mgr();
mgr->UnregisterRibIn(peer_close_->peer(), table);
}
void PeerCloseManager::MembershipRequest() {
if (!AssertMembershipState())
return;
// Pause if membership manager is not ready for usage.
if (!CanUseMembershipManager()) {
set_membership_state(MEMBERSHIP_IN_WAIT);
PEER_CLOSE_MANAGER_LOG("Wait for membership manager availability");
return;
}
set_membership_state(MEMBERSHIP_IN_USE);
EnqueueEvent(new Event(MEMBERSHIP_REQUEST));
}
void PeerCloseManager::MembershipRequest(Event *evnet) {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
set_membership_state(MEMBERSHIP_IN_USE);
if (!AssertMembershipReqCount())
return;
membership_req_pending_++;
std::list<BgpTable *> tables;
GetRegisteredRibs(&tables);
if (tables.empty()) {
assert(MembershipRequestCallback(NULL));
return;
}
// Account for extra increment above.
membership_req_pending_--;
BOOST_FOREACH(BgpTable *table, tables) {
membership_req_pending_++;
if (IsRegistered(table)) {
if (state_ == PeerCloseManager::DELETE) {
PEER_CLOSE_MANAGER_TABLE_LOG(
"MembershipManager::Unregister");
Unregister(table);
} else if (state_ == PeerCloseManager::SWEEP) {
PEER_CLOSE_MANAGER_TABLE_LOG("MembershipManager::WalkRibIn");
WalkRibIn(table);
} else {
PEER_CLOSE_MANAGER_TABLE_LOG(
"MembershipManager::UnregisterRibOut");
UnregisterRibOut(table);
}
} else {
assert(IsRibInRegistered(table));
if (state_ == PeerCloseManager::DELETE) {
PEER_CLOSE_MANAGER_TABLE_LOG(
"MembershipManager::UnregisterRibIn");
UnregisterRibIn(table);
} else {
PEER_CLOSE_MANAGER_TABLE_LOG("MembershipManager::WalkRibIn");
WalkRibIn(table);
}
}
}
}
void PeerCloseManager::MembershipRequestCallback() {
EnqueueEvent(new Event(MEMBERSHIP_REQUEST_COMPLETE_CALLBACK));
}
// Close process for this peer in terms of walking RibIns and RibOuts are
// complete. Do the final cleanups necessary and notify interested party
//
// Retrun true if we are done using membership manager, false otherwise.
bool PeerCloseManager::MembershipRequestCallback(Event *event) {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
bool result = false;
PEER_CLOSE_MANAGER_LOG("MembershipRequestCallback");
if (!AssertMembershipManagerInUse())
return result;
if (--membership_req_pending_)
return result;
// Indicate to the caller that we are done using the membership manager.
result = true;
set_membership_state(MEMBERSHIP_NONE);
if (state_ == DELETE) {
MOVE_TO_STATE(NONE);
peer_close_->Delete();
gr_elapsed_ = 0;
llgr_elapsed_ = 0;
stats_.init++;
close_again_ = false;
non_graceful_ = false;
return result;
}
// Process nested closures.
if (close_again_) {
CloseComplete();
return result;
}
// If any GR stale timer has to be launched, then to wait for some time
// hoping for the peer (and the paths) to come back up.
if (state_ == STALE) {
peer_close_->CloseComplete();
MOVE_TO_STATE(GR_TIMER);
peer_close_->GetGracefulRestartFamilies(&families_);
// Offset restart time with elapsed time during nested closures.
int time = peer_close_->GetGracefulRestartTime() * 1000;
time -= gr_elapsed_;
if (time < 0)
time = 0;
StartRestartTimer(time);
stats_.gr_timer++;
return result;
}
// From LLGR_STALE state, switch to LLGR_TIMER state. Typically this would
// be a very long timer, and we expect to receive EORs before this timer
// expires.
if (state_ == LLGR_STALE) {
MOVE_TO_STATE(LLGR_TIMER);
// Offset restart time with elapsed time during nested closures.
int time = peer_close_->GetLongLivedGracefulRestartTime() * 1000;
time -= llgr_elapsed_;
if (time < 0)
time = 0;
StartRestartTimer(time);
stats_.llgr_timer++;
return result;
}
TriggerSweepStateActions();
return result;
}
void PeerCloseManager::FillCloseInfo(BgpNeighborResp *resp) const {
PeerCloseInfo peer_close_info;
peer_close_info.state = GetStateName(state_);
peer_close_info.membership_state =
GetMembershipStateName(membership_state_);
peer_close_info.close_again = close_again_;
peer_close_info.non_graceful = non_graceful_;
peer_close_info.init = stats_.init;
peer_close_info.close = stats_.close;
peer_close_info.nested = stats_.nested;
peer_close_info.deletes = stats_.deletes;
peer_close_info.stale = stats_.stale;
peer_close_info.llgr_stale = stats_.llgr_stale;
peer_close_info.sweep = stats_.sweep;
peer_close_info.gr_timer = stats_.gr_timer;
peer_close_info.llgr_timer = stats_.llgr_timer;
resp->set_peer_close_info(peer_close_info);
}
bool PeerCloseManager::MembershipPathCallback(DBTablePartBase *root,
BgpRoute *rt, BgpPath *path) {
CHECK_CONCURRENCY("db::DBTable");
DBRequest::DBOperation oper;
BgpAttrPtr attrs;
BgpTable *table = static_cast<BgpTable *>(root->parent());
assert(table);
uint32_t stale = 0;
switch (state_) {
case NONE:
case GR_TIMER:
case LLGR_TIMER:
return false;
case SWEEP:
// Stale paths must be deleted.
if (!path->IsStale() && !path->IsLlgrStale())
return false;
path->ResetStale();
path->ResetLlgrStale();
oper = DBRequest::DB_ENTRY_DELETE;
attrs = NULL;
break;
case DELETE:
// This path must be deleted. Hence attr is not required.
oper = DBRequest::DB_ENTRY_DELETE;
attrs = NULL;
break;
case STALE:
// If path is already marked as stale, then there is no need to
// process again. This can happen if the session flips while in
// GR_TIMER state.
if (path->IsStale())
return false;
// This path must be marked for staling. Update the local
// preference and update the route accordingly.
oper = DBRequest::DB_ENTRY_ADD_CHANGE;
attrs = path->GetAttr();
stale = BgpPath::Stale;
break;
case LLGR_STALE:
// If the path has NO_LLGR community, DELETE it.
if (path->GetAttr()->community() &&
path->GetAttr()->community()->ContainsValue(
CommunityType::NoLlgr)) {
oper = DBRequest::DB_ENTRY_DELETE;
attrs = NULL;
break;
}
// If path is already marked as llgr_stale, then there is no
// need to process again. This can happen if the session flips
// while in LLGR_TIMER state.
if (path->IsLlgrStale())
return false;
attrs = path->GetAttr();
stale = BgpPath::LlgrStale;
oper = DBRequest::DB_ENTRY_ADD_CHANGE;
break;
}
// Feed the route modify/delete request to the table input process.
return table->InputCommon(root, rt, path, peer_close_->peer(), NULL, oper,
attrs, path->GetPathId(),
path->GetFlags() | stale, path->GetLabel());
}
//
// Handler for an Event.
//
bool PeerCloseManager::EventCallback(Event *event) {
CHECK_CONCURRENCY(peer_close_->GetTaskName());
bool result;
switch (event->event_type) {
case EVENT_NONE:
break;
case CLOSE:
Close(event);
break;
case EOR_RECEIVED:
ProcessEORMarkerReceived(event);
break;
case MEMBERSHIP_REQUEST:
MembershipRequest(event);
break;
case MEMBERSHIP_REQUEST_COMPLETE_CALLBACK:
result = MembershipRequestCallback(event);
// Notify clients if we are no longer using the membership mgr.
if (result)
peer_close_->MembershipRequestCallbackComplete();
break;
case TIMER_CALLBACK:
RestartTimerCallback(event);
break;
}
delete event;
return true;
}
|
tcpcloud/contrail-controller
|
src/bgp/peer_close_manager.cc
|
C++
|
apache-2.0
| 23,829
|
/*
* Copyright 2002-2019 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
*
* https://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.springframework.security.web.authentication.www;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* @author Sergey Bespalov
* @since 5.2.0
*/
@RunWith(MockitoJUnitRunner.class)
public class BasicAuthenticationConverterTests {
@Mock
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private BasicAuthenticationConverter converter;
@Before
public void setup() {
this.converter = new BasicAuthenticationConverter(this.authenticationDetailsSource);
}
@Test
public void testNormalOperation() {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
}
@Test
public void requestWhenAuthorizationSchemeInMixedCaseThenAuthenticates() {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
}
@Test
public void testWhenUnsupportedAuthorizationHeaderThenIgnored() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer someOtherToken");
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verifyZeroInteractions(this.authenticationDetailsSource);
assertThat(authentication).isNull();
}
@Test
public void testWhenInvalidBasicAuthorizationTokenThenError() {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request));
}
@Test
public void testWhenInvalidBase64ThenError() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request));
}
@Test
public void convertWhenEmptyPassword() {
String token = "rod:";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
assertThat(authentication.getCredentials()).isEqualTo("");
}
@Test
public void requestWhenEmptyBasicAuthorizationHeaderTokenThenError() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic ");
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.converter.convert(request));
}
}
|
fhanik/spring-security
|
web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverterTests.java
|
Java
|
apache-2.0
| 4,909
|
package com.gdkdemo.camera;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.buaa.network.HttpUtil;
import com.google.android.glass.media.CameraManager;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.JSONException;
import org.json.JSONObject;
public class CameraDemoActivity extends Activity
{
private final int IMAGE_CAPTURE_REQUEST_CODE = 101;
// For tap event
private GestureDetector mGestureDetector;
private String name = "";
private String birthday = "";
private String hometown ="";
private String college= "";
String APP_SDCARD_FOLDER =
Environment.getExternalStorageDirectory().getAbsolutePath();
@Override
protected void onDestroy()
{
//doUnbindService();
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d("onCreate() called.");
setContentView(R.layout.activity_start);
System.out.println("sdcard path"+APP_SDCARD_FOLDER);
// For gesture handling.
mGestureDetector = createGestureDetector(this);
// We need a real service.
// bind does not work. We need to call start() explilicitly...
// doBindService();
//doStartService();
// TBD: We need to call doStopService() when user "closes" the app....
// ...
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_CAMERA) {
// Stop the preview and release the camera.
// Execute your logic as quickly as possible
// so the capture happens quickly.
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == IMAGE_CAPTURE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if(data != null) {
Bundle extras = data.getExtras();
if(extras != null) {
// Note: Apparently there is currently a bug.
// https://developers.google.com/glass/develop/gdk/reference/com/google/android/glass/media/Camera#EXTRA_THUMBNAIL_FILE_PATH
String thumbnailFilePath = extras.getString(CameraManager.EXTRA_THUMBNAIL_FILE_PATH);
if(Log.I) Log.i("thumbnailFilePath = " + thumbnailFilePath);
String pictureFilePath = extras.getString(CameraManager.EXTRA_PICTURE_FILE_PATH);
if(Log.D) Log.d("pictureFilePath = " + pictureFilePath);
File myuploadimg = new File(thumbnailFilePath);
//System.out.println("file path"+thumbnailFilePath);
//System.out.println("file exists"+myuploadimg.exists());
Time t=new Time(); // or Time t=new Time("GMT+8"); ¼ÓÉÏTime Zone×ÊÁÏ¡£
t.setToNow();
int minute = t.minute;
int second = t.second;
//System.out.println("start upload time"+minute+"."+second);
upload(new File(thumbnailFilePath));
} else {
Log.w("The returned intent does not include extras.");
}
} else {
// Can this happen?
Log.w("Null Intent data returned.");
}
} else {
Log.i("Request failed: resultCode = " + resultCode);
}
}
// Call super?
super.onActivityResult(requestCode, resultCode, data);
}
// TBD:
// Just use context menu instead of gesture ???
// ...
@Override
public boolean onGenericMotionEvent(MotionEvent event)
{
if (mGestureDetector != null) {
return mGestureDetector.onMotionEvent(event);
}
return false;
}
private GestureDetector createGestureDetector(Context context)
{
GestureDetector gestureDetector = new GestureDetector(context);
//Create a base listener for generic gestures
gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
@Override
public boolean onGesture(Gesture gesture) {
if(Log.D) Log.d("gesture = " + gesture);
if (gesture == Gesture.TAP) {
handleGestureTap();
return true;
} else if (gesture == Gesture.TWO_TAP) {
handleGestureTwoTap();
return true;
} else if (gesture == Gesture.SWIPE_RIGHT) {
handleGestureSwipeRight();
return true;
} else if (gesture == Gesture.SWIPE_LEFT) {
handleGestureSwipeLeft();
return true;
}
return false;
}
});
return gestureDetector;
}
// Tap triggers photo taking...
private void handleGestureTap()
{
Log.d("handleGestureTap() called.");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, IMAGE_CAPTURE_REQUEST_CODE);
}
private void handleGestureTwoTap()
{
Log.d("handleGestureTwoTap() called.");
// Quit
this.finish();
}
private void handleGestureSwipeRight()
{
Log.d("handleGestureSwipeRight() called.");
}
private void handleGestureSwipeLeft()
{
Log.d("handleGestureSwipeLeft() called.");
}
public void upload(File myfile) {
RequestParams params = new RequestParams();
//params.put("person_name", trainName);
try {
System.out.println("file size"+myfile.length());
params.put("file", myfile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpUtil.post(params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonobject) {
// TODO Auto-generated method stub
super.onSuccess(jsonobject);
String statuscode = null;
try {
statuscode = jsonobject.getString("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("return json data"+jsonobject.toString());
try {
name = jsonobject.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
birthday = jsonobject.getString("birth_date");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hometown = jsonobject.getString("hometown");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
college = jsonobject.getString("college");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), PersonInfoActivity.class);
intent.putExtra("name", name);
intent.putExtra("birthday", birthday);
intent.putExtra("hometown", hometown);
intent.putExtra("college", college);
startActivity(intent);
}
public void onFailure(Throwable arg0) { // ʧ°Ü£¬µ÷ÓÃ
System.out.println("onfailure");
//status = 2;
}
public void onFinish() { // Íê³Éºóµ÷Óã¬Ê§°Ü£¬³É¹¦£¬¶¼Òªµô
System.out.println("onfinish");
}
@Override
protected void handleFailureMessage(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.handleFailureMessage(arg0, arg1);
Time t=new Time(); // or Time t=new Time("GMT+8"); ¼ÓÉÏTime Zone×ÊÁÏ¡£
t.setToNow();
int minute = t.minute;
int second = t.second;
System.out.println("end failure time"+minute+"."+second);
//status = 2;
//System.out.println("onfailuremessage" + arg0 + arg1);
String fileName = String.format("%s.html", "liuyuxiaolog");
String storepath = APP_SDCARD_FOLDER;
// System.out.println("storepath"+storepath);
try {
FileOutputStream fos = new FileOutputStream(storepath+"/"+fileName);
System.out.println("store log path "+storepath+fileName);
File tofile=new File(storepath+"/"+fileName);
System.out.println("log file exist "+tofile.exists());
FileWriter fw=new FileWriter(tofile);
BufferedWriter buffw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(buffw);
//String str="hellow world";
pw.println(arg1);
pw.close();
buffw.close();
fw.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println(e.toString());
}
};
},"/postFaceToIdentify/");
}
}
|
liuyuxiao/GoogleGlass
|
src/com/gdkdemo/camera/CameraDemoActivity.java
|
Java
|
apache-2.0
| 10,066
|
/*
* 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.nifi.admin.dao.impl;
import org.apache.nifi.admin.dao.ActionDAO;
import org.apache.nifi.admin.dao.DAOFactory;
import org.apache.nifi.admin.dao.IdpCredentialDAO;
import org.apache.nifi.admin.dao.IdpUserGroupDAO;
import org.apache.nifi.admin.dao.KeyDAO;
import java.sql.Connection;
/**
*
*/
public class DAOFactoryImpl implements DAOFactory {
private final Connection connection;
public DAOFactoryImpl(Connection connection) {
this.connection = connection;
}
@Override
public ActionDAO getActionDAO() {
return new StandardActionDAO(connection);
}
@Override
public KeyDAO getKeyDAO() {
return new StandardKeyDAO(connection);
}
@Override
public IdpCredentialDAO getIdpCredentialDAO() {
return new StandardIdpCredentialDAO(connection);
}
@Override
public IdpUserGroupDAO getIdpUserGroupDAO() {
return new StandardIdpUserGroupDAO(connection);
}
}
|
mattyb149/nifi
|
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-administration/src/main/java/org/apache/nifi/admin/dao/impl/DAOFactoryImpl.java
|
Java
|
apache-2.0
| 1,774
|
package main
import (
log "github.com/sirupsen/logrus"
"github.com/catpie/musdk-go"
"strconv"
"strings"
)
func handleLog(l string) error {
log.Info("get log: ", l)
arr := strings.Split(l, "\n")
log.Infof("len: %d ", len(arr))
// var logs []musdk.UserTrafficLog
for _, v := range arr {
s := strings.Split(v, " ")
log.Debugf("processing %s len: %d", v, len(s))
if len(s) < 8 {
continue
}
var sArr []string
for _, value := range s {
//log.Debugf("key: %d value %s",key,value)
if len(value) != 0 {
sArr = append(sArr, value)
}
}
log.Debugf("user %s traffic %s", sArr[7], sArr[4])
u, err := strconv.Atoi(sArr[7])
if err != nil {
log.Error("error on get user id ", err)
continue
}
d, err := strconv.Atoi(sArr[4])
if err != nil {
log.Error("error on get traffic ", err)
}
l := musdk.UserTrafficLog{
UserId: int64(u),
D: int64(d),
}
//logs = append(logs, l)
Queue.Append(l)
}
//log.Info("start update traffic to api", logs)
//err := client.UpdateTraffic(logs)
//if err != nil {
// log.Errorf("error on update traffic %s", err.Error())
//}
return nil
}
|
orvice/squid-log-server
|
server.go
|
GO
|
apache-2.0
| 1,138
|
<?php
/**
* Makes directory
*
* @phpstub
*
* @param string $pathname
* @param int $mode
* @param bool $recursive
* @param resource $context
*
* @return bool
*/
function mkdir($pathname, $mode = 777, $recursive = false, $context = NULL)
{
}
|
schmittjoh/php-stubs
|
res/php/filesystem/functions/mkdir.php
|
PHP
|
apache-2.0
| 252
|
# Calibrachoa sendtneriana (R.E.Fr.) J.R.Stehmann & J.Semir SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Novon 7:419. 1997
#### Original name
Petunia sendtneriana R.E.Fr.
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Calibrachoa/Calibrachoa sendtneriana/README.md
|
Markdown
|
apache-2.0
| 244
|
/**
* Copyright 2015 Adam Stroud
*
* 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 me.adamstroud.taggedstrings;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import org.xml.sax.XMLReader;
import java.util.HashMap;
import java.util.Map;
/**
* The base class for all other tag handlers.
*
* @author Adam Stroud <<a href="mailto:adam.stroud@gmail.com">adam.stroud@gmail.com</a>>
*/
public abstract class BaseTagHandler implements Html.TagHandler {
private static final String OUTER_TAG = "tagged";
private final Map<String, Object[]> resolvedTags = new HashMap<>();
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (!tag.equals(OUTER_TAG)) {
Object[] spans;
if (resolvedTags.containsKey(tag)) {
spans = resolvedTags.get(tag);
} else {
spans = getSpansForTag(tag);
resolvedTags.put(tag, spans);
}
if (spans != null) {
if (opening) {
processOpenTag(output, spans);
} else {
processCloseTag(output, spans);
}
}
}
}
/**
* Resolves the given tag into spans for the tag.
*
* @param tag The as specified in the string resource.
* @return The Array of spans to apply to the text defined by the tag.
*/
protected abstract Object[] getSpansForTag(String tag);
private void processOpenTag(Editable output, Object... spans) {
for (Object span : spans) {
int length = output.length();
output.setSpan(span, length, length, Spannable.SPAN_MARK_MARK);
}
}
private void processCloseTag(Editable output, Object... spans) {
for (Object span : spans) {
output.setSpan(span, output.getSpanStart(getLastSpanForType(output, span.getClass())), output.length(), 0);
}
}
private <T> T getLastSpanForType(Editable editable, Class<T> spanType) {
T lastSpan = null;
T[] spans = editable.getSpans(0, editable.length(), spanType);
if (spans.length > 0) {
for (int i = spans.length; i > 0; i--) {
T currentSpan = spans[i - 1];
if (editable.getSpanFlags(currentSpan) == Spannable.SPAN_MARK_MARK) {
lastSpan = currentSpan;
break;
}
}
}
return lastSpan;
}
public Spanned bindTags(String string) {
return Html.fromHtml(string, null, this);
}
}
|
adstro/tagged-strings
|
library/src/main/java/me/adamstroud/taggedstrings/BaseTagHandler.java
|
Java
|
apache-2.0
| 3,217
|
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>"stats/base/dists/lognormal/logpdf/docs/types/index.d" | stdlib</title>
<meta name="description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta name="author" content="stdlib">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- Icons -->
<link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
<link rel="manifest" href="../manifest.json">
<link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<!-- Facebook Open Graph -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="stdlib">
<meta property="og:url" content="https://stdlib.io/">
<meta property="og:title" content="A standard library for JavaScript and Node.js.">
<meta property="og:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="">
<!-- Twitter -->
<meta name="twitter:card" content="A standard library for JavaScript and Node.js.">
<meta name="twitter:site" content="@stdlibjs">
<meta name="twitter:url" content="https://stdlib.io/">
<meta name="twitter:title" content="stdlib">
<meta name="twitter:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta name="twitter:image" content="">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/theme.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title"><img src="../logo_white.svg" alt="stdlib"></a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html">"stats/base/dists/lognormal/logpdf/docs/types/index.d"</a>
</li>
</ul>
<h1>External module "stats/base/dists/lognormal/logpdf/docs/types/index.d"</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-not-exported">
<h3>Interfaces</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported"><a href="../interfaces/_stats_base_dists_lognormal_logpdf_docs_types_index_d_.logpdf.html" class="tsd-kind-icon">LogPDF</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-not-exported">
<h3>Type aliases</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-type-alias tsd-parent-kind-external-module tsd-is-not-exported"><a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html#unary" class="tsd-kind-icon">Unary</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-not-exported">
<h3>Variables</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-variable tsd-parent-kind-external-module tsd-is-not-exported"><a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html#logpdf-1" class="tsd-kind-icon">logPDF</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Type aliases</h2>
<section class="tsd-panel tsd-member tsd-kind-type-alias tsd-parent-kind-external-module tsd-is-not-exported">
<a name="unary" class="tsd-anchor"></a>
<h3>Unary</h3>
<div class="tsd-signature tsd-kind-icon">Unary<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-symbol">(</span>x<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol"> => </span><span class="tsd-signature-type">number</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/lognormal/logpdf/docs/types/index.d.ts#L27">lib/node_modules/@stdlib/stats/base/dists/lognormal/logpdf/docs/types/index.d.ts:27</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Evaluates the natural logarithm of the probability density function (logPDF) for a lognormal distribution.</p>
</div>
<dl class="tsd-comment-tags">
<dt>param</dt>
<dd><p>input value</p>
</dd>
<dt>returns</dt>
<dd><p>evaluated logPDF</p>
</dd>
</dl>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-siganture">
<ul class="tsd-signatures tsd-kind-type-literal tsd-parent-kind-type-alias tsd-is-not-exported">
<li class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">(</span>x<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>x: <span class="tsd-signature-type">number</span></h5>
</li>
</ul>
<h4 class="tsd-returns-title">Returns
<span class="tsd-signature-type">number</span>
</h4>
</li>
</ul>
</li>
</ul>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Variables</h2>
<section class="tsd-panel tsd-member tsd-kind-variable tsd-parent-kind-external-module tsd-is-not-exported">
<a name="logpdf-1" class="tsd-anchor"></a>
<h3>logPDF</h3>
<div class="tsd-signature tsd-kind-icon">logPDF<span class="tsd-signature-symbol">:</span> <a href="../interfaces/_stats_base_dists_arcsine_logpdf_docs_types_index_d_.logpdf.html" class="tsd-signature-type">LogPDF</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/lognormal/logpdf/docs/types/index.d.ts#L123">lib/node_modules/@stdlib/stats/base/dists/lognormal/logpdf/docs/types/index.d.ts:123</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Lognormal distribution natural logarithm of probability density function (logPDF).</p>
</div>
<dl class="tsd-comment-tags">
<dt>param</dt>
<dd><p>input value</p>
</dd>
<dt>param</dt>
<dd><p>location parameter</p>
</dd>
<dt>param</dt>
<dd><p>scale parameter</p>
</dd>
<dt>returns</dt>
<dd><p>evaluated logPDF</p>
</dd>
</div>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Packages</em></a>
</li>
<li class="current tsd-kind-external-module">
<a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html">"stats/base/dists/lognormal/logpdf/docs/types/index.d"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../interfaces/_stats_base_dists_lognormal_logpdf_docs_types_index_d_.logpdf.html" class="tsd-kind-icon">LogPDF</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module tsd-is-not-exported">
<a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html#unary" class="tsd-kind-icon">Unary</a>
</li>
<li class=" tsd-kind-variable tsd-parent-kind-external-module tsd-is-not-exported">
<a href="_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html#logpdf-1" class="tsd-kind-icon">logPDF</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer>
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
<li class="tsd-kind-type-alias tsd-has-type-parameter"><span class="tsd-kind-icon">Type alias with type parameter</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
<div class="bottom-nav center border-top">
<a href="https://www.patreon.com/athan">Donate</a>
/
<a href="/docs/api/">Docs</a>
/
<a href="https://gitter.im/stdlib-js/stdlib">Chat</a>
/
<a href="https://twitter.com/stdlibjs">Twitter</a>
/
<a href="https://github.com/stdlib-js/stdlib">Contribute</a>
</div>
</footer>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script src="../assets/js/theme.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-105890493-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
|
stdlib-js/www
|
public/docs/ts/latest/modules/_stats_base_dists_lognormal_logpdf_docs_types_index_d_.html
|
HTML
|
apache-2.0
| 16,239
|
<!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_60-ea) on Tue Sep 06 12:41:43 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer (Public javadocs 2016.9 API)</title>
<meta name="date" content="2016-09-06">
<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="org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer (Public javadocs 2016.9 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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="Package" class="title">Package org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroupConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroupConsumer</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroup.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroup</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroupSupplier.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroupSupplier</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroup.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroup</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/NodeConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">NodeConsumer</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">Node</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/NodeSupplier.html" title="interface in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">NodeSupplier</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">Node</a>></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroup.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroup</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/LoadBalancingGroup.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">LoadBalancingGroup</a><T>></td>
<td class="colLast">
<div class="block">A load balancing group</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">Node</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">Node</a><T>></td>
<td class="colLast">
<div class="block">Runtime representation of a mod_cluster node</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/Node.NodeResources.html" title="class in org.wildfly.swarm.config.undertow.configuration.mod_cluster.balancer">Node.NodeResources</a></td>
<td class="colLast">
<div class="block">Child mutators for Node</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/node/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2016.9/apidocs/org/wildfly/swarm/config/undertow/configuration/mod_cluster/balancer/package-summary.html
|
HTML
|
apache-2.0
| 9,902
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Elliptic.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Elliptic.Tests")]
[assembly: AssemblyCopyright("Copyright © 2013-2014 by Hans Wolff")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f68096d7-310d-4200-81a9-0443fb40ca29")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
|
hanswolff/curve25519
|
Curve25519.Tests/Properties/AssemblyInfo.cs
|
C#
|
apache-2.0
| 1,383
|
# Pyrenopeziza Fuckel GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Jb. nassau. Ver. Naturk. 23-24: 293 (1870)
#### Original name
Pyrenopeziza Fuckel
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Pyrenopeziza/README.md
|
Markdown
|
apache-2.0
| 228
|
package metcdv3
import "github.com/lytics/metafora"
type task struct {
id string
}
func (t *task) ID() string { return t.id }
// TaskFunc creates a Task interface from a task ID and etcd Node. The Node
// corresponds to the task directory.
//
// Implementations must support value being an empty string.
//
// If nil is returned the task is ignored.
type TaskFunc func(id, value string) metafora.Task
// DefaultTaskFunc is the default new task function used by the EtcdCoordinator
// and does not attempt to process the properties value.
func DefaultTaskFunc(id, _ string) metafora.Task { return &task{id: id} }
|
lytics/metafora
|
metcdv3/task.go
|
GO
|
apache-2.0
| 618
|
package vu.cornetto.stats;
import vu.cornetto.cdb.CdbCidArraySaxParser;
import vu.cornetto.cdb.CdbCid;
import java.util.Set;
import java.util.Iterator;
import java.util.ArrayList;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Created by IntelliJ IDEA.
* User: Piek Vossen
* Date: 25-aug-2008
* Time: 13:03:14
* To change this template use File | Settings | File Templates.
*/
public class CidStats {
static final String [] statusLabels = {"manual:ADJ",
"manual:ADJECTIVE",
"manual:NOUN",
"manual:VERB",
"manual:ADVERB",
"manual:",
"B-95:ADJ",
"B-95:NOUN",
"B-95:VERB",
"BM-90:ADJ",
"BM-90:ADJECTIVE",
"BM-90:NOUN",
"BM-90:VERB",
"BM-90:REST",
"M-97:ADJ",
"M-97:ADJECTIVE",
"M-97:NOUN",
"M-97:VERB",
"RESUME-75:ADJ",
"RESUME-75:NOUN",
"RESUME-75:VERB",
"D-75:NOUN",
"D-58:VERB",
"D-55:ADJ",
":ADJ",
":ADJECTIVE",
":ADVERB",
":CONJUNCTION",
":INTERJECTION",
":NOUN",
":NUMERAL",
":PREPOSITION",
":PRONOUN",
":VERB"};
static int [] statusInt = new int [statusLabels.length];
static public void main (String [] args) {
String cidPath = args[0];
System.out.println("cidPath = " + cidPath);
try {
FileOutputStream fos = new FileOutputStream(cidPath+".data.log");
FileOutputStream fosNoun = new FileOutputStream(cidPath+".noun.xls");
FileOutputStream fosVerb = new FileOutputStream(cidPath+".verb.xls");
FileOutputStream fosAdj = new FileOutputStream(cidPath+".adj.xls");
FileOutputStream fosRest = new FileOutputStream(cidPath+".rest.xls");
CdbCidArraySaxParser parser = new CdbCidArraySaxParser ();
parser.parseFile(cidPath);
//parser.parseFileAsBytes(cidPath);
Set keyset = parser.formMap.keySet();
Iterator keys = keyset.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
ArrayList cids = (ArrayList) parser.formMap.get(key);
int topSense = 0;
String name = "";
CdbCid topCid = null;
for (int i=0;i<cids.size();i++) {
CdbCid cid = (CdbCid) cids.get(i);
if ((name.length()==0) && (!cid.getName().equals("hel"))) {
name = cid.getName();
}
if ((cid.getC_seq_nr()>2) && (cid.getC_seq_nr()>topSense)) {
topCid = cid;
topSense = cid.getC_seq_nr();
if ((name.length()>0) && (cid.getName().equals("hel"))) {
topCid.setName(name);
}
}
for (int j=0;j<cids.size();j++) {
if (i!=j) {
CdbCid oCid = (CdbCid) cids.get(j);
if ((oCid.getC_seq_nr()==cid.getC_seq_nr()) &&
(!oCid.getC_lu_id().equals(cid.getC_lu_id()))) {
System.out.println("cid.\t" + cid.getCid());
System.out.println("oCid.\t" + oCid.getCid());
System.out.println("cid.getC_lu_id()\t" + cid.getC_lu_id());
System.out.println("cid.getSelected()\t" + cid.getSelected());
System.out.println("oCid.getSelected()\t" + oCid.getSelected());
System.out.println("oCid.getC_lu_id()\t" + oCid.getC_lu_id());
System.out.println("oCid.getC_form()\t" + oCid.getC_form());
System.out.println("oCid.getC_pos()\t" + oCid.getC_pos());
System.out.println("oCid.getC_seq_nr()\t" + oCid.getC_seq_nr());
}
}
}
}
if (topCid!=null) {
String str = topCid.getC_form()+"\t"+topCid.getC_pos()+"\t"+topCid.getC_seq_nr()+"\t"+topCid.getName()+"\n";
if (topCid.getC_pos().equalsIgnoreCase("NOUN")) {
fosNoun.write(str.getBytes());
}
else if (topCid.getC_pos().equalsIgnoreCase("VERB")) {
fosVerb.write(str.getBytes());
}
else if (topCid.getC_pos().equalsIgnoreCase("ADJ")) {
fosAdj.write(str.getBytes());
}
else {
fosRest.write(str.getBytes());
}
}
}
System.out.println("\nSTATUS MAP");
keyset = parser.statusMap.keySet();
keys = keyset.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
Integer count = (Integer) parser.statusMap.get(key);
int idx = vu.cornetto.util.Other.idxStringArray(key, statusLabels);
if (idx>-1) {
statusInt[idx] = count.intValue();
}
else {
System.out.println("UNKNOWN KEY AS STATUS:"+key);
}
//System.out.println(key+":"+count.toString());
}
int manual = 0;
int b95 = 0;
int bm90 = 0;
int d55 = 0;
int d58 = 0;
int d75 = 0;
int m97 = 0;
int resume = 0;
int auto = 0;
for (int i = 0; i < statusLabels.length; i++) {
String statusLabel = statusLabels[i];
int count = statusInt[i];
if (statusLabel.startsWith("manual:")) {
manual += count;
}
else if (statusLabel.startsWith("B-95:")) {
b95 += count;
}
else if (statusLabel.startsWith("BM-90:")) {
bm90 += count;
}
else if (statusLabel.startsWith("D-55:")) {
d55 += count;
}
else if (statusLabel.startsWith("D-58:")) {
d58 += count;
}
else if (statusLabel.startsWith("D-75:")) {
d75 += count;
}
else if (statusLabel.startsWith("M-97:")) {
m97 += count;
}
else if (statusLabel.startsWith("RESUME-75:")) {
resume += count;
}
else if (statusLabel.startsWith(":")) {
auto += count;
}
System.out.println(statusLabel+"\t"+count);
}
System.out.println("\nNo status value\t" + auto);
System.out.println("Status value\t" + (manual+b95+bm90+d55+d58+d75+m97+resume));
System.out.println("manual\t" + manual);
System.out.println("B-95\t" + b95);
System.out.println("BM-90\t= " + bm90);
System.out.println("D-55\t" + d55);
System.out.println("D-58\t" + d58);
System.out.println("D-75\t" + d75);
System.out.println("M-97\t" + m97);
System.out.println("RESUME-75\t" + resume);
System.out.println("\nNAME MAP");
keyset = parser.nameMap.keySet();
keys = keyset.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
Integer count = (Integer) parser.nameMap.get(key);
System.out.println(key+"\t"+count.toString());
}
keyset = parser.cidLuMap.keySet();
keys = keyset.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
ArrayList cids = (ArrayList) parser.cidLuMap.get(key);
for (int i=0;i<cids.size();i++) {
CdbCid cid = (CdbCid) cids.get(i);
fos.write(("CID:"+cid.getCid()+"\n").getBytes());
fos.write(("LU:"+cid.getC_lu_id()+"\n").getBytes());
fos.write(("SYNSET:"+cid.getC_sy_id()+"\n").getBytes());
fos.write(("FORM:"+cid.getC_form()+"\n").getBytes());
fos.write(("SEQNR:"+cid.getC_seq_nr()+"\n").getBytes());
}
}
fos.close();
fosNoun.close();
fosVerb.close();
fosAdj.close();
fosRest.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
|
cltl/CornettoExportParser
|
src/main/java/vu/cornetto/stats/CidStats.java
|
Java
|
apache-2.0
| 8,969
|
/*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* 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.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vlet.grid.voms;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import nl.esciencecenter.ptk.data.StringList;
import nl.esciencecenter.ptk.util.ResourceLoader;
import nl.esciencecenter.ptk.util.logging.ClassLogger;
import nl.esciencecenter.vbrowser.vrs.exceptions.VrsException;
import nl.esciencecenter.vlet.VletConfig;
import nl.esciencecenter.vlet.exception.AuthenticationException;
import nl.esciencecenter.vlet.exception.NestedIOException;
import nl.esciencecenter.vlet.exception.ResourceNotFoundException;
import nl.esciencecenter.vlet.grid.globus.GlobusCredentialWrapper;
import nl.esciencecenter.vlet.grid.globus.GlobusUtil;
import nl.esciencecenter.vlet.grid.proxy.GridProxy;
import nl.esciencecenter.vlet.grid.voms.VO;
import nl.esciencecenter.vlet.grid.voms.VOServer;
import nl.esciencecenter.vlet.grid.voms.VomsProxyCredential.VomsInfo;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.x509.AttributeCertificate;
import org.globus.gsi.GlobusCredential;
import org.ietf.jgss.GSSException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Static utility class for VomsProxyCredential.
*
* @author P.T. de Boer
*/
public class VomsUtil
{
private static ClassLogger logger;
// ==================
// Registry
// ==================
private static Hashtable<String, VO> vomsRegistry = new Hashtable<String, VO>();
public static final String CERT_VOMS_EXTENSION_OID = "1.3.6.1.4.1.8005.100.100.5";
static
{
initVoms();
logger = ClassLogger.getLogger(VomsUtil.class);
}
private static void initVoms()
{
// nop
/*
* for now: use: VO.loadFromXMLFile(...) to scan voms.xml file.
* addVO("pvier", "voms.grid.sara.nl", 30000,
* "/O=dutchgrid/O=hosts/OU=sara.nl/CN=voms.grid.sara.nl");
*
* addVO("vlemed", "voms.grid.sara.nl", 30003,
* "/O=dutchgrid/O=hosts/OU=sara.nl/CN=voms.grid.sara.nl");
*/
}
// ==================
// Utily methods
// ==================
/**
* Create VomsProxyCredential from GlobusCredentail using the information
* provided by the VO.
*
* @throws VrsException
*/
public static VomsProxyCredential createVomsCredential(GlobusCredential globusCred, VO vo, long lifetime)
throws VrsException
{
if (vo == null)
throw new NullPointerException("VO object can not be null");
VomsProxyCredential vomscred;
try
{
vomscred = new VomsProxyCredential(globusCred, vo, "G/" + vo.getVoName(), lifetime);
return vomscred;
}
// Exception Nesting:
catch (Exception e)
{
throw convertException("Couldn't create VOMS proxy for:" + vo.getVoName(), e);
}
}
private static VrsException convertException(String message, Exception e)
{
// Filter standard Globus exceptions:
VrsException ex = GlobusUtil.checkException(message, e);
if (ex != null)
return ex;
// Exception nesting:
if (e instanceof VrsException)
{
return ((VrsException) e); // keep my own;
}
else if (e instanceof GeneralSecurityException)
{
return new AuthenticationException(message + "\nReason=" + e.getMessage(), e);
}
else if (e instanceof GSSException)
{
return new AuthenticationException(message + "\nReason=" + e.getMessage(), e);
}
else if (e instanceof IOException)
{
return new NestedIOException(message + "\nReason=" + e.getMessage(), e);
}
// default:
return VrsException.create(e.getMessage(), e,e.getClass().getSimpleName());
}
/**
* Convert GlobusCredential to VOMS enbled GlobusCredential, using the VO
* information and lifetime (in seconds)
*
* @param vo
* VO INfo Object
* @param optVoGroup
* if the groupname differs from the VOname specify this value
* @param optVoRole
* optional VO Role
*/
public static VomsProxyCredential vomsify(GlobusCredential orgCred, VO vo, String optVoGroup, String optVoRole,
long lifetimeInSeconds) throws VrsException
{
if (vo == null)
throw new NullPointerException("VO object can not be null");
logger.infoPrintf("vomsify(): VO=%s, group=%s, role=%s\n", vo, optVoGroup, optVoRole);
String voprefix = optVoGroup; // group name: VOName/VOGroup
if (voprefix == null)
voprefix = vo.getVoName(); // plain name
// construct VOName/Group:Role command
String cmd = "B/" + voprefix;
if ((optVoRole != null) && (optVoRole.equals("") == false))
cmd = cmd + ":" + optVoRole;
try
{
VomsProxyCredential vomscred = new VomsProxyCredential(orgCred, vo, cmd, lifetimeInSeconds);
return vomscred;
}
// Exception Nesting:
catch (Exception e)
{
throw convertException("Couldn't create VOMS proxy for:" + vo.getVoName(), e);
}
}
// /**
// * Vomsify (VLET) GridProxy object and overwrite previous proxy with
// * vomsified proxy.
// */
// public static VomsProxyCredential vomsify(GridProxy prox, VO vo,
// long lifetimeInSeconds, boolean saveNewProxy) throws VlException
// {
// if (vo==null)
// throw new NullPointerException("VO object can not be null");
//
// logger.infoPrintf("vomsify(): Using proxy:"+prox.getProxyFilename());
//
// try
// {
// VomsProxyCredential vomscred = new VomsProxyCredential(prox,
// vo, "G/" + vo.getVoName(),
// lifetimeInSeconds);
// prox.setGlobusCredential(vomscred.getVomsProxy());
//
// // save and overwrite:
// if (saveNewProxy)
// {
// logger.infoPrintf("vomsify(): Saving new proxy to:"+prox.getProxyFilename());
// prox.saveProxy();
// }
//
// return vomscred;
// }
// // Exception Nesting:
// catch (Exception e)
// {
// throw
// convertException("Couldn't create VOMS proxy for:"+vo.getVoName(),e);
// }
// }
public static VomsProxyCredential vomsify(GlobusCredential cred, String voName, long lifeTimeInSeconds)
throws VrsException
{
return vomsify(cred, voName, null, null, lifeTimeInSeconds);
}
/**
* Vomsify (VLET) GridProxy object and overwrite previous proxy with
* vomsified proxy. The VO 'voName' must be know in the registry.
* <p>
* As of 1.3.0 the voCommand can be VOName/Group:VORole. Parameters voGroup
* and voRole are optional. Only specify voGroup if the fullgroup name is
* different then the VO Name. For example: VO Name="pvier", full group
* name= "pvier/test"
*
* @param voName
* shortname for the VO, for example "pvier"
* @param optional
* VO Group name, if different then VOName, for example
* "pvier/subgroup"
* @param optional
* role, for example "tester"
*/
public static VomsProxyCredential vomsify(GlobusCredential cred, String voName, String voGroup, String voRole,
long lifetimeInSeconds) throws VrsException
{
Exception except = null;
VO vo = null;
try
{
vo = getVO(voName);
}
catch (Exception e)
{
except = e;
}
if (vo == null)
throw new VrsException("VOMSProxyException: VO not known or configuration missing for vo:" + voName
+ "\nPlease add VO server information to voms.xml", except);
// String voRole=getVORole(voCommand);
// logger.debugPrintf("vomsify: vo=%s, voRole=%s\n",vo.getVoName(),voRole);
return vomsify(cred, vo, voGroup, voRole, lifetimeInSeconds);
}
/** Return list of VO names (aliases) to choose from. */
public static String[] getVOs()
{
Set<String> keys = vomsRegistry.keySet();
String names[] = new String[keys.size()];
names = keys.toArray(names);
return names;
}
/**
* Add VO information to the global registry.2 Overwrites previous
* information if already added.
*/
public static void addVO(String voName, String host, int port, String DN)
{
addVO(voName, voName, host, port, DN);
}
/**
* Add VO information to the global registry. Overwrites previous
* information if already added. Note that 'alias' is used to store the VO
* object, but 'name' is the actual VO name used when contacting the voms
* server. Use getVO(alias) to retrieve the VO object.
*/
public static void addVO(String alias, String voName, String host, int port, String DN)
{
// check voName, other fields can be set in a later stage (null is
// allowed).
if (voName == null)
throw new NullPointerException("voName can not be null");
if (alias == null)
alias = voName;
vomsRegistry.put(alias, new VO(voName, host, port, DN));
}
/** Static main for command line interaction */
static int verboseLevel = 0;
public static void main(String args[])
{
String proxyFile = null;
String newProxyFile = null;
// new argument array for parsed/shifted arguments
String shiftedArgs[] = new String[args.length];
String voname = null;
int index = 0;
String[] newArgs = VletConfig.parseArguments(args);
for (int i = 0; i < newArgs.length; i++)
{
// parse double argument options:
if ((args[i].startsWith("-") && (i + 1 < args.length)))
{
if (args[i].startsWith("-f"))
proxyFile = args[i + 1];
else if (args[i].startsWith("-o"))
newProxyFile = args[i + 1];
else
// unrecognized argment
Usage();
// shift extra argument!
i++;
}
else
// keep argument
shiftedArgs[index++] = args[i];
}
// use new args array.
args = shiftedArgs;
VO vo = null;
// first argument must be vo name
if (index > 0)
voname = args[0];
if (index < 4)
{
// non null VO name => query registry
if (voname == null)
{
Usage();
}
else
{
try
{
vo = getVO(voname);
}
catch (Exception e)
{
System.err.println("*** Exception:" + e);
e.printStackTrace();
}
if (vo == null)
{
Exit("Unknown VO. please specify contact details for VO:" + voname, 3);
}
}
}
else
{
String host = args[1];
int port = -1;
try
{
port = new Integer(args[2]);
}
catch (java.lang.NumberFormatException e)
{
Exit("Port argument is not a number:" + args[2], 5);
}
String dnname = args[3];
vo = new VO(voname, host, port, dnname);
}
GridProxy prox = null;
// Make sure new Grid Proxy setting are NOT saved !
VletConfig.setUsePersistantUserConfiguration(false);
if (proxyFile == null)
{
prox = GridProxy.getDefault();
}
else
{
try
{
prox = GridProxy.loadFrom(proxyFile);
}
catch (VrsException e)
{
if (verboseLevel > 1)
{
System.err.println("*** Exception:" + e);
e.printStackTrace();
}
Exit("*** Error loading proxy from:" + proxyFile + "\n" + "*** Reason:" + e.getMessage(), 4);
}
prox.setDefaultProxyLocation(proxyFile);
}
Message(1, "Using proxyfile:" + prox.getProxyFilename());
VomsProxyCredential vomsCred = null;
GlobusCredentialWrapper credWrapper = (GlobusCredentialWrapper) prox
.getCredential(GridProxy.GLOBUS_CREDENTIAL_TYPE);
try
{
vomsCred = vomsify(credWrapper.getGlobusCredential(), vo, null, null, prox.getTimeLeft());
}
catch (Exception e)
{
System.err.println("Exception:" + e);
e.printStackTrace();
System.exit(1);
}
if (prox.isValid() == false)
{
Exit("Error: Invalid proxy. Please create valid proxy first", 2);
}
// 0 = important message
// 1 = informational messages
// 2 = detailed information
// 3+ = debugging
if (verboseLevel >= 1)
{
VomsInfo info = null;
try
{
info = vomsCred.getVomsInfo();
}
catch (Exception e)
{
System.err.println("Exception:" + e);
e.printStackTrace();
}
if (info != null)
{
for (Enumeration<String> keys = info.keys(); keys.hasMoreElements();)
{
String key = keys.nextElement();
Message(1, "vomsinfo." + key + "=" + info.get(key));
}
}
else
{
System.err.println("***Error: NULL voms info:");
}
}
// all ok ?
Exit(0);
}
private static void Exit(String msg, int val)
{
System.err.println(msg);
System.exit(val);
}
private static void Exit(int val)
{
System.exit(val);
}
private static void Usage()
{
System.err.println("usage: <voname> [<host> <port> <serverdn>] [-f[ile] proxy] [-o[ut] newproxy");
System.exit(1);
}
public static void Message(int vLev, String msg)
{
if (verboseLevel >= vLev)
System.out.println(msg);
}
/**
* read from vomx.xml file and return vo object.
*
* @param vomsFilename
* path of voms.xml file, if null read from
* "/etc/grid-security/vomsdir/voms.xml".
* @param voName
* the name of the Virtual Organisation.
* @throws VrsException
*/
public static VO readFromXML(String vomsFilename, String voName) throws Exception
{
ResourceLoader loader = ResourceLoader.getDefault();
// this is a VERY IMPORTANT line - otherwise the DN cannot match against
// the C client that uses openssl
org.bouncycastle.asn1.x509.X509Name.DefaultSymbols.put(org.bouncycastle.asn1.x509.X509Name.EmailAddress,
"Email");
org.bouncycastle.asn1.x509.X509Name.RFC2253Symbols.put(org.bouncycastle.asn1.x509.X509Name.EmailAddress,
"Email");
org.bouncycastle.asn1.x509.X509Name.DefaultLookUp.put("Email", org.bouncycastle.asn1.x509.X509Name.E);
try
{
logger.infoPrintf("Trying VOMS file:%s\n", vomsFilename);
InputStream xmlStream = loader.createInputStream(vomsFilename);
// if (vomsXMLFile.exists()==false)
// {
// throw new
// ResourceNotFoundException("voms.xml not specified or file does not exist:"+vomsFilename);
// }
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlStream);
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfVOs = doc.getElementsByTagName("vo");
int numberOfVOs = listOfVOs.getLength();
logger.infoPrintf("parsing total nr. of VOs:%d", numberOfVOs);
for (int v = 0; v < numberOfVOs; v++)
{
Node voNode = listOfVOs.item(v);
Element voElement = (Element) voNode;
// name - only one
NodeList voNameList = voElement.getElementsByTagName("name");
Element nameElement = (Element) voNameList.item(0);
NodeList text = nameElement.getChildNodes();
String name = (String) ((Node) text.item(0)).getNodeValue().trim();
logger.infoPrintf("Reading voname=%s\n", name);
if (name.equals(voName))
{
VO vo = new VO(name); // protected constructor;
// this.name = name ;
// this.known = true ;
// admin - only one
NodeList voAdminList = voElement.getElementsByTagName("admin");
Element adminElement = (Element) voAdminList.item(0);
text = adminElement.getChildNodes();
vo.setAdmin((String) ((Node) text.item(0)).getNodeValue().trim());
NodeList voServersList = voElement.getElementsByTagName("server");
int nrOfservers = voServersList.getLength();
VOServer[] voServers = new VOServer[nrOfservers];
logger.infoPrintf(" - nrOfServers=%d\n", nrOfservers);
for (int i = 0; i < nrOfservers; i++)
{
Node serverNode = voServersList.item(i);
Element serverElement = (Element) serverNode;
// server name
NodeList list = serverElement.getElementsByTagName("name");
Element element = (Element) list.item(0);
text = element.getChildNodes();
String host = (String) ((Node) text.item(0)).getNodeValue().trim();
// server port
list = serverElement.getElementsByTagName("port");
element = (Element) list.item(0);
text = element.getChildNodes();
int port = Integer.parseInt((String) ((Node) text.item(0)).getNodeValue().trim());
// server cert
list = serverElement.getElementsByTagName("cert");
element = (Element) list.item(0);
text = element.getChildNodes();
String certFile = (String) ((Node) text.item(0)).getNodeValue().trim();
// server dn
list = serverElement.getElementsByTagName("dn");
element = (Element) list.item(0);
text = element.getChildNodes();
String hostDN = (String) ((Node) text.item(0)).getNodeValue().trim();
voServers[i] = new VOServer(host, port, certFile, hostDN);
logger.infoPrintf(" - VO server=%s:%d\n", host, port);
logger.infoPrintf(" - VO DN=%s\n", hostDN);
} // end of server tag loop
vo.setServers(voServers);
logger.infoPrintf("Returning VO=%s\n", vo);
// keep filename;
vo.setVOMSXmlFile(vomsFilename);
return vo;
} // end of vo test
// skip other VOs ?
} // end of vo tag loop
return null;
}
catch (ParserConfigurationException e)
{
logger.warnPrintf("Parse error when reading from file:%s\n", vomsFilename);
throw new VrsException("VomsUtil: Couldn't parse:" + vomsFilename, e);
}
catch (java.io.FileNotFoundException e)
{
logger.warnPrintf("VomsUtil: File doesn't exists:%s\n", vomsFilename);
throw e; // pass
}
catch (IOException e)
{
logger.warnPrintf("VomsUtil: Couldn't read VOMS file:%s\n", vomsFilename);
throw e ; // pass
}
catch (SAXException e)
{
logger.warnPrintf("SAXException: Couldn't parse VOMS file:%s\n", vomsFilename);
throw new VrsException("VomsUtil: SAXException, couldn't parse:" + vomsFilename, e);
}
// others:
catch (Exception e)
{
logger.warnPrintf("Unknown Exception when reading from file:%s\n", vomsFilename);
throw e;
}
}
/**
* Returns VO information from registry or NULL. Doesn't do any checking.
* voName can be VO name or an alias used to store the VO object. Current
* search order is:
*
* <pre>
* - $HOME/.globus/vomsdir/voms.xml
* - VLET_INSTALL/etc/vomsdir/voms.xml
* - /etc/grid-security/vomsdir/voms.xml
* </pre>
*
* When the VO information is found, it is assumed the parent directory of
* that file is the 'vomsdir' which also must contain the server certificate
* specified as 'cert' in the voms.xml file.
*
* @throws VrsException
*/
public static VO getVO(String voCommand) throws Exception
{
// strip optional command:
String voName = getVOName(voCommand);
// String voRole=getVOName(voCommand);
logger.debugPrintf("getVO: voCommand = '%s' => voName='%s'\n'", voCommand, voName);
VO vo = null;
// Always reread file, do not check registry to allow
// for runtime edition of the voms.xml file.
// Else the vbrowser has to be restarted each time
// the voms.xml file changes !
// ---
// vo=vomsRegistry.get(voName);
// if (vo!=null)
// return vo;
// ---
// ===
// search and read voms.xml information .
// ===
// search path:
// - user first : $HOME/.vletrc/voms.xml
// - globus : $HOME/.globus/vomsdir/voms.xml
// - vlet installation : VLET_INSTALL/etc/vomsdir/voms.xml
// - system installation /etc/grid-security/vomsdir/voms.xml
String searchPaths[];
try
{
// Search paths.
// All files are read, newer definition replace old.
searchPaths = new String[]
{
"/etc/grid-security/vomsdir/voms.xml", // system wide
"vomsdir/voms.xml", // Relative! installation
VletConfig.getUserHomeLocation().appendPath(".globus/vomsdir/voms.xml").getPath(), // $HOME/.globus
VletConfig.getUserHomeLocation().appendPath(".vletrc/vomsdir/voms.xml").getPath(), // vletrc
null // null = default location.
};
}
catch (Exception e)
{
throw new VrsException("Failed to initialize search paths", e);
}
VrsException except = null;
for (String path : searchPaths)
{
try
{
vo = readFromXML(path, voName);
if (vo != null)
{
// store:
vomsRegistry.put(vo.getVoName(), vo);
return vo;
}
}
catch (ResourceNotFoundException e)
{
// allowed: file does not exist.
logger.infoPrintf("File does not exists:%s\n", path);
vo = null;
}
catch (java.io.FileNotFoundException e)
{
// allowed: file does not exist.
logger.infoPrintf("File does not exists:%s\n", path);
vo = null;
}
catch (VrsException e)
{
except = e;
logger.logException(ClassLogger.ERROR, e, "Failed to read path:%s\n", path);
Throwable cause = null;
if ((cause = e.getCause()) != null)
logger.logException(ClassLogger.ERROR, cause, "cause=%s\n", cause);
}
}
// if no vo information could be found and there was an exception
// inform caller about the (last encountered) exception.
// Ignore Exceptions if valid
// VO information was found.
if ((vo == null) && (except != null))
throw except;
return null;
}
/**
* Strip name from full VO Command which can have an VORole appended.
*
* @param voCommand
* VOName[/voGroup]:VORole
* @return VOName part
*/
public static String getVOName(String voCommand)
{
if (voCommand == null)
return null;
String strs[] = voCommand.split(":");
if ((strs == null) || (strs.length <= 0))
return voCommand;
// split optional VOName/VOGroup
String subStrs[] = strs[0].split("/");
if (subStrs == null)
return strs[0];
return subStrs[0];
}
/**
* Strip name from full VO Command which can have an VORole appended.
*
* @param voCommand
* VOName/VORole
* @return VORole part
*/
public static String getVORole(String voCommand)
{
if (voCommand == null)
return null;
String strs[] = voCommand.split(":");
if ((strs == null) || (strs.length <= 1))
return null;
return strs[1];
}
public static String parse(X509Certificate certs[]) throws Exception
{
StringBuilder log = new StringBuilder();
log.append("> Started parsing #" + certs.length + " certificates\n");
for (int i = 0; i < certs.length; i++)
{
log.append("> [" + i + "]: --- Certificate Dump ---<\n");
logAppend(log, certs[i]);
log.append("> [" + i + "]: --- END Certificate Dump ---<\n");
ArrayList<AttributeCertificate> vomsACs = extractVOMSACs(certs);
if (vomsACs == null)
{
log.append("> [" + i + "]: *** No VOMS extension in certificate\n");
continue;
}
else
{
log.append("> [" + i + "]: VOMS extension founds:" + vomsACs.size() + ". Information following:\n");
}
for (int j = 0; j < vomsACs.size(); j++)
{
VOMSAttributeCertificate vomsAC = new VOMSAttributeCertificate(vomsACs.get(j));
ArrayList<String> strs = vomsAC.getVOMSFQANs();
log.append("> [" + i + "]: - VOMS AC[" + j + "] = {" + new StringList(strs).toString("'", ",") + "}\n");
}
}
return log.toString();
}
private static void logAppend(StringBuilder log, X509Certificate cert)
{
log.append(" - Type :" + cert.getType() + "\n - Version :" + cert.getVersion()
+ "\n - Issuer dn :" + cert.getIssuerDN() + "\n - Issuer unique id :" + cert.getIssuerUniqueID()
+ "\n - Not before :" + cert.getNotBefore() + "\n - Not after :" + cert.getNotAfter()
+ "\n - Subject dn :" + cert.getSubjectDN());
Set<String> oids1 = cert.getCriticalExtensionOIDs();
log.append("\n - Criticial Oids :{" + toString(oids1, ",") + "}");
Set<String> oids2 = cert.getNonCriticalExtensionOIDs();
log.append("\n - Non Critical Oids:{" + toString(oids2, ",") + "}");
log.append("\n");
}
private static String toString(Set<String> set, String sepString)
{
if (set == null)
return "";
StringList list = new StringList(set);
return list.toString(sepString);
}
/**
* Static method that returns all included AttributesCertificates of a
* GlobusCredential. In general we are only interested in the first one.
*
* @param vomsProxy
* the voms enabled proxy credential
* @return all AttributeCertificates
*/
public static ArrayList<AttributeCertificate> extractVOMSACs(X509Certificate[] x509s)
{
// the aim of this is to retrieve all VOMS ACs
ArrayList<AttributeCertificate> acArrayList = new ArrayList<AttributeCertificate>();
for (int x = 0; x < x509s.length; x++)
{
logger.debugPrintf(" - Checking certificate[" + x + "]\n");
try
{
byte[] payload = x509s[x].getExtensionValue(VomsUtil.CERT_VOMS_EXTENSION_OID);
if (payload == null)
{
logger.debugPrintf(" - #%d: No VOMS AC extension.\n", x);
continue;
}
else
logger.debugPrintf(" - #d: Found VOMS AC extension.\n", x);
// Octet String encapsulation - see RFC 3280 section 4.1
payload = ((ASN1OctetString) new ASN1InputStream(new ByteArrayInputStream(payload)).readObject())
.getOctets();
ASN1Sequence acSequence = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(payload))
.readObject();
for (Enumeration e1 = acSequence.getObjects(); e1.hasMoreElements();)
{
ASN1Sequence seq2 = (ASN1Sequence) e1.nextElement();
for (Enumeration e2 = seq2.getObjects(); e2.hasMoreElements();)
{
AttributeCertificate ac = new AttributeCertificate((ASN1Sequence) e2.nextElement());
acArrayList.add(ac);
}
}
}
catch (Exception pe)
{
logger.logException(ClassLogger.DEBUG, pe, " - #%d: This part of the chain has no AC\n", x);
}
}
return acArrayList;
}
}
|
NLeSC/vbrowser
|
source/nl.esciencecenter.vlet.grid.globus/src/nl/esciencecenter/vlet/grid/voms/VomsUtil.java
|
Java
|
apache-2.0
| 31,944
|
/**
*
* Copyright 2015 sourceforge.
*
* 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 org.cleanlogic.ol4gwt.showcase;
import com.google.gwt.user.client.ui.DialogBox;
/**
* This will create a standard gwt-dialogbox with a close button. the css for
* the close button:
* <pre>
* .gwt-DialogBox-closebutton {
* font-weight: bold;
* color: #dd0000;
* padding: 2px;
* margin-left: 2px;
* }
* .gwt-DialogBox-closebutton:ACTIVE {
* padding: 1px;
* border: thin #dd0000 solid;
* }
* .gwt-DialogBox-closebutton:HOVER {
* padding: 2px;
* color: #ee0000;
* }
* </pre>
* @author Frank Wynants
*/
public class DialogBoxWithCloseButton extends DialogBox
{
/** The count. */
private static int count = 0;
/**
* Define closeDialog using JSNI.
* @param dialogBox The dialog box.
* @param functionName The name of the function to invoke.
*/
private static native void redefineClose(DialogBox dialogBox, String functionName)
/*-{
$wnd[functionName] = function()
{
dialogBox.@org.cleanlogic.ol4gwt.showcase.DialogBoxWithCloseButton::hideDialog()();
}
}-*/;
/** The id. */
private final String uid;
/**
* Creates an instance.
*/
public DialogBoxWithCloseButton()
{
this(false);
}
/**
* Creates an instance.
* @param autoHide True to autohide.
*/
public DialogBoxWithCloseButton(final boolean autoHide)
{
this(autoHide, true);
}
/**
* Creates an instance.
* @param autoHide True to autohide.
* @param modal True to make the dialog modal.
*/
public DialogBoxWithCloseButton(final boolean autoHide, final boolean modal)
{
super(autoHide, modal);
setGlassEnabled(true);
this.uid = "DialogBoxWithCloseButton_" + count++ + "_Close";
setText("Dialog");
}
/**
* Hides the dialog.
*/
public void hideDialog()
{
super.hide();
}
/*
* (non-Javadoc)
* @see com.google.gwt.user.showcase.ui.DialogBox#setHTML(java.lang.String)
*/
@Override
public void setHTML(final String html)
{
final String styleName = getStyleName() + "-closebutton";
super.setHTML("<table border='0' cellspacing='0' cellpadding='0' width='100%'><tr><td width='5%'> </td><td align='left' width='90%'>" + html + "</td><td align='right' valign='middle' width='5%'><span class='" + styleName + "' onclick='"
+ this.uid + "()'>X</span></td></tr></table>");
redefineClose(this, this.uid);
}
/*
* (non-Javadoc)
* @see com.google.gwt.user.showcase.ui.DialogBox#setText(java.lang.String)
*/
@Override
public void setText(final String text)
{
this.setHTML(text);
}
}
|
iSergio/gwt-ol
|
ol4gwt-showcase/src/main/java/org/cleanlogic/ol4gwt/showcase/DialogBoxWithCloseButton.java
|
Java
|
apache-2.0
| 3,484
|
vcenter_client CHANGELOG
========================
This file is used to list changes made in each version of the vcenter_client cookbook.
0.1.0
-----
- [your_name] - Initial release of vcenter_client
- - -
Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown.
The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
|
pigram86/daas-repo
|
cookbooks/vcenter_client/CHANGELOG.md
|
Markdown
|
apache-2.0
| 483
|
<link rel="stylesheet" type="text/css" href="<?php echo skin_url("css/page/profile.css");?>">
<?php $this->load->view("include/banner", @$member);?>
<section class="section box-wapper-show-image my_photo" id="wrapper">
<div class="container" style="position: relative;min-height:400px;">
<div class="row"><h1 id="all-img-seach"><?php echo $all_photo;?> results found</h1></div>
<div class="row">
<div class="gird-img col-md-12" id="my_photo_page">
<div class="cards row">
<?php
$i = 0;
$count_photo = count($results);
if ($count_photo < 5) {
$count_photo = 3;
}
$max_items_set = ceil($count_photo / 3);
$user_id = -1;
if ($this->session->userdata('user_info')) {
$user_info = $this->session->userdata('user_info');
$user_id = $user_info["id"];
}
$colum = 1;
$items = 0;
$max_items = $max_items_set;
foreach ($results as $photo):
if ($max_items % $max_items_set == 0) {
if (($count_photo == 3 && $colum > 3)) {
} else {
echo "<div class='col-md-4 grid-column' id='grid-column-" . $colum . "'>";
}
$colum++;
$items = 0;
}
$max_items++;
$items++;
?>
<?php
$this->load->view("seach/seach_result_ajax",array("photo" => $photo));
if ($items == $max_items_set || (($max_items - $max_items_set) == $count_photo) && $items < $max_items_set) {
if ($count_photo == 3 && $colum > 3) {
} else {
echo "</div>";
}
}
?>
<?php endforeach; ?>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
</div><!--end container-->
</section>
<?php $this->load->view("include/share");?>
<?php $this->load->view("include/report-images"); ?>
<?php $this->load->view("include/modal_delete_photo"); ?>
<?php $this->load->view("include/modal_choose_photo"); ?>
<?php $this->load->view("include/modal_choose_story"); ?>
<style type="text/css">
.company_catalog{
position: fixed;
width: 350px;
background: #fff;
top: 20%;
right: -350px;
z-index: 100;
padding: 20px;
border-radius: 4px;
border-top-left-radius: 0;
border-bottom-right-radius: 0;
box-shadow: 1px 1px 1px 0px;
transition: right 0.5s ease-in-out;
-webkit-transition: right 0.5s ease-in-out;
}
.company_catalog.opens{
right: -20px;
}
.company_catalog .icon-catalog{
position: absolute;
left: -35px;
border-radius: 4px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
padding: 10px;
top: 0;
background: #fff;
cursor: pointer;
}
.company_catalog .icon-catalog{max-width: 38px;}
.company_catalog h3{
margin-top: 0;
color: #37a7a7;
font-weight: bold;
margin-bottom: 15px;
}
.company_catalog .compamy_catalog_cat{
margin-top: 20px;
direction: rtl;
}
.company_catalog .compamy_catalog_cat{
margin-top: 20px;
direction: rtl;
float: left;
max-height: 100%;
padding-left: 15px;
overflow: auto;
}
.company_catalog .compamy_catalog_cat .box_scroll_search{
direction: ltr;
}
.company_catalog .compamy_catalog_cat strong{
margin-bottom: 5px;
}
.company_catalog .compamy_catalog_cat .list-projects p,
.company_catalog .compamy_catalog_cat .list-product p{
margin-bottom: 0;
}
.company_catalog .box-refine a.refine-search{
font-size: 14px;
color: #212121;
text-decoration: underline;
width: 100%;
float: left;
text-align: left;
font-family: 'Avenir Next LT Pro Regular';
}
@media (max-width: 768px) {
.company_catalog .seach-sumit{
width: auto !important;
}
}
@media (max-width: 350px) {
.company_catalog{
width: 290px;
right: -290px;
}
.company_catalog .box-seach input[type='text']{
font-size: 12px;
}
.company_catalog .xsl-remove-padding-left{
padding-left: 0;
}
}
</style>
<script type="text/javascript">
var height_ = $(".company_catalog .compamy_catalog_cat").offset();
$(document).ready(function(){
$(".icon-catalog").click(function(){
$(this).parents('.company_catalog').toggleClass('opens');
var window_height = $(window).height();
var window_w = $(window).width();
console.log($(".company_catalog .compamy_catalog_cat").height());
if(window_w > 676){
$(".company_catalog .compamy_catalog_cat").css("height",(window_height - (height_.top + 42))+"px");
}else{
$(".company_catalog .compamy_catalog_cat").css("height",(window_height - height_.top)+"px");
}
});
});
/*
==========================================================
BEGIN: COMMENT
*/
function action_comment(obj) {
if (typeof $(obj).attr('comment-id') != 'undefined' && $(obj).attr('comment-id') != null) {
edit_comment(obj);
} else if (typeof $(obj).attr('reply-comment-id') != 'undefined' && $(obj).attr('reply-comment-id') != null) {
reply_comment(obj);
} else {
add_comment(obj);
}
}
function get_content_edit(obj) {
var object_id = $(obj).attr('data-id');
var text = $(obj).parents('.comment-items').find('.text-comment').text();
$(obj).parents('.form-comment').find('textarea').val(text);
$(obj).parents('.form-comment').find('.btn-custom').attr('comment-id', object_id);
return false;
}
function reply(obj) {
var object_id = $(obj).attr('data-id');
var text = $(obj).parents('.comment-items').find('.text-comment').text();
$(obj).parents('.form-comment').find('textarea').focus();
$(obj).parents('.form-comment').find('.btn-custom').attr('reply-comment-id', object_id);
return false;
}
function reply_comment(obj) {
$(obj).removeAttr('comment-id');
var object_id = $(obj).attr('data-id');
var reply_id = $(obj).attr('reply-comment-id');
var text = $(obj).parents('.form-comment').find('textarea').val();
if (text.trim() != '' && text.trim() != null) {
$(obj).attr('disabled', 'disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'initial');
$.ajax({
url: "<?php echo base_url('/comments/reply'); ?>/" + object_id + "/photo",
type: 'POST',
dataType: "json",
data: {
"text": text,
"reply_id": reply_id
},
success: function (data) {
if (data['status'].trim() == "true") {
var qty = data['num_comment'];
var strqty = (qty < 2) ? 'comment' : 'comments';
$(obj).parents('.form-comment').find('.photo-action-all-comment').append('<p style="margin-bottom:0;"><b>' + data['full_name'] + ':</b> <span class="text-comment">' + text + '</span></p>');
$(obj).parents('.form-comment').find('.text-tiny').html(qty + ' ' + strqty);
$(obj).parents('.form-comment').find('.photo-action-all-comment').animate({scrollTop: $(obj).parents('.form-comment').find('.photo-action-all-comment').prop("scrollHeight")}, 1000);
}
},
complete: function () {
$(obj).removeAttr('disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'none');
},
error: function (data) {
console.log(data['responseText']);
}
});
$(obj).parents('.form-comment').find('textarea').val('');
$(obj).removeAttr('reply-comment-id');
}
}
function delete_comment(obj) {
if (confirm('Are you sure you want to delete this?')) {
var object_id = $(obj).attr('data-id');
$.ajax({
url: "<?php echo base_url('/comments/delete'); ?>/" + object_id,
type: 'POST',
dataType: "json",
data: {},
success: function (data) {
if (data['status'].trim() == "true") {
$(obj).parents('.comment-items').fadeOut('slow', function () {
$(this).remove();
});
}
},
complete: function () {
},
error: function (data) {
console.log(data['responseText']);
}
});
}
}
function clean_comment(obj) {
$(obj).parents('.form-comment').find('textarea').val('');
$(obj).parents('.form-comment').find('.btn-custom').removeAttr('reply-comment-id');
$(obj).parents('.form-comment').find('.btn-custom').removeAttr('comment-id');
}
function edit_comment(obj) {
$(obj).removeAttr('reply-comment-id');
var object_id = $(obj).attr('data-id');
var comment_id = $(obj).attr('comment-id');
var text = $(obj).parents('.form-comment').find('textarea').val();
if (text.trim() != '' && text.trim() != null) {
$(obj).attr('disabled', 'disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'initial');
$.ajax({
url: "<?php echo base_url('/comments/update'); ?>/" + object_id + "/photo",
type: 'POST',
dataType: "json",
data: {
"text": text,
'data_id': comment_id
},
success: function (data) {
console.log(data);
if (data['status'].trim() == "true") {
$(obj).parents('.form-comment').find('.comment-items[data-id="' + comment_id + '"] .text-comment').text(text);
}
},
complete: function () {
$(obj).removeAttr('disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'none');
},
error: function (data) {
console.log(data['responseText']);
}
});
$(obj).parents('.form-comment').find('textarea').val('');
$(obj).parents('.form-comment').find('.btn-custom').removeAttr('comment-id');
}
}
function add_comment(obj) {
var object_id = $(obj).attr('data-id');
var text = $(obj).parents('.form-comment').find('textarea').val();
if (text.trim() != '' && text.trim() != null) {
$(obj).attr('disabled', 'disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'initial');
$.ajax({
url: "<?php echo base_url('/comments/add'); ?>/" + object_id + "/photo",
type: 'POST',
dataType: "json",
data: {
"text": text
},
success: function (data) {
if (data['status'].trim() == "true") {
var qty = data['num_comment'];
var strqty = (qty < 2) ? 'comment' : 'comments';
$(obj).parents('.form-comment').find('.photo-action-all-comment').append('<p style="margin-bottom:0;"><b>' + data['full_name'] + ':</b> <span class="text-comment">' + text + '</span></p>');
$(obj).parents('.form-comment').find('.text-tiny').html(qty + ' ' + strqty);
$(obj).parents('.form-comment').find('.photo-action-all-comment').animate({scrollTop: $(obj).parents('.form-comment').find('.photo-action-all-comment').prop("scrollHeight")}, 1000);
}
},
complete: function () {
$(obj).removeAttr('disabled');
$(obj).parents('.form-comment').find('.load-comment').css('display', 'none');
},
error: function (data) {
console.log(data['responseText']);
}
});
$(obj).parents('.form-comment').find('textarea').val('');
}
}
/*
==========================================================
END: COMMENT
*/
</script>
<style type="text/css">
.card .top-social .action{
position: absolute;
right: 10px;
top: 0;
display: inline-block;
}
.card .top-social .action ul li{
display: inline-block;
list-style: none;
margin-right: 10px;
}
.card .top-social{position: relative;}
.card .top-social{position: relative;}
</style>
<div class="modal fade" id="edit-social-popup-box" tabindex="-1" role="dialog" aria-labelledby="slide9-popup-upload">
<div id="comment-popup-box" class="modal-dialog" role="document">
<div class="modal-content">
<div class="comment-popup-head">
<h4 class="remove-margin">Share socially...</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">x</button>
</div>
<div class="modal-body">
<!-- commment pop_up -->
<div class="comment-body">
<form id="form-post-upload" method="post" action="<?php echo base_url("profile/update_social")?>">
<div class="thumbnail">
<div class="post">
<div class="form-group">
<textarea id="content-social" name="content" class="form-control" rows="6" placeholder="What's on your mind? Share a question, post a topic, or an idea..."></textarea>
</div>
<div class="content-upload-image none">
<p class="images-post remove-margin">
<img width="100%" src="#" alt="image" id="read-image-social">
<button type="button" id="remove-image-social" class="btn btn-default btn-image">x</button>
</p>
</div>
</div>
</div>
<p class="text-right" id="max-length-content">300</p>
<div class="row">
<div class="col-sm-12">
<ul class="list-inline list-btn remove-margin"">
<li>
<div class="dropdown">
<a href="#" class="dropdown-toggle" type="button" data-toggle="dropdown"><i class="fa fa-globe "></i></a>
<ul class="dropdown-menu">
<li>
<div class="checkbox checkbox-circle">
<input checked id="data-check-public" name="public" type="radio" value="1">
<label for="data-check-public">Public</label>
</div>
</li>
<li>
<div class="checkbox checkbox-circle">
<input id="data-check-connection-only" name="public" type="radio" value="0">
<label for="data-check-connection-only">Connection only</label>
</div>
</li>
</ul>
</div>
</li>
<li>
<div class='input-group date' id='datetimepicker1'>
<input style="display: none; width: 0;" type='text' name="daytime" class="none form-control" />
<span class="input-group-addon">
<i class="fa fa-calendar" aria-hidden="true"></i>
</span>
</div>
</li>
<li><input id="file-upload-socail" style="display: none;" type="file" class="none" name="image" accept="image/*"><a onclick="$('#file-upload-socail').trigger('click'); return false;" href="#"><i class="fa fa-camera "></i></a></li>
<li><button type="button" class="btn btn-gray" data-dismiss="modal" aria-label="Close">Cancel</button></li>
<li><button type="submit" class="relative btn btn-primary">Update</button></li>
</ul>
</div>
</div>
</form>
</div>
</div>
<!-- commment pop_up -->
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo skin_url('datetimepicker/js/moment.js');?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo skin_url('datetimepicker/css/bootstrap-datetimepicker.min.css')?>">
<script type="text/javascript" src="<?php echo skin_url('datetimepicker/js/bootstrap-datetimepicker.min.js')?>"></script>
<style type="text/css">
/*slide 9 post upload image*/
#comment-popup-box{width: 450px;max-width: 100%;border-radius: 5px;box-shadow: -5px 5px 5px 0px #333;}
#comment-popup-box .close{position: relative;top: -35px;right: -5px;font-size: 20px;}
#comment-popup-box .comment-popup-head{background-color: #339999;padding: 15px;border-top-left-radius: 5px;border-top-right-radius: 5px;}
#comment-popup-box .modal-content{border: none;}
.comment-body .name, .comment-body .name:hover{color: #333;font-size: 16px;}
.comment-popup-head h4{color: #fff;}
#form-post-upload{margin: 5px 0;}
#form-post-upload .thumbnail{border: 1px solid #777;}
#form-post-upload textarea{border: none;box-shadow: none;font-size: 16px;padding: 0;}
.thumbnail .post{padding: 5px;}
.thumbnail .post p{font-size: 16px;}
.images-post{position: relative;}
.list-btn .btn-fix{font-size: 14px;font-weight: 100;margin-left: 15px;padding: 6px 12px;}
.list-btn .btn{padding:8px 16px;font-size: 16px;}
.images-post .btn-image{position: absolute;right: 0;top:-40px;color: #000;border: none;font-size: 20px;padding-top: 2px;}
.btn-primary,.btn-primary:hover,.btn-primary:focus{
background-color: #339999;
border-color: #339999;
}
.list-btn{display: inline-flex;}
.list-btn .fa{font-size: 35px;color: #ccc;}
.list-btn li{margin:3px 18px 3px 0;}
.list-btn li:last-child{margin-right: 0px;}
#datetimepicker1 .input-group-addon{border: none; padding: 0;}
#datetimepicker1 .input-group-addon .input-group{display: block;}
#edit-social-popup-box .fa-globe{font-size: 38px;}
#edit-social-popup-box .dropdown-menu{padding: 0 10px;}
#edit-social-popup-box .dropdown-menu .checkbox{padding-left: 0;}
#edit-social-popup-box .checkbox input[type="checkbox"]:checked + label::after, #edit-social-popup-box .checkbox input[type="radio"]:checked + label::after{
content: "";
top: 1px;
left: 1px;
width: 16px;
height: 16px;
}
#edit-social-popup-box #comment-popup-box .close {
position: relative;
top: -27px;
right: -5px;
font-size: 20px;
}
#form-post-upload .thumbnail.error{border:1px solid red;}
#edit-social-popup-box .loadding{position: absolute; width: 100%;cursor: wait;right: 0;top: 0;bottom: 0; text-align: center;}
#edit-social-popup-box .loadding img {max-height: 100%;max-width: 100%; margin: 0 auto;}
/*////slide 9 post upload image*/
</style>
<script type="text/javascript">
$(document).ready(function(){
var id;
$("body #delete-socail-post").click(function(){
$("#modal_delete").modal();
id = $(this).attr("data-id");
});
$("#modal_delete #ok-delete").click(function(){
$.ajax({
url : base_url + "profile/delete_socail",
type : "post",
dataType : "json",
data : {id : id},
success : function(res){
if(res["status"] == "success"){
location.reload();
}else{
alert("Error!");
}
},error : function(){
alert("Error!");
}
});
return false;
});
$("body #edit-socail-post").click(function(){
id = $(this).attr("data-id");
//get info post
$.ajax({
url : base_url + "profile/get_info_socail_post",
type : "post",
dataType : "json",
data : {id : id},
success : function (res){
if(res["status"] == "success"){
$("#edit-social-popup-box #content-social").val(res["response"]["content"]);
$("#edit-social-popup-box [name=public][value="+res["response"]["public"]+"]").prop('checked', true);
$("#edit-social-popup-box [name=daytime]").val(res["response"]["created_at"]);
if(res["response"]["thumb"] != null && res["response"]["thumb"].trim() != ""){
$("#edit-social-popup-box #read-image-social").attr("src",res["response"]["thumb"]);
$("#edit-social-popup-box .content-upload-image").removeClass("none");
}else{
$("#edit-social-popup-box .content-upload-image").addClass("none");
}
}
},error : function(){
alert("Error!")
}
})
$("#edit-social-popup-box").modal();
return false;
});
$("#edit-social-popup-box .loadding").click(function(event){
event.stopPropagation();
event.preventDefault();
return false;
});
$("#edit-social-popup-box #form-post-upload").submit(function(){
if($(this).find("#content-social").val() == null || $(this).find("#content-social").val().trim() == ""){
$(this).find(".thumbnail").addClass("error");
return false;
}
$(this).find(".thumbnail").removeClass("error");
$(this).ajaxSubmit({
beforeSubmit : function(){
$("#edit-social-popup-box #form-post-upload").find("button[type=submit]").append('<div class="loadding"><img src="<?php echo skin_url("images/loading.gif");?>"></div>');
},
dataType:"json",
data :{id : id},
success:function(res){
if(res["status"] == "success"){
location.reload();
}else{
alert("Error!");
$("#edit-social-popup-box #form-post-upload").find(".loadding").remove();
}
},
error:function(){
$("#edit-social-popup-box #form-post-upload").find(".loadding").remove();
}
});
return false;
});
$("#edit-social-popup-box #form-post-upload #file-upload-socail").change(function(){
var _this = $(this);
if ($(this)[0].files && $(this)[0].files[0]) {
var file = $(this)[0].files[0];
window.URL = window.URL || window.webkitURL;
var url = window.URL.createObjectURL(file);
$("#edit-social-popup-box .content-upload-image #read-image-social").attr("src",url);
$("#edit-social-popup-box .content-upload-image").removeClass("none");
}else{
$(this).parent().find(".box-img-select").html('');
}
return false;
});
$("#edit-social-popup-box #remove-image-social").click(function(){
var input = $("#form-post-upload #file-upload-socail");
input.replaceWith(input.val('').clone(true));
$("#edit-social-popup-box .content-upload-image").addClass("none");
$("#edit-social-popup-box .content-upload-image #read-image-social").attr("src","#");
});
$("#edit-social-popup-box #content-social").keydown(function(event){
var maxlength = 300;
var currentlength = $(this).val().length;
var cl_length = maxlength - currentlength;
$("#edit-social-popup-box #max-length-content").text(cl_length);
if(event.keyCode != 8){
if(cl_length <= 0){
event.stopPropagation();
event.preventDefault();
return false;
}
}
return true;
});
$("#edit-social-popup-box #content-social").keyup(function(event){
var maxlength = 300;
var currentlength = $(this).val().length;
var cl_length = maxlength - currentlength;
$("#edit-social-popup-box #max-length-content").text(cl_length);
if(event.keyCode != 8){
if(cl_length <= 0){
event.stopPropagation();
event.preventDefault();
return false;
}
}
return true;
});
$("#edit-social-popup-box #datetimepicker1").datetimepicker({
format :"Y/MM/DD"
});
});
</script>
|
phanquanghiep123/dezignwall
|
application/views/profile/new_images.php
|
PHP
|
apache-2.0
| 27,141
|
# vagrantpackagingscript
|
som-mishra/vagrantpackagingscript
|
README.md
|
Markdown
|
apache-2.0
| 24
|
package alicloud
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAlicloudCenBandwidthPackage_importBasic(t *testing.T) {
resourceName := "alicloud_cen_bandwidth_package.foo"
ignoreFields := []string{"period"}
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCenBandwidthPackageDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCenBandwidthPackageConfig,
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: ignoreFields,
},
},
})
}
|
xiaozhu36/terraform-provider
|
alicloud/import_alicloud_cen_bandwidth_package_test.go
|
GO
|
apache-2.0
| 725
|
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "ManualBindings.h"
#undef TOLUA_TEMPLATE_BIND
#include <sstream>
#include <iomanip>
#include <array>
#include "tolua++/include/tolua++.h"
#include "polarssl/md5.h"
#include "polarssl/sha1.h"
#include "PluginLua.h"
#include "PluginManager.h"
#include "LuaWindow.h"
#include "../Root.h"
#include "../World.h"
#include "../Entities/Player.h"
#include "../WebAdmin.h"
#include "../ClientHandle.h"
#include "../BlockArea.h"
#include "../BlockEntities/BeaconEntity.h"
#include "../BlockEntities/BrewingstandEntity.h"
#include "../BlockEntities/ChestEntity.h"
#include "../BlockEntities/CommandBlockEntity.h"
#include "../BlockEntities/DispenserEntity.h"
#include "../BlockEntities/DropperEntity.h"
#include "../BlockEntities/FurnaceEntity.h"
#include "../BlockEntities/HopperEntity.h"
#include "../BlockEntities/NoteEntity.h"
#include "../BlockEntities/MobHeadEntity.h"
#include "../BlockEntities/FlowerPotEntity.h"
#include "../Generating/ChunkDesc.h"
#include "../LineBlockTracer.h"
#include "../WorldStorage/SchematicFileSerializer.h"
#include "../CompositeChat.h"
#include "../StringCompression.h"
#include "../CommandOutput.h"
#include "../BuildInfo.h"
#include "../HTTP/UrlParser.h"
#include "../BoundingBox.h"
////////////////////////////////////////////////////////////////////////////////
// LuaCommandHandler:
/** Defines a bridge between cPluginManager::cCommandHandler and cLuaState::cCallback. */
class LuaCommandHandler:
public cPluginManager::cCommandHandler
{
public:
LuaCommandHandler(cLuaState::cCallbackPtr && a_Callback):
m_Callback(std::move(a_Callback))
{
}
virtual bool ExecuteCommand(
const AStringVector & a_Split,
cPlayer * a_Player,
const AString & a_Command,
cCommandOutputCallback * a_Output
) override
{
bool res = false;
AString s;
if (!m_Callback->Call(a_Split, a_Player, a_Command, cLuaState::Return, res, s))
{
return false;
}
if (res && (a_Output != nullptr) && !s.empty())
{
a_Output->Out(s);
}
return res;
}
protected:
cLuaState::cCallbackPtr m_Callback;
};
////////////////////////////////////////////////////////////////////////////////
// cManualBindings:
// Better error reporting for Lua
int cManualBindings::tolua_do_error(lua_State * L, const char * a_pMsg, tolua_Error * a_pToLuaError)
{
// Retrieve current function name
lua_Debug entry;
VERIFY(lua_getstack(L, 0, &entry));
VERIFY(lua_getinfo(L, "n", &entry));
// Insert function name into error msg
AString msg(a_pMsg);
ReplaceString(msg, "#funcname#", entry.name?entry.name:"?");
// Send the error to Lua
tolua_error(L, msg.c_str(), a_pToLuaError);
return 0;
}
int cManualBindings::lua_do_error(lua_State * L, const char * a_pFormat, ...)
{
// Retrieve current function name
lua_Debug entry;
VERIFY(lua_getstack(L, 0, &entry));
VERIFY(lua_getinfo(L, "n", &entry));
// Insert function name into error msg
AString msg(a_pFormat);
ReplaceString(msg, "#funcname#", (entry.name != nullptr) ? entry.name : "?");
// Copied from luaL_error and modified
va_list argp;
va_start(argp, a_pFormat);
luaL_where(L, 1);
lua_pushvfstring(L, msg.c_str(), argp);
va_end(argp);
lua_concat(L, 2);
return lua_error(L);
}
// Lua bound functions with special return types
static int tolua_Clamp(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int NumArgs = lua_gettop(LuaState);
if (NumArgs != 3)
{
return cManualBindings::lua_do_error(LuaState, "Error in function call '#funcname#': Requires 3 arguments, got %i", NumArgs);
}
if (!lua_isnumber(LuaState, 1) || !lua_isnumber(LuaState, 2) || !lua_isnumber(LuaState, 3))
{
return cManualBindings::lua_do_error(LuaState, "Error in function call '#funcname#': Expected a number for parameters #1, #2 and #3");
}
lua_Number Number = tolua_tonumber(LuaState, 1, 0);
lua_Number Min = tolua_tonumber(LuaState, 2, 0);
lua_Number Max = tolua_tonumber(LuaState, 3, 0);
lua_Number Result = Clamp(Number, Min, Max);
LuaState.Push(Result);
return 1;
}
static int tolua_CompressStringZLIB(lua_State * tolua_S)
{
cLuaState S(tolua_S);
if (
!S.CheckParamString(1) ||
(
!S.CheckParamNumber(2) &&
!S.CheckParamEnd(2)
)
)
{
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// Get the params:
AString ToCompress;
int CompressionLevel = 5;
S.GetStackValues(1, ToCompress, CompressionLevel);
// Compress the string:
AString res;
CompressString(ToCompress.data(), ToCompress.size(), res, CompressionLevel);
S.Push(res);
return 1;
}
static int tolua_UncompressStringZLIB(lua_State * tolua_S)
{
cLuaState S(tolua_S);
if (
!S.CheckParamString(1) ||
!S.CheckParamNumber(2)
)
{
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// Get the params:
AString ToUncompress;
size_t UncompressedSize = 0;
S.GetStackValues(1, ToUncompress, UncompressedSize);
// Compress the string:
AString res;
UncompressString(ToUncompress.data(), ToUncompress.size(), res, UncompressedSize);
S.Push(res);
return 1;
}
static int tolua_CompressStringGZIP(lua_State * tolua_S)
{
cLuaState S(tolua_S);
if (
!S.CheckParamString(1) ||
!S.CheckParamEnd(2)
)
{
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// Get the params:
AString ToCompress;
S.GetStackValues(1, ToCompress);
// Compress the string:
AString res;
CompressStringGZIP(ToCompress.data(), ToCompress.size(), res);
S.Push(res);
return 1;
}
static int tolua_UncompressStringGZIP(lua_State * tolua_S)
{
cLuaState S(tolua_S);
if (
!S.CheckParamString(1) ||
!S.CheckParamEnd(2)
)
{
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// Get the params:
AString ToUncompress;
S.GetStackValues(1, ToUncompress);
// Compress the string:
AString res;
UncompressStringGZIP(ToUncompress.data(), ToUncompress.size(), res);
S.Push(res);
return 1;
}
static int tolua_InflateString(lua_State * tolua_S)
{
cLuaState S(tolua_S);
if (
!S.CheckParamString(1) ||
!S.CheckParamEnd(2)
)
{
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// Get the params:
AString ToUncompress;
S.GetStackValues(1, ToUncompress);
// Compress the string:
AString res;
InflateString(ToUncompress.data(), ToUncompress.size(), res);
S.Push(res);
return 1;
}
static int tolua_StringSplit(lua_State * tolua_S)
{
// Get the params:
cLuaState LuaState(tolua_S);
AString str, delim;
LuaState.GetStackValues(1, str, delim);
// Execute and push the result:
LuaState.Push(StringSplit(str, delim));
return 1;
}
static int tolua_StringSplitWithQuotes(lua_State * tolua_S)
{
cLuaState S(tolua_S);
AString str;
AString delim;
S.GetStackValues(1, str, delim);
AStringVector Split = StringSplitWithQuotes(str, delim);
S.Push(Split);
return 1;
}
static int tolua_StringSplitAndTrim(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamString(1, 2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Process:
AString str, delim;
L.GetStackValues(1, str, delim);
L.Push(StringSplitAndTrim(str, delim));
return 1;
}
/** Retrieves the log message from the first param on the Lua stack.
Can take either a string or a cCompositeChat.
*/
static AString GetLogMessage(lua_State * tolua_S)
{
tolua_Error err;
if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err))
{
return reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr))->ExtractText();
}
else
{
size_t len = 0;
const char * str = lua_tolstring(tolua_S, 1, &len);
if (str != nullptr)
{
return AString(str, len);
}
}
return "";
}
static int tolua_LOG(lua_State * tolua_S)
{
// If there's no param, spit out an error message instead of crashing:
if (lua_isnil(tolua_S, 1))
{
LOGWARNING("Attempting to LOG a nil value!");
cLuaState::LogStackTrace(tolua_S);
return 0;
}
// If the param is a cCompositeChat, read the log level from it:
cLogger::eLogLevel LogLevel = cLogger::llRegular;
tolua_Error err;
if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err))
{
LogLevel = cCompositeChat::MessageTypeToLogLevel(reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr))->GetMessageType());
}
// Log the message:
cLogger::GetInstance().LogSimple(GetLogMessage(tolua_S).c_str(), LogLevel);
return 0;
}
static int tolua_LOGINFO(lua_State * tolua_S)
{
// If there's no param, spit out an error message instead of crashing:
if (lua_isnil(tolua_S, 1))
{
LOGWARNING("Attempting to LOGINFO a nil value!");
cLuaState::LogStackTrace(tolua_S);
return 0;
}
cLogger::GetInstance().LogSimple(GetLogMessage(tolua_S).c_str(), cLogger::llInfo);
return 0;
}
static int tolua_LOGWARN(lua_State * tolua_S)
{
// If there's no param, spit out an error message instead of crashing:
if (lua_isnil(tolua_S, 1))
{
LOGWARNING("Attempting to LOGWARN a nil value!");
cLuaState::LogStackTrace(tolua_S);
return 0;
}
cLogger::GetInstance().LogSimple(GetLogMessage(tolua_S).c_str(), cLogger::llWarning);
return 0;
}
static int tolua_LOGERROR(lua_State * tolua_S)
{
// If there's no param, spit out an error message instead of crashing:
if (lua_isnil(tolua_S, 1))
{
LOGWARNING("Attempting to LOGERROR a nil value!");
cLuaState::LogStackTrace(tolua_S);
return 0;
}
cLogger::GetInstance().LogSimple(GetLogMessage(tolua_S).c_str(), cLogger::llError);
return 0;
}
static int tolua_Base64Encode(lua_State * tolua_S)
{
cLuaState L(tolua_S);
if (
!L.CheckParamString(1) ||
!L.CheckParamEnd(2)
)
{
return 0;
}
AString Src;
L.GetStackValue(1, Src);
AString res = Base64Encode(Src);
L.Push(res);
return 1;
}
static int tolua_Base64Decode(lua_State * tolua_S)
{
cLuaState L(tolua_S);
if (
!L.CheckParamString(1) ||
!L.CheckParamEnd(2)
)
{
return 0;
}
AString Src;
L.GetStackValue(1, Src);
AString res = Base64Decode(Src);
L.Push(res);
return 1;
}
cPluginLua * cManualBindings::GetLuaPlugin(lua_State * L)
{
// Get the plugin identification out of LuaState:
lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME);
if (!lua_islightuserdata(L, -1))
{
LOGWARNING("%s: cannot get plugin instance, what have you done to my Lua state?", __FUNCTION__);
lua_pop(L, 1);
return nullptr;
}
cPluginLua * Plugin = reinterpret_cast<cPluginLua *>(const_cast<void*>(lua_topointer(L, -1)));
lua_pop(L, 1);
return Plugin;
}
static int tolua_cFile_ChangeFileExt(lua_State * tolua_S)
{
// API signature:
// ChangeFileExt(string, string) -> string
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2, 3) ||
!L.CheckParamEnd(4)
)
{
return 0;
}
// Execute:
AString FileName, NewExt;
VERIFY(L.GetStackValues(2, FileName, NewExt));
L.Push(cFile::ChangeFileExt(FileName, NewExt));
return 1;
}
static int tolua_cFile_Copy(lua_State * tolua_S)
{
// API signature:
// cFile:Copy(string, string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2, 3) ||
!L.CheckParamEnd(4)
)
{
return 0;
}
// Execute:
AString SrcFile, DstFile;
VERIFY(L.GetStackValues(2, SrcFile, DstFile));
L.Push(cFile::Copy(SrcFile, DstFile));
return 1;
}
static int tolua_cFile_CreateFolder(lua_State * tolua_S)
{
// API signature:
// cFile:CreateFolder(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString FolderPath;
VERIFY(L.GetStackValues(2, FolderPath));
L.Push(cFile::CreateFolder(FolderPath));
return 1;
}
static int tolua_cFile_CreateFolderRecursive(lua_State * tolua_S)
{
// API signature:
// cFile:CreateFolderRecursive(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString FolderPath;
VERIFY(L.GetStackValues(2, FolderPath));
L.Push(cFile::CreateFolderRecursive(FolderPath));
return 1;
}
static int tolua_cFile_Delete(lua_State * tolua_S)
{
// API signature:
// cFile:Delete(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::Delete(Path));
return 1;
}
static int tolua_cFile_DeleteFile(lua_State * tolua_S)
{
// API signature:
// cFile:DeleteFile(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::DeleteFile(Path));
return 1;
}
static int tolua_cFile_DeleteFolder(lua_State * tolua_S)
{
// API signature:
// cFile:DeleteFolder(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::DeleteFolder(Path));
return 1;
}
static int tolua_cFile_DeleteFolderContents(lua_State * tolua_S)
{
// API signature:
// cFile:DeleteFolderContents(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::DeleteFolderContents(Path));
return 1;
}
static int tolua_cFile_Exists(lua_State * tolua_S)
{
// API signature:
// cFile:Exists(string) -> bool
// Obsolete, use IsFile() or IsFolder() instead
cLuaState L(tolua_S);
LOGWARNING("cFile:Exists() is obsolete, use cFile:IsFolder() or cFile:IsFile() instead!");
L.LogStackTrace();
// Check params:
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::Exists(Path));
return 1;
}
static int tolua_cFile_GetFolderContents(lua_State * tolua_S)
{
// API signature:
// cFile:GetFolderContents(string) -> {string, string, ...}
// Check params:
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserTable(1, "cFile") ||
!LuaState.CheckParamString (2) ||
!LuaState.CheckParamEnd (3)
)
{
return 0;
}
// Get params:
AString Folder;
VERIFY(LuaState.GetStackValues(2, Folder));
// Execute and push result:
LuaState.Push(cFile::GetFolderContents(Folder));
return 1;
}
static int tolua_cFile_GetLastModificationTime(lua_State * tolua_S)
{
// API signature:
// cFile:GetLastModificationTime(string) -> number
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::GetLastModificationTime(Path));
return 1;
}
static int tolua_cFile_GetSize(lua_State * tolua_S)
{
// API signature:
// cFile:GetSize(string) -> number
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::GetSize(Path));
return 1;
}
static int tolua_cFile_IsFile(lua_State * tolua_S)
{
// API signature:
// cFile:IsFile(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::IsFile(Path));
return 1;
}
static int tolua_cFile_IsFolder(lua_State * tolua_S)
{
// API signature:
// cFile:IsFolder(string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Execute:
AString Path;
VERIFY(L.GetStackValues(2, Path));
L.Push(cFile::IsFolder(Path));
return 1;
}
static int tolua_cFile_ReadWholeFile(lua_State * tolua_S)
{
// API signature:
// cFile:ReadWholeFile(string) -> string
// Check params:
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserTable(1, "cFile") ||
!LuaState.CheckParamString (2) ||
!LuaState.CheckParamEnd (3)
)
{
return 0;
}
// Get params:
AString FileName;
VERIFY(LuaState.GetStackValues(2, FileName));
// Execute and push result:
LuaState.Push(cFile::ReadWholeFile(FileName));
return 1;
}
static int tolua_cFile_Rename(lua_State * tolua_S)
{
// API signature:
// cFile:Rename(string, string) -> bool
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cFile") ||
!L.CheckParamString(2, 3) ||
!L.CheckParamEnd(4)
)
{
return 0;
}
// Execute:
AString SrcPath, DstPath;
VERIFY(L.GetStackValues(2, SrcPath, DstPath));
L.Push(cFile::Rename(SrcPath, DstPath));
return 1;
}
static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S)
{
// API function no longer available:
LOGWARNING("cPluginManager:GetAllPlugins() is no longer available, use cPluginManager:ForEachPlugin() instead");
cLuaState::LogStackTrace(tolua_S);
// Return an empty table:
lua_newtable(tolua_S);
return 1;
}
static int tolua_cPluginManager_GetCurrentPlugin(lua_State * S)
{
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(S);
if (Plugin == nullptr)
{
// An error message has already been printed in GetLuaPlugin()
return 0;
}
tolua_pushusertype(S, Plugin, "cPluginLua");
return 1;
}
static int tolua_cPluginManager_GetPlugin(lua_State * tolua_S)
{
// API function no longer available:
LOGWARNING("cPluginManager:GetPlugin() is no longer available. Use cPluginManager:DoWithPlugin() or cPluginManager:CallPlugin() instead.");
cLuaState::LogStackTrace(tolua_S);
return 0;
}
static int tolua_cPluginManager_LogStackTrace(lua_State * S)
{
cLuaState::LogStackTrace(S);
return 0;
}
static int tolua_cPluginManager_AddHook_FnRef(cPluginManager * a_PluginManager, cLuaState & S, int a_ParamIdx)
{
// Helper function for cPluginmanager:AddHook() binding
// Takes care of the new case (#121): args are HOOK_TYPE and CallbackFunction
// The arg types have already been checked
// Retrieve the cPlugin from the LuaState:
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(S);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
return 0;
}
// Retrieve and check the hook type
int HookType;
if (!S.GetStackValue(a_ParamIdx, HookType))
{
LOGWARNING("cPluginManager.AddHook(): Cannot read the hook type.");
S.LogStackTrace();
return 0;
}
if (!a_PluginManager->IsValidHookType(HookType))
{
LOGWARNING("cPluginManager.AddHook(): Invalid HOOK_TYPE parameter: %d", HookType);
S.LogStackTrace();
return 0;
}
// Add the hook to the plugin
cLuaState::cCallbackPtr callback;
if (!S.GetStackValue(a_ParamIdx + 1, callback))
{
LOGWARNING("cPluginManager.AddHook(): Cannot read the callback parameter");
S.LogStackTrace();
return 0;
}
if (!Plugin->AddHookCallback(HookType, std::move(callback)))
{
LOGWARNING("cPluginManager.AddHook(): Cannot add hook %d, unknown error.", HookType);
S.LogStackTrace();
return 0;
}
a_PluginManager->AddHook(Plugin, HookType);
// Success
return 0;
}
static int tolua_cPluginManager_AddHook_DefFn(cPluginManager * a_PluginManager, cLuaState & S, int a_ParamIdx)
{
// Helper function for cPluginmanager:AddHook() binding
// Takes care of the old case (#121): args are cPluginLua and HOOK_TYPE
// The arg types have already been checked
// Retrieve and check the cPlugin parameter
cPluginLua * Plugin = reinterpret_cast<cPluginLua *>(tolua_tousertype(S, a_ParamIdx, nullptr));
if (Plugin == nullptr)
{
LOGWARNING("cPluginManager.AddHook(): Invalid Plugin parameter, expected a valid cPlugin object. Hook not added");
S.LogStackTrace();
return 0;
}
if (Plugin != cManualBindings::GetLuaPlugin(S))
{
// The plugin parameter passed to us is not our stored plugin. Disallow this!
LOGWARNING("cPluginManager.AddHook(): Invalid Plugin parameter, cannot add hook to foreign plugins. Hook not added.");
S.LogStackTrace();
return 0;
}
// Retrieve and check the hook type
int HookType = static_cast<int>(tolua_tonumber(S, a_ParamIdx + 1, -1));
if (!a_PluginManager->IsValidHookType(HookType))
{
LOGWARNING("cPluginManager.AddHook(): Invalid HOOK_TYPE parameter: %d", HookType);
S.LogStackTrace();
return 0;
}
// Get the standard name for the callback function:
const char * FnName = cPluginLua::GetHookFnName(HookType);
if (FnName == nullptr)
{
LOGWARNING("cPluginManager.AddHook(): Unknown hook type (%d). Hook not added.", HookType);
S.LogStackTrace();
return 0;
}
// Retrieve the function to call and add it to the plugin:
cLuaState::cCallbackPtr callback;
lua_getglobal(S, FnName);
bool res = S.GetStackValue(-1, callback);
lua_pop(S, 1);
if (!res || !callback->IsValid())
{
LOGWARNING("cPluginManager.AddHook(): Function %s not found. Hook not added.", FnName);
S.LogStackTrace();
return 0;
}
a_PluginManager->AddHook(Plugin, HookType);
// Success
return 0;
}
static int tolua_cPluginManager_AddHook(lua_State * tolua_S)
{
/*
Function signatures:
cPluginManager:AddHook(HOOK_TYPE, CallbackFunction) -- (1) recommended
cPluginManager.AddHook(HOOK_TYPE, CallbackFunction) -- (2) accepted silently (#401 deprecates this)
cPluginManager:Get():AddHook(HOOK_TYPE, CallbackFunction) -- (3) accepted silently
cPluginManager:Get():AddHook(Plugin, HOOK_TYPE) -- (4) old style (#121), accepted but complained about in the console
cPluginManager.AddHook(Plugin, HOOK_TYPE) -- (5) old style (#121) mangled, accepted but complained about in the console
*/
cLuaState S(tolua_S);
cPluginManager * PlgMgr = cPluginManager::Get();
// If the first param is a cPluginManager instance, use it instead of the global one:
int ParamIdx = 1;
tolua_Error err;
if (tolua_isusertype(S, 1, "cPluginManager", 0, &err))
{
// Style 2 or 3, retrieve the PlgMgr instance
PlgMgr = reinterpret_cast<cPluginManager *>(tolua_tousertype(S, 1, nullptr));
if (PlgMgr == nullptr)
{
LOGWARNING("Malformed plugin, use cPluginManager.AddHook(HOOK_TYPE, CallbackFunction). Fixing the call for you.");
S.LogStackTrace();
PlgMgr = cPluginManager::Get();
}
ParamIdx += 1;
}
else if (tolua_isusertable(S, 1, "cPluginManager", 0, &err))
{
// Style 1, use the global PlgMgr, but increment ParamIdx
ParamIdx++;
}
if (lua_isnumber(S, ParamIdx) && lua_isfunction(S, ParamIdx + 1))
{
// The next params are a number and a function, assume style 1 or 2
return tolua_cPluginManager_AddHook_FnRef(PlgMgr, S, ParamIdx);
}
else if (tolua_isusertype(S, ParamIdx, "cPlugin", 0, &err) && lua_isnumber(S, ParamIdx + 1))
{
// The next params are a cPlugin and a number, assume style 3 or 4
LOGINFO("cPluginManager.AddHook(): Deprecated format used, use cPluginManager.AddHook(HOOK_TYPE, CallbackFunction) instead. Fixing the call for you.");
S.LogStackTrace();
return tolua_cPluginManager_AddHook_DefFn(PlgMgr, S, ParamIdx);
}
AString ParamDesc;
Printf(ParamDesc, "%s, %s, %s", S.GetTypeText(1).c_str(), S.GetTypeText(2).c_str(), S.GetTypeText(3).c_str());
LOGWARNING("cPluginManager:AddHook(): bad parameters. Expected HOOK_TYPE and CallbackFunction, got %s. Hook not added.", ParamDesc.c_str());
S.LogStackTrace();
return 0;
}
static int tolua_cPluginManager_ForEachCommand(lua_State * tolua_S)
{
/*
Function signature:
cPluginManager:Get():ForEachCommand(a_CallbackFn) -> bool
*/
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cPluginManager") ||
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
cLuaState::cRef FnRef;
L.GetStackValues(2, FnRef);
if (!FnRef.IsValid())
{
LOGWARN("Error in function call 'ForEachCommand': Could not get function reference of parameter #1");
return 0;
}
// Callback for enumerating all commands:
class cLuaCallback : public cPluginManager::cCommandEnumCallback
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override
{
UNUSED(a_Plugin);
bool ret = false;
m_LuaState.Call(m_FnRef, a_Command, a_Permission, a_HelpString, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Execute and push the returned value:
L.Push(cPluginManager::Get()->ForEachCommand(Callback));
return 1;
}
static int tolua_cPluginManager_ForEachConsoleCommand(lua_State * tolua_S)
{
/*
Function signature:
cPluginManager:Get():ForEachConsoleCommand(a_CallbackFn) -> bool
*/
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cPluginManager") ||
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
cLuaState::cRef FnRef;
L.GetStackValues(2, FnRef);
if (!FnRef.IsValid())
{
LOGWARN("Error in function call 'ForEachConsoleCommand': Could not get function reference of parameter #1");
return 0;
}
// Callback for enumerating all commands:
class cLuaCallback : public cPluginManager::cCommandEnumCallback
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override
{
UNUSED(a_Plugin);
UNUSED(a_Permission);
bool ret = false;
m_LuaState.Call(m_FnRef, a_Command, a_HelpString, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Execute and push the returned value:
L.Push(cPluginManager::Get()->ForEachConsoleCommand(Callback));
return 1;
}
static int tolua_cPluginManager_BindCommand(lua_State * a_LuaState)
{
/* Function signatures:
cPluginManager:Get():BindCommand(Command, Permission, Function, HelpString) -- regular
cPluginManager:BindCommand(Command, Permission, Function, HelpString) -- static
cPluginManager.BindCommand(Command, Permission, Function, HelpString) -- without the "self" param
*/
cLuaState L(a_LuaState);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
return 0;
}
// Read the arguments to this API call:
tolua_Error tolua_err;
int idx = 1;
if (
tolua_isusertype (L, 1, "cPluginManager", 0, &tolua_err) ||
tolua_isusertable(L, 1, "cPluginManager", 0, &tolua_err)
)
{
idx++;
}
if (
!tolua_iscppstring(L, idx, 0, &tolua_err) ||
!tolua_iscppstring(L, idx + 1, 0, &tolua_err) ||
!tolua_iscppstring(L, idx + 3, 0, &tolua_err) ||
!tolua_isnoobj (L, idx + 4, &tolua_err)
)
{
tolua_error(L, "#ferror in function 'BindCommand'.", &tolua_err);
return 0;
}
if (!lua_isfunction(L, idx + 2))
{
luaL_error(L, "\"BindCommand\" function expects a function as its 3rd parameter. Command-binding aborted.");
return 0;
}
cPluginManager * self = cPluginManager::Get();
AString Command, Permission, HelpString;
cLuaState::cCallbackPtr Handler;
L.GetStackValues(idx, Command, Permission, Handler, HelpString);
if (!Handler->IsValid())
{
LOGERROR("\"BindCommand\": Cannot create a function reference. Command \"%s\" not bound.", Command.c_str());
return 0;
}
auto CommandHandler = std::make_shared<LuaCommandHandler>(std::move(Handler));
if (!self->BindCommand(Command, Plugin, CommandHandler, Permission, HelpString))
{
// Refused. Possibly already bound. Error message has been given, display the callstack:
L.LogStackTrace();
return 0;
}
L.Push(true);
return 1;
}
static int tolua_cPluginManager_BindConsoleCommand(lua_State * a_LuaState)
{
/* Function signatures:
cPluginManager:Get():BindConsoleCommand(Command, Function, HelpString) -- regular
cPluginManager:BindConsoleCommand(Command, Function, HelpString) -- static
cPluginManager.BindConsoleCommand(Command, Function, HelpString) -- without the "self" param
*/
// Get the plugin identification out of LuaState:
cLuaState L(a_LuaState);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
return 0;
}
// Read the arguments to this API call:
tolua_Error tolua_err;
int idx = 1;
if (
tolua_isusertype(L, 1, "cPluginManager", 0, &tolua_err) ||
tolua_isusertable(L, 1, "cPluginManager", 0, &tolua_err)
)
{
idx++;
}
if (
!tolua_iscppstring(L, idx, 0, &tolua_err) || // Command
!tolua_iscppstring(L, idx + 2, 0, &tolua_err) || // HelpString
!tolua_isnoobj (L, idx + 3, &tolua_err)
)
{
tolua_error(L, "#ferror in function 'BindConsoleCommand'.", &tolua_err);
return 0;
}
if (!lua_isfunction(L, idx + 1))
{
luaL_error(L, "\"BindConsoleCommand\" function expects a function as its 2nd parameter. Command-binding aborted.");
return 0;
}
cPluginManager * self = cPluginManager::Get();
AString Command, HelpString;
cLuaState::cCallbackPtr Handler;
L.GetStackValues(idx, Command, Handler, HelpString);
if (!Handler->IsValid())
{
LOGERROR("\"BindConsoleCommand\": Cannot create a function reference. Console command \"%s\" not bound.", Command.c_str());
return 0;
}
auto CommandHandler = std::make_shared<LuaCommandHandler>(std::move(Handler));
if (!self->BindConsoleCommand(Command, Plugin, CommandHandler, HelpString))
{
// Refused. Possibly already bound. Error message has been given, display the callstack:
L.LogStackTrace();
return 0;
}
L.Push(true);
return 1;
}
static int tolua_cPluginManager_CallPlugin(lua_State * tolua_S)
{
/*
Function signature:
cPluginManager:CallPlugin("PluginName", "FunctionName", args...)
*/
// Check the parameters:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cPluginManager") ||
!L.CheckParamString(2, 3))
{
return 0;
}
// Retrieve the plugin name and function name
AString PluginName, FunctionName;
L.ToString(2, PluginName);
L.ToString(3, FunctionName);
if (PluginName.empty() || FunctionName.empty())
{
LOGWARNING("cPluginManager:CallPlugin(): Invalid plugin name or function name");
L.LogStackTrace();
return 0;
}
// If requesting calling the current plugin, refuse:
cPluginLua * ThisPlugin = cManualBindings::GetLuaPlugin(L);
if (ThisPlugin == nullptr)
{
return 0;
}
if (ThisPlugin->GetName() == PluginName)
{
LOGWARNING("cPluginManager::CallPlugin(): Calling self is not implemented (why would it?)");
L.LogStackTrace();
return 0;
}
// Call the destination plugin using a plugin callback:
class cCallback :
public cPluginManager::cPluginCallback
{
public:
int m_NumReturns;
cCallback(const AString & a_FunctionName, cLuaState & a_SrcLuaState) :
m_NumReturns(0),
m_FunctionName(a_FunctionName),
m_SrcLuaState(a_SrcLuaState)
{
}
protected:
const AString & m_FunctionName;
cLuaState & m_SrcLuaState;
virtual bool Item(cPlugin * a_Plugin) override
{
if (!a_Plugin->IsLoaded())
{
return false;
}
m_NumReturns = static_cast<cPluginLua *>(a_Plugin)->CallFunctionFromForeignState(
m_FunctionName, m_SrcLuaState, 4, lua_gettop(m_SrcLuaState)
);
return true;
}
} Callback(FunctionName, L);
if (!cPluginManager::Get()->DoWithPlugin(PluginName, Callback))
{
return 0;
}
if (Callback.m_NumReturns < 0)
{
// The call has failed, there are zero return values. Do NOT return negative number (Lua considers that a "yield")
return 0;
}
return Callback.m_NumReturns;
}
static int tolua_cPluginManager_ExecuteConsoleCommand(lua_State * tolua_S)
{
/*
Function signature:
cPluginManager:ExecuteConsoleCommand(EntireCommandStr) -> OutputString
*/
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cPluginManager") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
AString Command;
L.GetStackValues(2, Command);
auto Split = StringSplit(Command, " ");
// Store the command output in a string:
cStringAccumCommandOutputCallback CommandOutput;
L.Push(cPluginManager::Get()->ExecuteConsoleCommand(Split, CommandOutput, Command));
L.Push(CommandOutput.GetAccum());
return 2;
}
static int tolua_cPluginManager_FindPlugins(lua_State * tolua_S)
{
// API function no longer exists:
LOGWARNING("cPluginManager:FindPlugins() is obsolete, use cPluginManager:RefreshPluginList() instead!");
cLuaState::LogStackTrace(tolua_S);
// Still, do the actual work performed by the API function when it existed:
cPluginManager::Get()->RefreshPluginList();
return 0;
}
static int tolua_cPlayer_GetPermissions(lua_State * tolua_S)
{
// Function signature: cPlayer:GetPermissions() -> {permissions-array}
// Check the params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cPlayer") ||
!L.CheckParamEnd (2)
)
{
return 0;
}
// Get the params:
cPlayer * self = reinterpret_cast<cPlayer *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
LOGWARNING("%s: invalid self (%p)", __FUNCTION__, static_cast<void *>(self));
return 0;
}
// Push the permissions:
L.Push(self->GetPermissions());
return 1;
}
static int tolua_cPlayer_GetRestrictions(lua_State * tolua_S)
{
// Function signature: cPlayer:GetRestrictions() -> {restrictions-array}
// Check the params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cPlayer") ||
!L.CheckParamEnd (2)
)
{
return 0;
}
// Get the params:
cPlayer * self = reinterpret_cast<cPlayer *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
LOGWARNING("%s: invalid self (%p)", __FUNCTION__, static_cast<void *>(self));
return 0;
}
// Push the permissions:
L.Push(self->GetRestrictions());
return 1;
}
static int tolua_cPlayer_PermissionMatches(lua_State * tolua_S)
{
// Function signature: cPlayer:PermissionMatches(PermissionStr, TemplateStr) -> bool
// Check the params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cPlayer") ||
!L.CheckParamString (2, 3) ||
!L.CheckParamEnd (4)
)
{
return 0;
}
// Get the params:
AString Permission, Template;
L.GetStackValues(2, Permission, Template);
// Push the result of the match:
L.Push(cPlayer::PermissionMatches(StringSplit(Permission, "."), StringSplit(Template, ".")));
return 1;
}
template <
class OBJTYPE,
void (OBJTYPE::*SetCallback)(cLuaState::cCallbackPtr && a_CallbackFn)
>
static int tolua_SetObjectCallback(lua_State * tolua_S)
{
// Function signature: OBJTYPE:SetWhateverCallback(CallbackFunction)
// Get the parameters - self and the function reference:
cLuaState L(tolua_S);
OBJTYPE * self;
cLuaState::cCallbackPtr callback;
if (!L.GetStackValues(1, self, callback))
{
LOGWARNING("%s: Cannot get parameters", __FUNCTION__);
L.LogStackTrace();
return 0;
}
// Set the callback
(self->*SetCallback)(std::move(callback));
return 0;
}
// Callback class used for the WebTab:
class cWebTabCallback:
public cWebAdmin::cWebTabCallback
{
public:
/** The Lua callback to call to generate the page contents. */
cLuaState::cCallback m_Callback;
virtual bool Call(
const HTTPRequest & a_Request,
const AString & a_UrlPath,
AString & a_Content,
AString & a_ContentType
) override
{
AString content, contentType;
return m_Callback.Call(&a_Request, a_UrlPath, cLuaState::Return, a_Content, a_ContentType);
}
};
static int tolua_cPluginLua_AddWebTab(lua_State * tolua_S)
{
// OBSOLETE, use cWebAdmin:AddWebTab() instead!
// Function signature:
// cPluginLua:AddWebTab(Title, CallbackFn, [UrlPath])
// TODO: Warn about obsolete API usage
// Only implement after merging the new API change and letting some time for changes in the plugins
// Check params:
cLuaState LuaState(tolua_S);
cPluginLua * self = cManualBindings::GetLuaPlugin(tolua_S);
if (self == nullptr)
{
return 0;
}
if (
!LuaState.CheckParamString(2) ||
!LuaState.CheckParamFunction(3) ||
// Optional string as param 4
!LuaState.CheckParamEnd(5)
)
{
return 0;
}
// Read the params:
AString title, urlPath;
auto callback = std::make_shared<cWebTabCallback>();
if (!LuaState.GetStackValues(2, title, callback->m_Callback))
{
LOGWARNING("cPlugin:AddWebTab(): Cannot read required parameters");
return 0;
}
if (!LuaState.GetStackValue(4, urlPath))
{
urlPath = cWebAdmin::GetURLEncodedString(title);
}
cRoot::Get()->GetWebAdmin()->AddWebTab(title, urlPath, self->GetName(), callback);
return 0;
}
static int tolua_cPlugin_GetDirectory(lua_State * tolua_S)
{
cLuaState L(tolua_S);
// Log the obsoletion warning:
LOGWARNING("cPlugin:GetDirectory() is obsolete, use cPlugin:GetFolderName() instead.");
L.LogStackTrace();
// Retrieve the params:
cPlugin * Plugin = static_cast<cPluginLua *>(tolua_tousertype(tolua_S, 1, nullptr));
// Get the folder name:
L.Push(Plugin->GetFolderName());
return 1;
}
static int tolua_cPlugin_GetLocalDirectory(lua_State * tolua_S)
{
cLuaState L(tolua_S);
// Log the obsoletion warning:
LOGWARNING("cPlugin:GetLocalDirectory() is obsolete, use cPlugin:GetLocalFolder() instead.");
L.LogStackTrace();
// Retrieve the params:
cPlugin * Plugin = static_cast<cPluginLua *>(tolua_tousertype(tolua_S, 1, nullptr));
// Get the folder:
L.Push(Plugin->GetLocalFolder());
return 1;
}
static int tolua_md5(lua_State * tolua_S)
{
// Calculate the raw md5 checksum byte array:
unsigned char Output[16];
size_t len = 0;
const unsigned char * SourceString = reinterpret_cast<const unsigned char *>(lua_tolstring(tolua_S, 1, &len));
if (SourceString == nullptr)
{
return 0;
}
md5(SourceString, len, Output);
lua_pushlstring(tolua_S, reinterpret_cast<const char *>(Output), ARRAYCOUNT(Output));
return 1;
}
/** Does the same as tolua_md5, but reports that the usage is obsolete and the plugin should use cCrypto.md5(). */
static int tolua_md5_obsolete(lua_State * tolua_S)
{
LOGWARNING("Using md5() is obsolete, please change your plugin to use cCryptoHash.md5()");
cLuaState::LogStackTrace(tolua_S);
return tolua_md5(tolua_S);
}
static int tolua_md5HexString(lua_State * tolua_S)
{
// Calculate the raw md5 checksum byte array:
unsigned char md5Output[16];
size_t len = 0;
const unsigned char * SourceString = reinterpret_cast<const unsigned char *>(lua_tolstring(tolua_S, 1, &len));
if (SourceString == nullptr)
{
return 0;
}
md5(SourceString, len, md5Output);
// Convert the md5 checksum to hex string:
std::stringstream Output;
Output << std::hex << std::setfill('0');
for (size_t i = 0; i < ARRAYCOUNT(md5Output); i++)
{
Output << std::setw(2) << static_cast<unsigned short>(md5Output[i]); // Need to cast to a number, otherwise a char is output
}
lua_pushlstring(tolua_S, Output.str().c_str(), Output.str().size());
return 1;
}
static int tolua_sha1(lua_State * tolua_S)
{
// Calculate the raw SHA1 checksum byte array from the input string:
unsigned char Output[20];
size_t len = 0;
const unsigned char * SourceString = reinterpret_cast<const unsigned char *>(lua_tolstring(tolua_S, 1, &len));
if (SourceString == nullptr)
{
return 0;
}
sha1(SourceString, len, Output);
lua_pushlstring(tolua_S, reinterpret_cast<const char *>(Output), ARRAYCOUNT(Output));
return 1;
}
static int tolua_sha1HexString(lua_State * tolua_S)
{
// Calculate the raw SHA1 checksum byte array from the input string:
unsigned char sha1Output[20];
size_t len = 0;
const unsigned char * SourceString = reinterpret_cast<const unsigned char *>(lua_tolstring(tolua_S, 1, &len));
if (SourceString == nullptr)
{
return 0;
}
sha1(SourceString, len, sha1Output);
// Convert the sha1 checksum to hex string:
std::stringstream Output;
Output << std::hex << std::setfill('0');
for (size_t i = 0; i < ARRAYCOUNT(sha1Output); i++)
{
Output << std::setw(2) << static_cast<unsigned short>(sha1Output[i]); // Need to cast to a number, otherwise a char is output
}
lua_pushlstring(tolua_S, Output.str().c_str(), Output.str().size());
return 1;
}
static int tolua_get_HTTPRequest_Params(lua_State * a_LuaState)
{
cLuaState L(a_LuaState);
HTTPRequest * self;
if (!L.GetStackValues(1, self))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid self parameter, expected a HTTPRequest instance", &err);
return 0;
}
L.Push(self->Params);
return 1;
}
static int tolua_get_HTTPRequest_PostParams(lua_State * a_LuaState)
{
cLuaState L(a_LuaState);
HTTPRequest * self;
if (!L.GetStackValues(1, self))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid self parameter, expected a HTTPRequest instance", &err);
return 0;
}
L.Push(self->PostParams);
return 1;
}
static int tolua_get_HTTPRequest_FormData(lua_State* a_LuaState)
{
cLuaState L(a_LuaState);
HTTPRequest * self;
if (!L.GetStackValues(1, self))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid self parameter, expected a HTTPRequest instance", &err);
return 0;
}
const auto & FormData = self->FormData;
lua_newtable(a_LuaState);
int top = lua_gettop(a_LuaState);
for (auto itr = FormData.cbegin(); itr != FormData.cend(); ++itr)
{
lua_pushstring(a_LuaState, itr->first.c_str());
tolua_pushusertype(a_LuaState, const_cast<void *>(reinterpret_cast<const void *>(&(itr->second))), "HTTPFormData");
// lua_pushlstring(a_LuaState, it->second.Value.c_str(), it->second.Value.size()); // Might contain binary data
lua_settable(a_LuaState, top);
}
return 1;
}
static int tolua_cUrlParser_GetDefaultPort(lua_State * a_LuaState)
{
// API function signature:
// cUrlParser:GetDefaultPort("scheme") -> number
// Check params:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cUrlParser") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Read params from Lua:
AString scheme;
L.GetStackValue(2, scheme);
// Execute and push result:
L.Push(cUrlParser::GetDefaultPort(scheme));
return 1;
}
static int tolua_cUrlParser_IsKnownScheme(lua_State * a_LuaState)
{
// API function signature:
// cUrlParser:IsKnownScheme("scheme") -> bool
// Check params:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cUrlParser") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Read params from Lua:
AString scheme;
L.GetStackValue(2, scheme);
// Execute and push result:
L.Push(cUrlParser::IsKnownScheme(scheme));
return 1;
}
static int tolua_cUrlParser_Parse(lua_State * a_LuaState)
{
// API function signature:
// cUrlParser:Parse("url") -> "scheme", "user", "password", "host", portnum, "path", "query", "fragment"
// On error, returns nil and error message
// Check params:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cUrlParser") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Read params from Lua:
AString url;
L.GetStackValue(2, url);
// Execute and push result:
AString scheme, username, password, host, path, query, fragment;
UInt16 port;
auto res = cUrlParser::Parse(url, scheme, username, password, host, port, path, query, fragment);
if (!res.first)
{
// Error, return nil and error msg:
L.Push(cLuaState::Nil, res.second);
return 2;
}
L.Push(scheme, username, password, host, port, path, query, fragment);
return 8;
}
static int tolua_cUrlParser_ParseAuthorityPart(lua_State * a_LuaState)
{
// API function signature:
// cUrlParser:ParseAuthorityPart("authority") -> "user", "password", "host", portnum
// On error, returns nil and error message
// Parts not specified in the "authority" are left empty / zero
// Check params:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cUrlParser") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Read params from Lua:
AString authPart;
L.GetStackValue(2, authPart);
// Execute and push result:
AString username, password, host;
UInt16 port;
auto res = cUrlParser::ParseAuthorityPart(authPart, username, password, host, port);
if (!res.first)
{
// Error, return nil and error msg:
L.Push(cLuaState::Nil, res.second);
return 2;
}
L.Push(username, password, host, port);
return 4;
}
static int tolua_cUrlParser_UrlDecode(lua_State * tolua_S)
{
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care about the first param
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
AString Input;
S.GetStackValue(2, Input);
// Convert and return:
auto res = URLDecode(Input);
if (res.first)
{
S.Push(res.second);
}
else
{
S.Push(cLuaState::Nil);
}
return 1;
}
static int tolua_cUrlParser_UrlEncode(lua_State * tolua_S)
{
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care about the first param
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
AString Input;
S.GetStackValue(2, Input);
// Convert and return:
S.Push(URLEncode(Input));
return 1;
}
static int tolua_cWebAdmin_AddWebTab(lua_State * tolua_S)
{
// Function signatures:
// cWebAdmin:AddWebTab(Title, UrlPath, CallbackFn)
// Check params:
cLuaState LuaState(tolua_S);
cPluginLua * self = cManualBindings::GetLuaPlugin(tolua_S);
if (self == nullptr)
{
return 0;
}
if (
// Don't care whether the first param is a cWebAdmin instance or class
!LuaState.CheckParamString(2, 3) ||
!LuaState.CheckParamFunction(4) ||
!LuaState.CheckParamEnd(5)
)
{
return 0;
}
// Read the params:
AString title, urlPath;
auto callback = std::make_shared<cWebTabCallback>();
if (!LuaState.GetStackValues(2, title, urlPath, callback->m_Callback))
{
LOGWARNING("cWebAdmin:AddWebTab(): Cannot read required parameters");
return 0;
}
cRoot::Get()->GetWebAdmin()->AddWebTab(title, urlPath, self->GetName(), callback);
return 0;
}
static int tolua_cWebAdmin_GetAllWebTabs(lua_State * tolua_S)
{
// Function signature:
// cWebAdmin:GetAllWebTabs() -> { {"PluginName", "UrlPath", "Title"}, {"PluginName", "UrlPath", "Title"}, ...}
// Don't care about params at all
auto webTabs = cRoot::Get()->GetWebAdmin()->GetAllWebTabs();
lua_createtable(tolua_S, static_cast<int>(webTabs.size()), 0);
int newTable = lua_gettop(tolua_S);
int index = 1;
cLuaState L(tolua_S);
for (const auto & wt: webTabs)
{
lua_createtable(tolua_S, 0, 3);
L.Push(wt->m_PluginName);
lua_setfield(tolua_S, -2, "PluginName");
L.Push(wt->m_UrlPath);
lua_setfield(tolua_S, -2, "UrlPath");
L.Push(wt->m_Title);
lua_setfield(tolua_S, -2, "Title");
lua_rawseti(tolua_S, newTable, index);
++index;
}
return 1;
}
/** Binding for cWebAdmin::GetBaseURL.
Manual code required because ToLua generates an extra return value */
static int tolua_cWebAdmin_GetBaseURL(lua_State * tolua_S)
{
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care whether the first param is a cWebAdmin instance or class
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
AString Input;
S.GetStackValue(2, Input);
// Convert and return:
S.Push(cWebAdmin::GetBaseURL(Input));
return 1;
}
/** Binding for cWebAdmin::GetContentTypeFromFileExt.
Manual code required because ToLua generates an extra return value */
static int tolua_cWebAdmin_GetContentTypeFromFileExt(lua_State * tolua_S)
{
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care whether the first param is a cWebAdmin instance or class
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
AString Input;
S.GetStackValue(2, Input);
// Convert and return:
S.Push(cWebAdmin::GetContentTypeFromFileExt(Input));
return 1;
}
/** Binding for cWebAdmin::GetHTMLEscapedString.
Manual code required because ToLua generates an extra return value */
static int tolua_cWebAdmin_GetHTMLEscapedString(lua_State * tolua_S)
{
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care whether the first param is a cWebAdmin instance or class
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
AString Input;
S.GetStackValue(2, Input);
// Convert and return:
S.Push(cWebAdmin::GetHTMLEscapedString(Input));
return 1;
}
/** Binding for cWebAdmin::GetPage. */
static int tolua_cWebAdmin_GetPage(lua_State * tolua_S)
{
/*
Function signature:
cWebAdmin:GetPage(a_HTTPRequest) ->
{
Content = "", // Content generated by the plugin
ContentType = "", // Content type generated by the plugin (default: "text/html")
UrlPath = "", // URL path of the tab
TabTitle = "", // Tab's title, as register via cWebAdmin:AddWebTab()
PluginName = "", // Plugin's API name
PluginFolder = "", // Plugin's folder name (display name)
}
*/
// Check the param types:
cLuaState S(tolua_S);
if (
// Don't care about first param, whether it's cWebAdmin instance or class
!S.CheckParamUserType(2, "HTTPRequest") ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the parameters:
HTTPRequest * request = nullptr;
if (!S.GetStackValue(2, request))
{
LOGWARNING("cWebAdmin:GetPage(): Cannot read the HTTPRequest parameter.");
return 0;
}
// Generate the page and push the results as a dictionary-table:
auto page = cRoot::Get()->GetWebAdmin()->GetPage(*request);
lua_createtable(S, 0, 6);
S.Push(page.Content);
lua_setfield(S, -2, "Content");
S.Push(page.ContentType);
lua_setfield(S, -2, "ContentType");
S.Push(page.TabUrlPath);
lua_setfield(S, -2, "UrlPath");
S.Push(page.TabTitle);
lua_setfield(S, -2, "TabTitle");
S.Push(page.PluginName);
lua_setfield(S, -2, "PluginName");
S.Push(cPluginManager::Get()->GetPluginFolderName(page.PluginName));
lua_setfield(S, -2, "PluginFolder");
return 1;
}
/** Binding for cWebAdmin::GetURLEncodedString. */
static int tolua_cWebAdmin_GetURLEncodedString(lua_State * tolua_S)
{
// Emit the obsoletion warning:
cLuaState S(tolua_S);
LOGWARNING("cWebAdmin:GetURLEncodedString() is obsolete, use cUrlParser:UrlEncode() instead.");
S.LogStackTrace();
return tolua_cUrlParser_UrlEncode(tolua_S);
}
static int tolua_cClientHandle_SendPluginMessage(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserType(1, "cClientHandle") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
{
return 0;
}
cClientHandle * Client = reinterpret_cast<cClientHandle *>(tolua_tousertype(L, 1, nullptr));
if (Client == nullptr)
{
LOGWARNING("ClientHandle is nil in cClientHandle:SendPluginMessage()");
S.LogStackTrace();
return 0;
}
AString Channel, Message;
Channel.assign(lua_tostring(L, 2), lua_strlen(L, 2));
Message.assign(lua_tostring(L, 3), lua_strlen(L, 3));
Client->SendPluginMessage(Channel, Message);
return 0;
}
static int tolua_cMojangAPI_AddPlayerNameToUUIDMapping(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamString(2) ||
!S.CheckParamString(3) ||
!S.CheckParamEnd(4)
)
{
return 0;
}
// Retrieve the parameters:
AString UUID, PlayerName;
S.GetStackValue(2, PlayerName);
S.GetStackValue(3, UUID);
// Store in the cache:
cRoot::Get()->GetMojangAPI().AddPlayerNameToUUIDMapping(PlayerName, UUID);
return 0;
}
static int tolua_cMojangAPI_GetPlayerNameFromUUID(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(4)
)
{
return 0;
}
AString UUID;
S.GetStackValue(2, UUID);
// If the UseOnlyCached param was given, read it; default to false
bool ShouldUseCacheOnly = false;
if (lua_gettop(L) == 3)
{
ShouldUseCacheOnly = (lua_toboolean(L, 3) != 0);
lua_pop(L, 1);
}
// Return the PlayerName:
AString PlayerName = cRoot::Get()->GetMojangAPI().GetPlayerNameFromUUID(UUID, ShouldUseCacheOnly);
S.Push(PlayerName);
return 1;
}
static int tolua_cMojangAPI_GetUUIDFromPlayerName(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(4)
)
{
return 0;
}
AString PlayerName;
S.GetStackValue(2, PlayerName);
// If the UseOnlyCached param was given, read it; default to false
bool ShouldUseCacheOnly = false;
if (lua_gettop(L) == 3)
{
ShouldUseCacheOnly = (lua_toboolean(L, 3) != 0);
lua_pop(L, 1);
}
// Return the UUID:
AString UUID = cRoot::Get()->GetMojangAPI().GetUUIDFromPlayerName(PlayerName, ShouldUseCacheOnly);
S.Push(UUID);
return 1;
}
static int tolua_cMojangAPI_GetUUIDsFromPlayerNames(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamTable(2) ||
!S.CheckParamEnd(4)
)
{
return 0;
}
// Convert the input table into AStringVector:
AStringVector PlayerNames;
int NumNames = luaL_getn(L, 2);
PlayerNames.reserve(static_cast<size_t>(NumNames));
for (int i = 1; i <= NumNames; i++)
{
lua_rawgeti(L, 2, i);
AString Name;
S.GetStackValue(-1, Name);
if (!Name.empty())
{
PlayerNames.push_back(Name);
}
lua_pop(L, 1);
}
// If the UseOnlyCached param was given, read it; default to false
bool ShouldUseCacheOnly = false;
if (lua_gettop(L) == 3)
{
ShouldUseCacheOnly = (lua_toboolean(L, 3) != 0);
lua_pop(L, 1);
}
// Push the output table onto the stack:
lua_newtable(L);
// Get the UUIDs:
AStringVector UUIDs = cRoot::Get()->GetMojangAPI().GetUUIDsFromPlayerNames(PlayerNames, ShouldUseCacheOnly);
if (UUIDs.size() != PlayerNames.size())
{
// A hard error has occured while processing the request, no UUIDs were returned. Return an empty table:
return 1;
}
// Convert to output table, PlayerName -> UUID:
size_t len = UUIDs.size();
for (size_t i = 0; i < len; i++)
{
if (UUIDs[i].empty())
{
// No UUID was provided for PlayerName[i], skip it in the resulting table
continue;
}
lua_pushlstring(L, UUIDs[i].c_str(), UUIDs[i].length());
lua_setfield(L, 3, PlayerNames[i].c_str());
}
return 1;
}
static int tolua_cMojangAPI_MakeUUIDDashed(lua_State * L)
{
// Function signature: cMojangAPI:MakeUUIDDashed(UUID) -> string
// Check params:
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
AString UUID;
S.GetStackValue(2, UUID);
// Push the result:
S.Push(cRoot::Get()->GetMojangAPI().MakeUUIDDashed(UUID));
return 1;
}
static int tolua_cMojangAPI_MakeUUIDShort(lua_State * L)
{
// Function signature: cMojangAPI:MakeUUIDShort(UUID) -> string
// Check params:
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cMojangAPI") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
AString UUID;
S.GetStackValue(2, UUID);
// Push the result:
S.Push(cRoot::Get()->GetMojangAPI().MakeUUIDShort(UUID));
return 1;
}
static int Lua_ItemGrid_GetSlotCoords(lua_State * L)
{
tolua_Error tolua_err;
if (
!tolua_isusertype(L, 1, "const cItemGrid", 0, &tolua_err) ||
!tolua_isnumber (L, 2, 0, &tolua_err) ||
!tolua_isnoobj (L, 3, &tolua_err)
)
{
goto tolua_lerror;
}
{
const cItemGrid * self = reinterpret_cast<const cItemGrid *>(tolua_tousertype(L, 1, nullptr));
int SlotNum = static_cast<int>(tolua_tonumber(L, 2, 0));
if (self == nullptr)
{
tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", nullptr);
return 0;
}
int X, Y;
self->GetSlotCoords(SlotNum, X, Y);
tolua_pushnumber(L, static_cast<lua_Number>(X));
tolua_pushnumber(L, static_cast<lua_Number>(Y));
return 2;
}
tolua_lerror:
tolua_error(L, "#ferror in function 'cItemGrid:GetSlotCoords'.", &tolua_err);
return 0;
}
/** Provides interface between a Lua table of callbacks and the cBlockTracer::cCallbacks */
class cLuaBlockTracerCallbacks :
public cBlockTracer::cCallbacks
{
public:
cLuaBlockTracerCallbacks(cLuaState::cTableRefPtr && a_Callbacks):
m_Callbacks(std::move(a_Callbacks))
{
}
virtual bool OnNextBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, char a_EntryFace) override
{
bool res = false;
if (!m_Callbacks->CallTableFn(
"OnNextBlock",
a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_EntryFace,
cLuaState::Return, res
))
{
// No such function in the table, skip the callback
return false;
}
return res;
}
virtual bool OnNextBlockNoData(int a_BlockX, int a_BlockY, int a_BlockZ, char a_EntryFace) override
{
bool res = false;
if (!m_Callbacks->CallTableFn(
"OnNextBlockNoData",
a_BlockX, a_BlockY, a_BlockZ, a_EntryFace,
cLuaState::Return, res
))
{
// No such function in the table, skip the callback
return false;
}
return res;
}
virtual bool OnOutOfWorld(double a_BlockX, double a_BlockY, double a_BlockZ) override
{
bool res = false;
if (!m_Callbacks->CallTableFn(
"OnOutOfWorld",
a_BlockX, a_BlockY, a_BlockZ,
cLuaState::Return, res
))
{
// No such function in the table, skip the callback
return false;
}
return res;
}
virtual bool OnIntoWorld(double a_BlockX, double a_BlockY, double a_BlockZ) override
{
bool res = false;
if (!m_Callbacks->CallTableFn(
"OnIntoWorld",
a_BlockX, a_BlockY, a_BlockZ,
cLuaState::Return, res
))
{
// No such function in the table, skip the callback
return false;
}
return res;
}
virtual void OnNoMoreHits(void) override
{
m_Callbacks->CallTableFn("OnNoMoreHits");
}
virtual void OnNoChunk(void) override
{
m_Callbacks->CallTableFn("OnNoChunk");
}
protected:
cLuaState::cTableRefPtr m_Callbacks;
} ;
static int tolua_cLineBlockTracer_Trace(lua_State * tolua_S)
{
/* Supported function signatures:
cLineBlockTracer:Trace(World, Callbacks, StartX, StartY, StartZ, EndX, EndY, EndZ) // Canonical
cLineBlockTracer.Trace(World, Callbacks, StartX, StartY, StartZ, EndX, EndY, EndZ)
*/
// If the first param is the cLineBlockTracer class, shift param index by one:
int idx = 1;
tolua_Error err;
if (tolua_isusertable(tolua_S, 1, "cLineBlockTracer", 0, &err))
{
idx = 2;
}
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(idx, "cWorld") ||
!L.CheckParamTable (idx + 1) ||
!L.CheckParamNumber (idx + 2, idx + 7) ||
!L.CheckParamEnd (idx + 8)
)
{
return 0;
}
// Get the params:
cWorld * world;
double startX, startY, startZ;
double endX, endY, endZ;
cLuaState::cTableRefPtr callbacks;
if (!L.GetStackValues(idx, world, callbacks, startX, startY, startZ, endX, endY, endZ))
{
LOGWARNING("cLineBlockTracer:Trace(): Cannot read parameters (starting at idx %d), aborting the trace.", idx);
L.LogStackTrace();
L.LogStackValues("Values on the stack");
return 0;
}
// Trace:
cLuaBlockTracerCallbacks tracerCallbacks(std::move(callbacks));
bool res = cLineBlockTracer::Trace(*world, tracerCallbacks, startX, startY, startZ, endX, endY, endZ);
tolua_pushboolean(L, res ? 1 : 0);
return 1;
}
static int tolua_cLuaWindow_new(lua_State * tolua_S)
{
// Function signature:
// cLuaWindow:new(type, slotsX, slotsY, title)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cLuaWindow") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamString(5) ||
!L.CheckParamEnd(6)
)
{
return 0;
}
// Read params:
int windowType, slotsX, slotsY;
AString title;
if (!L.GetStackValues(2, windowType, slotsX, slotsY, title))
{
LOGWARNING("%s: Cannot read Lua parameters", __FUNCTION__);
L.LogStackValues();
L.LogStackTrace();
}
// Create the window and return it:
L.Push(new cLuaWindow(L, static_cast<cLuaWindow::WindowType>(windowType), slotsX, slotsY, title));
return 1;
}
static int tolua_cLuaWindow_new_local(lua_State * tolua_S)
{
// Function signature:
// cLuaWindow:new(type, slotsX, slotsY, title)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cLuaWindow") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamString(5) ||
!L.CheckParamEnd(6)
)
{
return 0;
}
// Read params:
int windowType, slotsX, slotsY;
AString title;
if (!L.GetStackValues(2, windowType, slotsX, slotsY, title))
{
LOGWARNING("%s: Cannot read Lua parameters", __FUNCTION__);
L.LogStackValues();
L.LogStackTrace();
}
// Create the window, register it for GC and return it:
L.Push(new cLuaWindow(L, static_cast<cLuaWindow::WindowType>(windowType), slotsX, slotsY, title));
tolua_register_gc(tolua_S, lua_gettop(tolua_S));
return 1;
}
static int tolua_cRoot_GetBuildCommitID(lua_State * tolua_S)
{
cLuaState L(tolua_S);
L.Push(BUILD_COMMIT_ID);
return 1;
}
static int tolua_cRoot_GetBuildDateTime(lua_State * tolua_S)
{
cLuaState L(tolua_S);
L.Push(BUILD_DATETIME);
return 1;
}
static int tolua_cRoot_GetBuildID(lua_State * tolua_S)
{
cLuaState L(tolua_S);
L.Push(BUILD_ID);
return 1;
}
static int tolua_cRoot_GetBuildSeriesName(lua_State * tolua_S)
{
cLuaState L(tolua_S);
L.Push(BUILD_SERIES_NAME);
return 1;
}
static int tolua_cRoot_GetBrewingRecipe(lua_State * tolua_S)
{
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cRoot") ||
!L.CheckParamUserType (2, "const cItem") ||
!L.CheckParamUserType (3, "const cItem") ||
!L.CheckParamEnd (4)
)
{
return 0;
}
// Check the bottle param:
cItem * Bottle = nullptr;
L.GetStackValue(2, Bottle);
if (Bottle == nullptr)
{
LOGWARNING("cRoot:GetBrewingRecipe: the Bottle parameter is nil or missing.");
return 0;
}
cItem * Ingredient = nullptr;
L.GetStackValue(3, Ingredient);
if (Ingredient == nullptr)
{
LOGWARNING("cRoot:GetBrewingRecipe: the Ingredient parameter is nil or missing.");
return 0;
}
// Get the recipe for the input
cBrewingRecipes * BR = cRoot::Get()->GetBrewingRecipes();
const cBrewingRecipes::cRecipe * Recipe = BR->GetRecipeFrom(*Bottle, *Ingredient);
if (Recipe == nullptr)
{
// There is no such brewing recipe for this bottle and ingredient, return no value
return 0;
}
// Push the output item
L.Push(Recipe->Output.get());
return 1;
}
static int tolua_cRoot_GetFurnaceRecipe(lua_State * tolua_S)
{
cLuaState L(tolua_S);
if (
!L.CheckParamUserTable(1, "cRoot") ||
!L.CheckParamUserType (2, "const cItem") ||
!L.CheckParamEnd (3)
)
{
return 0;
}
// Check the input param:
cItem * Input = nullptr;
L.GetStackValue(2, Input);
if (Input == nullptr)
{
LOGWARNING("cRoot:GetFurnaceRecipe: the Input parameter is nil or missing.");
return 0;
}
// Get the recipe for the input
cFurnaceRecipe * FR = cRoot::Get()->GetFurnaceRecipe();
const cFurnaceRecipe::cRecipe * Recipe = FR->GetRecipeFrom(*Input);
if (Recipe == nullptr)
{
// There is no such furnace recipe for this input, return no value
return 0;
}
// Push the output, number of ticks and input as the three return values:
L.Push(Recipe->Out, Recipe->CookTime, Recipe->In);
return 3;
}
static int tolua_cScoreboard_GetTeamNames(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserType(1, "cScoreboard") ||
!S.CheckParamEnd(2)
)
{
return 0;
}
// Get the groups:
cScoreboard * Scoreboard = reinterpret_cast<cScoreboard *>(tolua_tousertype(L, 1, nullptr));
AStringVector Teams = Scoreboard->GetTeamNames();
// Push the results:
S.Push(Teams);
return 1;
}
static int tolua_cHopperEntity_GetOutputBlockPos(lua_State * tolua_S)
{
// function cHopperEntity::GetOutputBlockPos()
// Exported manually because tolua would require meaningless params
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cHopperEntity") ||
!L.CheckParamNumber (2) ||
!L.CheckParamEnd (3)
)
{
return 0;
}
cHopperEntity * self = reinterpret_cast<cHopperEntity *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cHopperEntity::GetOutputBlockPos()'", nullptr);
return 0;
}
NIBBLETYPE a_BlockMeta = static_cast<NIBBLETYPE>(tolua_tonumber(tolua_S, 2, 0));
int a_OutputX, a_OutputY, a_OutputZ;
bool res = self->GetOutputBlockPos(a_BlockMeta, a_OutputX, a_OutputY, a_OutputZ);
tolua_pushboolean(tolua_S, res);
if (res)
{
tolua_pushnumber(tolua_S, static_cast<lua_Number>(a_OutputX));
tolua_pushnumber(tolua_S, static_cast<lua_Number>(a_OutputY));
tolua_pushnumber(tolua_S, static_cast<lua_Number>(a_OutputZ));
return 4;
}
return 1;
}
static int tolua_cBlockArea_GetBlockTypeMeta(lua_State * tolua_S)
{
// function cBlockArea::GetBlockTypeMeta()
// Exported manually because tolua generates extra input params for the outputs
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamNumber (2, 4)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr);
return 0;
}
int BlockX = static_cast<int>(tolua_tonumber(tolua_S, 2, 0));
int BlockY = static_cast<int>(tolua_tonumber(tolua_S, 3, 0));
int BlockZ = static_cast<int>(tolua_tonumber(tolua_S, 4, 0));
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
self->GetBlockTypeMeta(BlockX, BlockY, BlockZ, BlockType, BlockMeta);
tolua_pushnumber(tolua_S, BlockType);
tolua_pushnumber(tolua_S, BlockMeta);
return 2;
}
static int tolua_cBlockArea_GetOrigin(lua_State * tolua_S)
{
// function cBlockArea::GetOrigin()
// Returns all three coords of the origin point
// Exported manually because there's no direct C++ equivalent,
// plus tolua would generate extra input params for the outputs
cLuaState L(tolua_S);
if (!L.CheckParamUserType(1, "cBlockArea"))
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetOrigin'", nullptr);
return 0;
}
// Push the three origin coords:
lua_pushnumber(tolua_S, self->GetOriginX());
lua_pushnumber(tolua_S, self->GetOriginY());
lua_pushnumber(tolua_S, self->GetOriginZ());
return 3;
}
static int tolua_cBlockArea_GetNonAirCropRelCoords(lua_State * tolua_S)
{
// function cBlockArea::GetNonAirCropRelCoords()
// Exported manually because tolua would generate extra input params for the outputs
cLuaState L(tolua_S);
if (!L.CheckParamUserType(1, "cBlockArea"))
{
return 0;
}
cBlockArea * self = nullptr;
BLOCKTYPE IgnoreBlockType = E_BLOCK_AIR;
L.GetStackValues(1, self, IgnoreBlockType);
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetNonAirCropRelCoords'", nullptr);
return 0;
}
// Calculate the crop coords:
int MinRelX, MinRelY, MinRelZ, MaxRelX, MaxRelY, MaxRelZ;
self->GetNonAirCropRelCoords(MinRelX, MinRelY, MinRelZ, MaxRelX, MaxRelY, MaxRelZ, IgnoreBlockType);
// Push the six crop coords:
L.Push(MinRelX, MinRelY, MinRelZ, MaxRelX, MaxRelY, MaxRelZ);
return 6;
}
static int tolua_cBlockArea_GetRelBlockTypeMeta(lua_State * tolua_S)
{
// function cBlockArea::GetRelBlockTypeMeta()
// Exported manually because tolua generates extra input params for the outputs
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamNumber (2, 4)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr);
return 0;
}
int BlockX = static_cast<int>(tolua_tonumber(tolua_S, 2, 0));
int BlockY = static_cast<int>(tolua_tonumber(tolua_S, 3, 0));
int BlockZ = static_cast<int>(tolua_tonumber(tolua_S, 4, 0));
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
self->GetRelBlockTypeMeta(BlockX, BlockY, BlockZ, BlockType, BlockMeta);
tolua_pushnumber(tolua_S, BlockType);
tolua_pushnumber(tolua_S, BlockMeta);
return 2;
}
static int tolua_cBlockArea_GetSize(lua_State * tolua_S)
{
// function cBlockArea::GetSize()
// Returns all three sizes of the area
// Exported manually because there's no direct C++ equivalent,
// plus tolua would generate extra input params for the outputs
cLuaState L(tolua_S);
if (!L.CheckParamUserType(1, "cBlockArea"))
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr);
return 0;
}
// Push the three origin coords:
lua_pushnumber(tolua_S, self->GetSizeX());
lua_pushnumber(tolua_S, self->GetSizeY());
lua_pushnumber(tolua_S, self->GetSizeZ());
return 3;
}
static int tolua_cBlockArea_GetCoordRange(lua_State * tolua_S)
{
// function cBlockArea::GetCoordRange()
// Returns all three sizes of the area, miuns one, so that they represent the maximum coord value
// Exported manually because there's no direct C++ equivalent,
// plus tolua would generate extra input params for the outputs
cLuaState L(tolua_S);
if (!L.CheckParamUserType(1, "cBlockArea"))
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr);
return 0;
}
// Push the three origin coords:
lua_pushnumber(tolua_S, self->GetSizeX() - 1);
lua_pushnumber(tolua_S, self->GetSizeY() - 1);
lua_pushnumber(tolua_S, self->GetSizeZ() - 1);
return 3;
}
static int tolua_cBlockArea_LoadFromSchematicFile(lua_State * tolua_S)
{
// function cBlockArea::LoadFromSchematicFile
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamString (2) ||
!L.CheckParamEnd (3)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr);
return 0;
}
AString Filename = tolua_tostring(tolua_S, 2, 0);
bool res = cSchematicFileSerializer::LoadFromSchematicFile(*self, Filename);
tolua_pushboolean(tolua_S, res);
return 1;
}
static int tolua_cBlockArea_LoadFromSchematicString(lua_State * tolua_S)
{
// function cBlockArea::LoadFromSchematicString
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamString (2) ||
!L.CheckParamEnd (3)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr);
return 0;
}
AString Data;
L.GetStackValue(2, Data);
bool res = cSchematicFileSerializer::LoadFromSchematicString(*self, Data);
tolua_pushboolean(tolua_S, res);
return 1;
}
static int tolua_cBlockArea_SaveToSchematicFile(lua_State * tolua_S)
{
// function cBlockArea::SaveToSchematicFile
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamString (2) ||
!L.CheckParamEnd (3)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr);
return 0;
}
AString Filename = tolua_tostring(tolua_S, 2, 0);
bool res = cSchematicFileSerializer::SaveToSchematicFile(*self, Filename);
tolua_pushboolean(tolua_S, res);
return 1;
}
static int tolua_cBlockArea_SaveToSchematicString(lua_State * tolua_S)
{
// function cBlockArea::SaveToSchematicString
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cBlockArea") ||
!L.CheckParamEnd (2)
)
{
return 0;
}
cBlockArea * self = reinterpret_cast<cBlockArea *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr);
return 0;
}
AString Data;
if (cSchematicFileSerializer::SaveToSchematicString(*self, Data))
{
L.Push(Data);
return 1;
}
return 0;
}
static int tolua_cBoundingBox_CalcLineIntersection(lua_State * a_LuaState)
{
/* Function signatures:
bbox:CalcLineIntersection(pt1, pt2) -> bool, [number, blockface]
cBoundingBox:CalcLineIntersection(min, max, pt1, pt2) -> bool, [number, blockface]
*/
cLuaState L(a_LuaState);
const Vector3d * min;
const Vector3d * max;
const Vector3d * pt1;
const Vector3d * pt2;
double lineCoeff;
eBlockFace blockFace;
bool res;
if (L.GetStackValues(2, min, max, pt1, pt2)) // Try the static signature first
{
res = cBoundingBox::CalcLineIntersection(min, max, pt1, pt2, lineCoeff, blockFace);
}
else
{
const cBoundingBox * bbox;
if (!L.GetStackValues(1, bbox, pt1, pt2)) // Try the regular signature
{
L.LogStackValues();
tolua_error(a_LuaState, "Invalid function params. Expected either bbox:CalcLineIntersection(pt1, pt2) or cBoundingBox:CalcLineIntersection(min, max, pt1, pt2).", nullptr);
return 0;
}
res = bbox->CalcLineIntersection(pt1, pt2, lineCoeff, blockFace);
}
L.Push(res);
if (res)
{
L.Push(lineCoeff, blockFace);
return 3;
}
return 1;
}
static int tolua_cBoundingBox_Intersect(lua_State * a_LuaState)
{
/* Function signature:
bbox:Intersect(a_OtherBbox) -> bool, cBoundingBox
*/
cLuaState L(a_LuaState);
const cBoundingBox * self;
const cBoundingBox * other;
if (!L.GetStackValues(1, self, other))
{
L.LogStackValues();
tolua_error(a_LuaState, "Invalid function params. Expected bbox:Intersect(otherBbox).", nullptr);
return 0;
}
auto intersection = new cBoundingBox(*self);
auto res = self->Intersect(*other, *intersection);
L.Push(res);
if (!res)
{
delete intersection;
return 1;
}
L.Push(intersection);
tolua_register_gc(L, lua_gettop(L)); // Make Lua own the "intersection" object
return 2;
}
static int tolua_cChunkDesc_GetBlockTypeMeta(lua_State * a_LuaState)
{
/* Function signature:
ChunkDesc:GetBlockTypeMeta(RelX, RelY, RelZ) -> BlockType, BlockMeta
*/
cLuaState L(a_LuaState);
const cChunkDesc * self;
int relX, relY, relZ;
if (!L.GetStackValues(1, self, relX, relY, relZ))
{
L.LogStackValues();
tolua_error(a_LuaState, "Invalid function params. Expected chunkDesc:GetBlockTypeMeta(relX, relY, relZ)", nullptr);
return 0;
}
BLOCKTYPE blockType;
NIBBLETYPE blockMeta;
self->GetBlockTypeMeta(relX, relY, relZ, blockType, blockMeta);
L.Push(blockType, blockMeta);
return 2;
}
static int tolua_cCompositeChat_new(lua_State * a_LuaState)
{
/* Function signatures:
cCompositeChat()
cCompositeChat(a_ParseText, a_MessageType)
*/
// Check if it's the no-param version:
cLuaState L(a_LuaState);
if (lua_isnone(a_LuaState, 2))
{
auto * res = static_cast<cCompositeChat *>(Mtolua_new(cCompositeChat()));
L.Push(res);
return 1;
}
// Check the second signature:
AString parseText;
if (!L.GetStackValue(2, parseText))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid ParseText parameter (1) in cCompositeChat constructor.", &err);
return 0;
}
int messageTypeInt = mtCustom;
if (!lua_isnone(a_LuaState, 3))
{
if (!L.GetStackValue(3, messageTypeInt))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid type of the MessageType parameter (2) in cCompositeChat constructor.", &err);
return 0;
}
if ((messageTypeInt < 0) || (messageTypeInt >= mtMaxPlusOne))
{
tolua_Error err;
tolua_error(a_LuaState, "Invalid MessageType parameter (2) value in cCompositeChat constructor.", &err);
return 0;
}
}
L.Push(static_cast<cCompositeChat *>(Mtolua_new(cCompositeChat(parseText, static_cast<eMessageType>(messageTypeInt)))));
return 1;
}
static int tolua_cCompositeChat_new_local(lua_State * a_LuaState)
{
// Use the same constructor as global, just register it for GC:
auto res = tolua_cCompositeChat_new(a_LuaState);
if (res == 1)
{
tolua_register_gc(a_LuaState, lua_gettop(a_LuaState));
}
return res;
}
static int tolua_cCompositeChat_AddRunCommandPart(lua_State * tolua_S)
{
// function cCompositeChat:AddRunCommandPart(Message, Command, [Style])
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamString(2, 3)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddRunCommandPart'", nullptr);
return 0;
}
// Add the part:
AString Text, Command, Style = "u@a";
L.GetStackValue(2, Text);
L.GetStackValue(3, Command);
L.GetStackValue(4, Style);
self->AddRunCommandPart(Text, Command, Style);
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_AddSuggestCommandPart(lua_State * tolua_S)
{
// function cCompositeChat:AddSuggestCommandPart(Message, Command, [Style])
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamString(2, 3)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddSuggestCommandPart'", nullptr);
return 0;
}
// Add the part:
AString Text, Command, Style;
L.GetStackValue(2, Text);
L.GetStackValue(3, Command);
L.GetStackValue(4, Style);
self->AddSuggestCommandPart(Text, Command, Style);
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_AddTextPart(lua_State * tolua_S)
{
// function cCompositeChat:AddTextPart(Message, [Style])
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamString(2)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddTextPart'", nullptr);
return 0;
}
// Add the part:
AString Text, Style;
L.GetStackValue(2, Text);
L.GetStackValue(3, Style);
self->AddTextPart(Text, Style);
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_AddUrlPart(lua_State * tolua_S)
{
// function cCompositeChat:AddTextPart(Message, Url, [Style])
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamString(2, 3)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddUrlPart'", nullptr);
return 0;
}
// Add the part:
AString Text, Url, Style;
L.GetStackValue(2, Text);
L.GetStackValue(3, Url);
L.GetStackValue(4, Style);
self->AddUrlPart(Text, Url, Style);
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_Clear(lua_State * tolua_S)
{
// function cCompositeChat:Clear()
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamEnd(2)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", nullptr);
return 0;
}
// Clear all the parts:
self->Clear();
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_ParseText(lua_State * tolua_S)
{
// function cCompositeChat:ParseText(TextMessage)
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamString(2)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", nullptr);
return 0;
}
// Parse the text:
AString Text;
L.GetStackValue(2, Text);
self->ParseText(Text);
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_SetMessageType(lua_State * tolua_S)
{
// function cCompositeChat:SetMessageType(MessageType)
// Exported manually to support call-chaining (return *this)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cCompositeChat") ||
!L.CheckParamNumber(2)
)
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:SetMessageType'", nullptr);
return 0;
}
// Set the type:
int MessageType = mtCustom;
L.GetStackValue(2, MessageType);
self->SetMessageType(static_cast<eMessageType>(MessageType));
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cCompositeChat_UnderlineUrls(lua_State * tolua_S)
{
// function cCompositeChat:UnderlineUrls()
// Exported manually to support call-chaining (return self)
// Check params:
cLuaState L(tolua_S);
if (!L.CheckParamUserType(1, "cCompositeChat"))
{
return 0;
}
cCompositeChat * self = reinterpret_cast<cCompositeChat *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:UnderlineUrls'", nullptr);
return 0;
}
// Call the processing
self->UnderlineUrls();
// Cut away everything from the stack except for the cCompositeChat instance; return that:
lua_settop(L, 1);
return 1;
}
static int tolua_cEntity_GetPosition(lua_State * tolua_S)
{
cLuaState L(tolua_S);
// Get the params:
cEntity * self = reinterpret_cast<cEntity *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
LOGWARNING("%s: invalid self (%p)", __FUNCTION__, static_cast<void *>(self));
return 0;
}
L.Push(Mtolua_new((Vector3d)(self->GetPosition())));
tolua_register_gc(L, lua_gettop(L)); // Make Lua own the object
return 1;
}
static int tolua_cEntity_GetSpeed(lua_State * tolua_S)
{
cLuaState L(tolua_S);
// Get the params:
cEntity * self = reinterpret_cast<cEntity *>(tolua_tousertype(tolua_S, 1, nullptr));
if (self == nullptr)
{
LOGWARNING("%s: invalid self (%p)", __FUNCTION__, static_cast<void *>(self));
return 0;
}
L.Push(Mtolua_new((Vector3d)(self->GetSpeed())));
tolua_register_gc(L, lua_gettop(L)); // Make Lua own the object
return 1;
}
void cManualBindings::Bind(lua_State * tolua_S)
{
tolua_beginmodule(tolua_S, nullptr);
// Create the new classes:
tolua_usertype(tolua_S, "cCryptoHash");
tolua_usertype(tolua_S, "cLineBlockTracer");
tolua_usertype(tolua_S, "cStringCompression");
tolua_usertype(tolua_S, "cUrlParser");
tolua_cclass(tolua_S, "cCryptoHash", "cCryptoHash", "", nullptr);
tolua_cclass(tolua_S, "cLineBlockTracer", "cLineBlockTracer", "", nullptr);
tolua_cclass(tolua_S, "cStringCompression", "cStringCompression", "", nullptr);
tolua_cclass(tolua_S, "cUrlParser", "cUrlParser", "", nullptr);
// Globals:
tolua_function(tolua_S, "Clamp", tolua_Clamp);
tolua_function(tolua_S, "StringSplit", tolua_StringSplit);
tolua_function(tolua_S, "StringSplitWithQuotes", tolua_StringSplitWithQuotes);
tolua_function(tolua_S, "StringSplitAndTrim", tolua_StringSplitAndTrim);
tolua_function(tolua_S, "LOG", tolua_LOG);
tolua_function(tolua_S, "LOGINFO", tolua_LOGINFO);
tolua_function(tolua_S, "LOGWARN", tolua_LOGWARN);
tolua_function(tolua_S, "LOGWARNING", tolua_LOGWARN);
tolua_function(tolua_S, "LOGERROR", tolua_LOGERROR);
tolua_function(tolua_S, "Base64Encode", tolua_Base64Encode);
tolua_function(tolua_S, "Base64Decode", tolua_Base64Decode);
tolua_function(tolua_S, "md5", tolua_md5_obsolete); // OBSOLETE, use cCryptoHash.md5() instead
tolua_beginmodule(tolua_S, "cBlockArea");
tolua_function(tolua_S, "GetBlockTypeMeta", tolua_cBlockArea_GetBlockTypeMeta);
tolua_function(tolua_S, "GetCoordRange", tolua_cBlockArea_GetCoordRange);
tolua_function(tolua_S, "GetOrigin", tolua_cBlockArea_GetOrigin);
tolua_function(tolua_S, "GetNonAirCropRelCoords", tolua_cBlockArea_GetNonAirCropRelCoords);
tolua_function(tolua_S, "GetRelBlockTypeMeta", tolua_cBlockArea_GetRelBlockTypeMeta);
tolua_function(tolua_S, "GetSize", tolua_cBlockArea_GetSize);
tolua_function(tolua_S, "LoadFromSchematicFile", tolua_cBlockArea_LoadFromSchematicFile);
tolua_function(tolua_S, "LoadFromSchematicString", tolua_cBlockArea_LoadFromSchematicString);
tolua_function(tolua_S, "SaveToSchematicFile", tolua_cBlockArea_SaveToSchematicFile);
tolua_function(tolua_S, "SaveToSchematicString", tolua_cBlockArea_SaveToSchematicString);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cBoundingBox");
tolua_function(tolua_S, "CalcLineIntersection", tolua_cBoundingBox_CalcLineIntersection);
tolua_function(tolua_S, "Intersect", tolua_cBoundingBox_Intersect);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cChunkDesc");
tolua_function(tolua_S, "GetBlockTypeMeta", tolua_cChunkDesc_GetBlockTypeMeta);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cClientHandle");
tolua_constant(tolua_S, "MAX_VIEW_DISTANCE", cClientHandle::MAX_VIEW_DISTANCE);
tolua_constant(tolua_S, "MIN_VIEW_DISTANCE", cClientHandle::MIN_VIEW_DISTANCE);
tolua_function(tolua_S, "SendPluginMessage", tolua_cClientHandle_SendPluginMessage);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cCompositeChat");
tolua_function(tolua_S, "new", tolua_cCompositeChat_new);
tolua_function(tolua_S, "new_local", tolua_cCompositeChat_new_local);
tolua_function(tolua_S, ".call", tolua_cCompositeChat_new_local);
tolua_function(tolua_S, "AddRunCommandPart", tolua_cCompositeChat_AddRunCommandPart);
tolua_function(tolua_S, "AddSuggestCommandPart", tolua_cCompositeChat_AddSuggestCommandPart);
tolua_function(tolua_S, "AddTextPart", tolua_cCompositeChat_AddTextPart);
tolua_function(tolua_S, "AddUrlPart", tolua_cCompositeChat_AddUrlPart);
tolua_function(tolua_S, "Clear", tolua_cCompositeChat_Clear);
tolua_function(tolua_S, "ParseText", tolua_cCompositeChat_ParseText);
tolua_function(tolua_S, "SetMessageType", tolua_cCompositeChat_SetMessageType);
tolua_function(tolua_S, "UnderlineUrls", tolua_cCompositeChat_UnderlineUrls);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cCryptoHash");
tolua_function(tolua_S, "md5", tolua_md5);
tolua_function(tolua_S, "md5HexString", tolua_md5HexString);
tolua_function(tolua_S, "sha1", tolua_sha1);
tolua_function(tolua_S, "sha1HexString", tolua_sha1HexString);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cEntity");
tolua_constant(tolua_S, "INVALID_ID", cEntity::INVALID_ID);
tolua_function(tolua_S, "GetPosition", tolua_cEntity_GetPosition);
tolua_function(tolua_S, "GetSpeed", tolua_cEntity_GetSpeed);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cFile");
tolua_function(tolua_S, "ChangeFileExt", tolua_cFile_ChangeFileExt);
tolua_function(tolua_S, "Copy", tolua_cFile_Copy);
tolua_function(tolua_S, "CreateFolder", tolua_cFile_CreateFolder);
tolua_function(tolua_S, "CreateFolderRecursive", tolua_cFile_CreateFolderRecursive);
tolua_function(tolua_S, "Delete", tolua_cFile_Delete);
tolua_function(tolua_S, "DeleteFile", tolua_cFile_DeleteFile);
tolua_function(tolua_S, "DeleteFolder", tolua_cFile_DeleteFolder);
tolua_function(tolua_S, "DeleteFolderContents", tolua_cFile_DeleteFolderContents);
tolua_function(tolua_S, "Exists", tolua_cFile_Exists);
tolua_function(tolua_S, "GetFolderContents", tolua_cFile_GetFolderContents);
tolua_function(tolua_S, "GetLastModificationTime", tolua_cFile_GetLastModificationTime);
tolua_function(tolua_S, "GetSize", tolua_cFile_GetSize);
tolua_function(tolua_S, "IsFile", tolua_cFile_IsFile);
tolua_function(tolua_S, "IsFolder", tolua_cFile_IsFolder);
tolua_function(tolua_S, "ReadWholeFile", tolua_cFile_ReadWholeFile);
tolua_function(tolua_S, "Rename", tolua_cFile_Rename);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cHopperEntity");
tolua_function(tolua_S, "GetOutputBlockPos", tolua_cHopperEntity_GetOutputBlockPos);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cItemGrid");
tolua_function(tolua_S, "GetSlotCoords", Lua_ItemGrid_GetSlotCoords);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cLineBlockTracer");
tolua_function(tolua_S, "Trace", tolua_cLineBlockTracer_Trace);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cLuaWindow");
tolua_function(tolua_S, "new", tolua_cLuaWindow_new);
tolua_function(tolua_S, "new_local", tolua_cLuaWindow_new_local);
tolua_function(tolua_S, ".call", tolua_cLuaWindow_new_local);
tolua_function(tolua_S, "SetOnClosing", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnClosing>);
tolua_function(tolua_S, "SetOnSlotChanged", tolua_SetObjectCallback<cLuaWindow, &cLuaWindow::SetOnSlotChanged>);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cMapManager");
tolua_function(tolua_S, "DoWithMap", DoWithID<cMapManager, cMap, &cMapManager::DoWithMap>);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cMojangAPI");
tolua_function(tolua_S, "AddPlayerNameToUUIDMapping", tolua_cMojangAPI_AddPlayerNameToUUIDMapping);
tolua_function(tolua_S, "GetPlayerNameFromUUID", tolua_cMojangAPI_GetPlayerNameFromUUID);
tolua_function(tolua_S, "GetUUIDFromPlayerName", tolua_cMojangAPI_GetUUIDFromPlayerName);
tolua_function(tolua_S, "GetUUIDsFromPlayerNames", tolua_cMojangAPI_GetUUIDsFromPlayerNames);
tolua_function(tolua_S, "MakeUUIDDashed", tolua_cMojangAPI_MakeUUIDDashed);
tolua_function(tolua_S, "MakeUUIDShort", tolua_cMojangAPI_MakeUUIDShort);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cPlayer");
tolua_function(tolua_S, "GetPermissions", tolua_cPlayer_GetPermissions);
tolua_function(tolua_S, "GetRestrictions", tolua_cPlayer_GetRestrictions);
tolua_function(tolua_S, "PermissionMatches", tolua_cPlayer_PermissionMatches);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cPlugin");
tolua_function(tolua_S, "GetDirectory", tolua_cPlugin_GetDirectory);
tolua_function(tolua_S, "GetLocalDirectory", tolua_cPlugin_GetLocalDirectory);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cPluginLua");
tolua_function(tolua_S, "AddWebTab", tolua_cPluginLua_AddWebTab);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cPluginManager");
tolua_function(tolua_S, "AddHook", tolua_cPluginManager_AddHook);
tolua_function(tolua_S, "BindCommand", tolua_cPluginManager_BindCommand);
tolua_function(tolua_S, "BindConsoleCommand", tolua_cPluginManager_BindConsoleCommand);
tolua_function(tolua_S, "CallPlugin", tolua_cPluginManager_CallPlugin);
tolua_function(tolua_S, "DoWithPlugin", StaticDoWith<cPluginManager, cPlugin, &cPluginManager::DoWithPlugin>);
tolua_function(tolua_S, "ExecuteConsoleCommand", tolua_cPluginManager_ExecuteConsoleCommand);
tolua_function(tolua_S, "FindPlugins", tolua_cPluginManager_FindPlugins);
tolua_function(tolua_S, "ForEachCommand", tolua_cPluginManager_ForEachCommand);
tolua_function(tolua_S, "ForEachConsoleCommand", tolua_cPluginManager_ForEachConsoleCommand);
tolua_function(tolua_S, "ForEachPlugin", StaticForEach<cPluginManager, cPlugin, &cPluginManager::ForEachPlugin>);
tolua_function(tolua_S, "GetAllPlugins", tolua_cPluginManager_GetAllPlugins);
tolua_function(tolua_S, "GetCurrentPlugin", tolua_cPluginManager_GetCurrentPlugin);
tolua_function(tolua_S, "GetPlugin", tolua_cPluginManager_GetPlugin);
tolua_function(tolua_S, "LogStackTrace", tolua_cPluginManager_LogStackTrace);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cRoot");
tolua_function(tolua_S, "FindAndDoWithPlayer", DoWith <cRoot, cPlayer, &cRoot::FindAndDoWithPlayer>);
tolua_function(tolua_S, "DoWithPlayerByUUID", DoWith <cRoot, cPlayer, &cRoot::DoWithPlayerByUUID>);
tolua_function(tolua_S, "ForEachPlayer", ForEach<cRoot, cPlayer, &cRoot::ForEachPlayer>);
tolua_function(tolua_S, "ForEachWorld", ForEach<cRoot, cWorld, &cRoot::ForEachWorld>);
tolua_function(tolua_S, "GetBrewingRecipe", tolua_cRoot_GetBrewingRecipe);
tolua_function(tolua_S, "GetBuildCommitID", tolua_cRoot_GetBuildCommitID);
tolua_function(tolua_S, "GetBuildDateTime", tolua_cRoot_GetBuildDateTime);
tolua_function(tolua_S, "GetBuildID", tolua_cRoot_GetBuildID);
tolua_function(tolua_S, "GetBuildSeriesName", tolua_cRoot_GetBuildSeriesName);
tolua_function(tolua_S, "GetFurnaceRecipe", tolua_cRoot_GetFurnaceRecipe);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cScoreboard");
tolua_function(tolua_S, "ForEachObjective", ForEach<cScoreboard, cObjective, &cScoreboard::ForEachObjective>);
tolua_function(tolua_S, "ForEachTeam", ForEach<cScoreboard, cTeam, &cScoreboard::ForEachTeam>);
tolua_function(tolua_S, "GetTeamNames", tolua_cScoreboard_GetTeamNames);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cStringCompression");
tolua_function(tolua_S, "CompressStringZLIB", tolua_CompressStringZLIB);
tolua_function(tolua_S, "UncompressStringZLIB", tolua_UncompressStringZLIB);
tolua_function(tolua_S, "CompressStringGZIP", tolua_CompressStringGZIP);
tolua_function(tolua_S, "UncompressStringGZIP", tolua_UncompressStringGZIP);
tolua_function(tolua_S, "InflateString", tolua_InflateString);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cUrlParser");
tolua_function(tolua_S, "GetDefaultPort", tolua_cUrlParser_GetDefaultPort);
tolua_function(tolua_S, "IsKnownScheme", tolua_cUrlParser_IsKnownScheme);
tolua_function(tolua_S, "Parse", tolua_cUrlParser_Parse);
tolua_function(tolua_S, "ParseAuthorityPart", tolua_cUrlParser_ParseAuthorityPart);
tolua_function(tolua_S, "UrlDecode", tolua_cUrlParser_UrlDecode);
tolua_function(tolua_S, "UrlEncode", tolua_cUrlParser_UrlEncode);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cWebAdmin");
tolua_function(tolua_S, "AddWebTab", tolua_cWebAdmin_AddWebTab);
tolua_function(tolua_S, "GetAllWebTabs", tolua_cWebAdmin_GetAllWebTabs);
tolua_function(tolua_S, "GetBaseURL", tolua_cWebAdmin_GetBaseURL);
tolua_function(tolua_S, "GetContentTypeFromFileExt", tolua_cWebAdmin_GetContentTypeFromFileExt);
tolua_function(tolua_S, "GetHTMLEscapedString", tolua_cWebAdmin_GetHTMLEscapedString);
tolua_function(tolua_S, "GetPage", tolua_cWebAdmin_GetPage);
tolua_function(tolua_S, "GetURLEncodedString", tolua_cWebAdmin_GetURLEncodedString);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "HTTPRequest");
tolua_variable(tolua_S, "FormData", tolua_get_HTTPRequest_FormData, nullptr);
tolua_variable(tolua_S, "Params", tolua_get_HTTPRequest_Params, nullptr);
tolua_variable(tolua_S, "PostParams", tolua_get_HTTPRequest_PostParams, nullptr);
tolua_endmodule(tolua_S);
BindNetwork(tolua_S);
BindRankManager(tolua_S);
BindWorld(tolua_S);
tolua_endmodule(tolua_S);
}
|
johnsoch/cuberite
|
src/Bindings/ManualBindings.cpp
|
C++
|
apache-2.0
| 98,080
|
package org.gradle.test.performance.mediummonolithicjavaproject.p254;
public class Production5082 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
}
|
oehme/analysing-gradle-performance
|
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p254/Production5082.java
|
Java
|
apache-2.0
| 1,891
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 Anso Labs, 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.
"""
:mod:`nova` -- Cloud IaaS Platform
===================================
.. automodule:: nova
:platform: Unix
:synopsis: Infrastructure-as-a-Service Cloud platform.
.. moduleauthor:: Jesse Andrews <jesse@ansolabs.com>
.. moduleauthor:: Devin Carlen <devin.carlen@gmail.com>
.. moduleauthor:: Vishvananda Ishaya <vishvananda@yahoo.com>
.. moduleauthor:: Joshua McKenty <joshua@cognition.ca>
.. moduleauthor:: Manish Singh <yosh@gimp.org>
.. moduleauthor:: Andy Smith <andy@anarkystic.com>
"""
from exception import *
|
sorenh/cc
|
nova/__init__.py
|
Python
|
apache-2.0
| 1,336
|
<!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_92) on Wed Jul 27 21:19:22 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class net.sourceforge.pmd.lang.java.rule.codesize.StdCyclomaticComplexityRule (PMD 5.5.1 API)</title>
<meta name="date" content="2016-07-27">
<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="Uses of Class net.sourceforge.pmd.lang.java.rule.codesize.StdCyclomaticComplexityRule (PMD 5.5.1 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><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/StdCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">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/sourceforge/pmd/lang/java/rule/codesize/class-use/StdCyclomaticComplexityRule.html" target="_top">Frames</a></li>
<li><a href="StdCyclomaticComplexityRule.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 net.sourceforge.pmd.lang.java.rule.codesize.StdCyclomaticComplexityRule" class="title">Uses of Class<br>net.sourceforge.pmd.lang.java.rule.codesize.StdCyclomaticComplexityRule</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/StdCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">StdCyclomaticComplexityRule</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.sourceforge.pmd.lang.java.rule.codesize">net.sourceforge.pmd.lang.java.rule.codesize</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sourceforge.pmd.lang.java.rule.codesize">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/StdCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">StdCyclomaticComplexityRule</a> in <a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/package-summary.html">net.sourceforge.pmd.lang.java.rule.codesize</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/StdCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">StdCyclomaticComplexityRule</a> in <a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/package-summary.html">net.sourceforge.pmd.lang.java.rule.codesize</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><span class="memberNameLink"><a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/CyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">CyclomaticComplexityRule</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/ModifiedCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">ModifiedCyclomaticComplexityRule</a></span></code>
<div class="block">Implements the modified cyclomatic complexity rule</div>
</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="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../net/sourceforge/pmd/lang/java/rule/codesize/StdCyclomaticComplexityRule.html" title="class in net.sourceforge.pmd.lang.java.rule.codesize">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/sourceforge/pmd/lang/java/rule/codesize/class-use/StdCyclomaticComplexityRule.html" target="_top">Frames</a></li>
<li><a href="StdCyclomaticComplexityRule.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 © 2002–2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p>
</body>
</html>
|
jasonwee/videoOnCloud
|
pmd/pmd-doc-5.5.1/apidocs/net/sourceforge/pmd/lang/java/rule/codesize/class-use/StdCyclomaticComplexityRule.html
|
HTML
|
apache-2.0
| 7,892
|
/**
* Copyright (C) 2013 Carnegie Mellon University
*
* 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 tdb
import akka.actor.ActorRef
import akka.pattern.ask
import scala.collection.immutable
import scala.collection.mutable.Map
import scala.concurrent.Await
import tdb.Constants._
import tdb.ddg._
import tdb.list._
import tdb.messages._
import tdb.TDB._
object TDB {
def createList[T, U](conf: ListConf)
(implicit c: Context): ListInput[T, U] = {
val future = c.masterRef ? CreateListMessage(conf, c.taskId)
val input = Await.result(future.mapTo[ListInput[T, U]], DURATION)
input
}
def getAdjustableList[T, U](input: ListInput[T, U])
(implicit c: Context): AdjustableList[T, U] = {
input.getList(c.resolver)
}
def put[T, U](input: ListInput[T, U], key: T, value: U)
(implicit c: Context) {
val anyInput = input.asInstanceOf[ListInput[Any, Any]]
val timestamp = c.ddg.addPut(anyInput, key, value, c)
if (!c.buffers.contains(anyInput)) {
c.buffers(anyInput) = anyInput.getBuffer()
}
c.buffers(anyInput).putAll(Iterable((key, value)))
timestamp.end = c.ddg.nextTimestamp(timestamp.node, c)
}
def putAll[T, U](input: ListInput[T, U], values: Iterable[(T, U)])
(implicit c: Context) {
val anyInput = input.asInstanceOf[ListInput[Any, Any]]
val timestamp = c.ddg.addPutAll(anyInput, values, c)
if (!c.buffers.contains(anyInput)) {
c.buffers(anyInput) = anyInput.getBuffer()
}
c.buffers(anyInput).putAll(values)
timestamp.end = c.ddg.nextTimestamp(timestamp.node, c)
}
def putIn[T]
(traceable: Traceable[T, _, _], parameters: T)
(implicit c: Context) {
val anyTraceable = traceable.asInstanceOf[Traceable[Any, Any, Any]]
val timestamp = c.ddg.addPutIn(
anyTraceable, parameters.asInstanceOf[Any], c)
if (!c.bufs.contains(traceable.inputId)) {
c.bufs(traceable.inputId) = anyTraceable.getTraceableBuffer()
}
c.bufs(traceable.inputId).putIn(parameters)
timestamp.end = c.ddg.nextTimestamp(timestamp.node, c)
}
def get[T, U](input: ListInput[T, U], key: T)
(getter: U => Unit)
(implicit c: Context): Unit = {
val timestamp =
c.ddg.addGet(
input.asInstanceOf[ListInput[Any, Any]],
key,
getter.asInstanceOf[Any => Unit],
c)
val value = input.get(key, c.taskRef)
getter(value)
timestamp.node.currentModId = c.currentModId
timestamp.end = c.ddg.nextTimestamp(timestamp.node, c)
}
def getFrom[T, U]
(traceable: Traceable[_, T, U], parameters: T)
(getter: U => Unit)
(implicit c: Context) {
val getNode = new GetFromNode(
traceable.asInstanceOf[Traceable[Any, Any, Any]],
parameters.asInstanceOf[Any],
getter.asInstanceOf[Any => Unit])
val timestamp = c.ddg.nextTimestamp(getNode, c)
c.ddg.nodes(c.nextNodeId) = timestamp
val value = traceable.get(parameters, c.nextNodeId, c.taskRef)
getter(value)
c.nextNodeId += 1
timestamp.end = c.ddg.nextTimestamp(timestamp.node, c)
}
def read[T, U](mod: Mod[T])
(reader: T => Changeable[U])
(implicit c: Context): Changeable[U] = {
val value = c.read(mod, c.taskRef)
val timestamp = c.ddg.addRead(
mod.asInstanceOf[Mod[Any]],
value,
reader.asInstanceOf[Any => Changeable[Any]],
c)
val readNode = timestamp.node
val changeable = reader(value)
readNode.currentModId = c.currentModId
timestamp.end = c.ddg.nextTimestamp(readNode, c)
changeable
}
def readAny[T](mod: Mod[T])
(reader: T => Unit)
(implicit c: Context) {
val value = c.read(mod, c.taskRef)
val timestamp = c.ddg.addRead(
mod.asInstanceOf[Mod[Any]],
value,
reader.asInstanceOf[Any => Changeable[Any]],
c)
val readNode = timestamp.node
val ret = reader(value)
readNode.currentModId = c.currentModId
timestamp.end = c.ddg.nextTimestamp(readNode, c)
}
def read2[T, U, V](mod: Mod[T])
(reader: T => (Changeable[U], Changeable[V]))
(implicit c: Context): (Changeable[U], Changeable[V]) = {
val value = c.read(mod, c.taskRef)
val timestamp = c.ddg.addRead(
mod.asInstanceOf[Mod[Any]],
value,
reader.asInstanceOf[Any => Changeable[Any]],
c)
val readNode = timestamp.node
val changeables = reader(value)
readNode.currentModId = c.currentModId
readNode.currentModId2 = c.currentModId2
timestamp.end = c.ddg.nextTimestamp(readNode, c)
changeables
}
def read_2[T, U, V, W](mod1: Mod[T], mod2: Mod[U])
(reader: (T, U) => W)
(implicit c: Context): W = {
val value1 = c.read(mod1, c.taskRef)
val value2 = c.read(mod2, c.taskRef)
val timestamp = c.ddg.addRead2(
mod1.asInstanceOf[Mod[Any]],
mod2.asInstanceOf[Mod[Any]],
value1,
value2,
reader.asInstanceOf[(Any, Any) => Changeable[Any]],
c)
val read2Node = timestamp.node
val changeable = reader(value1, value2)
read2Node.currentModId = c.currentModId
timestamp.end = c.ddg.nextTimestamp(read2Node, c)
changeable
}
def read_3[T, U, V, W](mod1: Mod[T], mod2: Mod[U], mod3: Mod[V])
(reader: (T, U, V) => W)
(implicit c: Context): W = {
val value1 = c.read(mod1, c.taskRef)
val value2 = c.read(mod2, c.taskRef)
val value3 = c.read(mod3, c.taskRef)
val timestamp = c.ddg.addRead3(
mod1.asInstanceOf[Mod[Any]],
mod2.asInstanceOf[Mod[Any]],
mod3.asInstanceOf[Mod[Any]],
value1,
value2,
value3,
reader.asInstanceOf[(Any, Any, Any) => Changeable[Any]],
c)
val read3Node = timestamp.node
val changeable = reader(value1, value2, value3)
read3Node.currentModId = c.currentModId
timestamp.end = c.ddg.nextTimestamp(read3Node, c)
changeable
}
def mod[T](initializer: => Changeable[T])
(implicit c: Context): Mod[T] = {
val mod1 = new Mod[T](c.newModId())
modInternal(initializer, mod1, c)
}
def modInternal[T]
(initializer: => Changeable[T],
mod1: Mod[T],
c: Context): Mod[T] = {
val oldCurrentModId = c.currentModId
c.currentModId = mod1.id
val timestamp = c.ddg.addMod(
mod1.id,
-1,
c)
val modNode = timestamp.node
initializer
timestamp.end = c.ddg.nextTimestamp(modNode, c)
c.currentModId = oldCurrentModId
mod1
}
def write[T](value: T)(implicit c: Context): Changeable[T] = {
c.update(c.currentModId, value)
(new Changeable[T](c.currentModId))
}
def write2[T, U](value: T, value2: U)
(implicit c: Context): (Changeable[T], Changeable[U]) = {
c.update(c.currentModId, value)
c.update(c.currentModId2, value2)
(new Changeable[T](c.currentModId),
new Changeable[U](c.currentModId2))
}
def writeLeft[T, U](value: T, changeable: Changeable[U])
(implicit c: Context): (Changeable[T], Changeable[U]) = {
c.update(c.currentModId, value)
(new Changeable[T](c.currentModId),
new Changeable[U](c.currentModId2))
}
def writeRight[T, U](changeable: Changeable[T], value2: U)
(implicit c: Context): (Changeable[T], Changeable[U]) = {
c.update(c.currentModId2, value2)
(new Changeable[T](c.currentModId),
new Changeable[U](c.currentModId2))
}
def parWithHint[T, U]
(one: Context => T, datastoreId1: TaskId = -1, name1: String = "")
(two: Context => U, datastoreId2: TaskId = -1, name2: String = "")
(implicit c: Context): (T, U) = {
innerPar(one, datastoreId1, name1)(two, datastoreId2, name2)(c)
}
def innerPar[T, U]
(one: Context => T, datastoreId1: TaskId = -1, name1: String = "")
(two: Context => U, datastoreId2: TaskId = -1, name2: String = "")
(implicit c: Context): (T, U) = {
val adjust1 = new Adjustable[T] {
def run(implicit c: Context) = {
one(c)
}
}
val future1 = c.masterRef ? ScheduleTaskMessage(
name1, c.taskId, datastoreId1, adjust1)
val adjust2 = new Adjustable[U] {
def run(implicit c: Context) = {
two(c)
}
}
val future2 = c.masterRef ? ScheduleTaskMessage(
name2, c.taskId, datastoreId2, adjust2)
val (taskId1, oneRet) = Await.result(
future1.mapTo[(TaskId, T)], DURATION)
val (taskId2, twoRet) = Await.result(
future2.mapTo[(TaskId, U)], DURATION)
val parNode = c.ddg.addPar(taskId1, taskId2, c)
(oneRet, twoRet)
}
def par[T](one: Context => T): Parizer[T] = {
new Parizer(one)
}
}
|
twmarshall/tdb
|
core/src/main/scala/tdb/TDB.scala
|
Scala
|
apache-2.0
| 9,130
|
# Agaricus junceus var. cuspidatus Fr., 1875 VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Agaricus junceus var. cuspidatus Fr., 1875
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Entoloma/Entoloma cuspidiferum/ Syn. Agaricus junceus cuspidatus/README.md
|
Markdown
|
apache-2.0
| 237
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* 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 org.zaproxy.addon.automation.gui;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import org.parosproxy.paros.view.View;
import org.zaproxy.addon.automation.jobs.JobUtils;
import org.zaproxy.addon.automation.jobs.SpiderJob;
import org.zaproxy.addon.automation.jobs.SpiderJob.Parameters;
import org.zaproxy.zap.spider.SpiderParam;
import org.zaproxy.zap.spider.SpiderParam.HandleParametersOption;
import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.view.StandardFieldsDialog;
public class SpiderJobDialog extends StandardFieldsDialog {
private static final long serialVersionUID = 1L;
private static final String[] TAB_LABELS = {
"automation.dialog.tab.params",
"automation.dialog.spider.tab.parse",
"automation.dialog.spider.tab.adv"
};
private static final String TITLE = "automation.dialog.spider.title";
private static final String NAME_PARAM = "automation.dialog.all.name";
private static final String CONTEXT_PARAM = "automation.dialog.spider.context";
private static final String URL_PARAM = "automation.dialog.spider.url";
private static final String MAX_DURATION_PARAM = "automation.dialog.spider.maxduration";
private static final String MAX_DEPTH_PARAM = "automation.dialog.spider.maxdepth";
private static final String MAX_CHILDREN_PARAM = "automation.dialog.spider.maxchildren";
private static final String FIELD_ADVANCED = "automation.dialog.spider.advanced";
private static final String ACCEPT_COOKIES_PARAM = "automation.dialog.spider.acceptcookies";
private static final String HANDLE_ODATA_PARAM = "automation.dialog.spider.handleodata";
private static final String HANDLE_PARAMS_PARAM = "automation.dialog.spider.handleparams";
private static final String MAX_PARSE_PARAM = "automation.dialog.spider.maxparse";
private static final String PARSE_COMMENTS_PARAM = "automation.dialog.spider.parsecomments";
private static final String PARSE_GIT_PARAM = "automation.dialog.spider.parsegit";
private static final String PARSE_ROBOTS_PARAM = "automation.dialog.spider.parserobots";
private static final String PARSE_SITEMAP_PARAM = "automation.dialog.spider.parsesitemap";
private static final String PARSE_SVN_PARAM = "automation.dialog.spider.parsessvn";
private static final String POST_FORM_PARAM = "automation.dialog.spider.postform";
private static final String PROCESS_FORM_PARAM = "automation.dialog.spider.processform";
private static final String REQ_WAIT_TIME_PARAM = "automation.dialog.spider.reqwaittime";
private static final String SEND_REFERER_PARAM = "automation.dialog.spider.sendreferer";
private static final String THREAD_COUNT_PARAM = "automation.dialog.spider.threadcount";
private static final String USER_AGENT_PARAM = "automation.dialog.spider.useragent";
private SpiderJob job;
private DefaultComboBoxModel<SpiderParam.HandleParametersOption> handleParamsModel;
public SpiderJobDialog(SpiderJob job) {
super(
View.getSingleton().getMainFrame(),
TITLE,
DisplayUtils.getScaledDimension(500, 400),
TAB_LABELS);
this.job = job;
this.addTextField(0, NAME_PARAM, this.job.getData().getName());
List<String> contextNames = this.job.getEnv().getContextNames();
// Add blank option
contextNames.add(0, "");
this.addComboField(0, CONTEXT_PARAM, contextNames, this.job.getParameters().getContext());
// Cannot select the node as it might not be present in the Sites tree
this.addNodeSelectField(0, URL_PARAM, null, true, false);
Component urlField = this.getField(URL_PARAM);
if (urlField instanceof JTextField) {
((JTextField) urlField).setText(this.job.getParameters().getUrl());
}
this.addNumberField(
0,
MAX_DURATION_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getMaxDuration()));
this.addNumberField(
0,
MAX_DEPTH_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getMaxDepth()));
this.addNumberField(
0,
MAX_CHILDREN_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getMaxChildren()));
this.addCheckBoxField(0, FIELD_ADVANCED, advOptionsSet());
this.addFieldListener(
FIELD_ADVANCED,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setAdvancedTabs(getBoolValue(FIELD_ADVANCED));
}
});
this.addPadding(0);
this.addCheckBoxField(
1,
PARSE_COMMENTS_PARAM,
JobUtils.unBox(this.job.getParameters().getParseComments()));
this.addCheckBoxField(
1, PARSE_GIT_PARAM, JobUtils.unBox(this.job.getParameters().getParseGit()));
this.addCheckBoxField(
1,
PARSE_ROBOTS_PARAM,
JobUtils.unBox(this.job.getParameters().getParseRobotsTxt()));
this.addCheckBoxField(
1,
PARSE_SITEMAP_PARAM,
JobUtils.unBox(this.job.getParameters().getParseSitemapXml()));
this.addCheckBoxField(
1, PARSE_SVN_PARAM, JobUtils.unBox(this.job.getParameters().getParseSVNEntries()));
this.addPadding(1);
this.addNumberField(
2,
MAX_PARSE_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getMaxParseSizeBytes()));
this.addNumberField(
2,
REQ_WAIT_TIME_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getRequestWaitTime()));
this.addNumberField(
2,
THREAD_COUNT_PARAM,
0,
Integer.MAX_VALUE,
JobUtils.unBox(this.job.getParameters().getThreadCount()));
handleParamsModel = new DefaultComboBoxModel<SpiderParam.HandleParametersOption>();
Arrays.stream(SpiderParam.HandleParametersOption.values())
.forEach(v -> handleParamsModel.addElement(v));
DefaultListCellRenderer renderer =
new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(
JList<?> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label =
(JLabel)
super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
if (value instanceof HandleParametersOption) {
// The name is i18n'ed
label.setText(((HandleParametersOption) value).getName());
}
return label;
}
};
SpiderParam.HandleParametersOption hpo = null;
if (this.job.getParameters().getHandleParameters() != null) {
hpo =
SpiderParam.HandleParametersOption.valueOf(
this.job.getParameters().getHandleParameters());
handleParamsModel.setSelectedItem(hpo);
}
this.addComboField(2, HANDLE_PARAMS_PARAM, handleParamsModel);
Component acField = this.getField(HANDLE_PARAMS_PARAM);
if (acField instanceof JComboBox) {
((JComboBox<?>) acField).setRenderer(renderer);
}
this.addCheckBoxField(
2,
ACCEPT_COOKIES_PARAM,
JobUtils.unBox(this.job.getParameters().getAcceptCookies()));
this.addCheckBoxField(
2,
HANDLE_ODATA_PARAM,
JobUtils.unBox(this.job.getParameters().getHandleODataParametersVisited()));
this.addCheckBoxField(
2, POST_FORM_PARAM, JobUtils.unBox(this.job.getParameters().getPostForm()));
this.addCheckBoxField(
2, PROCESS_FORM_PARAM, JobUtils.unBox(this.job.getParameters().getProcessForm()));
this.addCheckBoxField(
2,
SEND_REFERER_PARAM,
JobUtils.unBox(this.job.getParameters().getSendRefererHeader()));
this.addTextField(2, USER_AGENT_PARAM, this.job.getParameters().getUserAgent());
this.addPadding(2);
setAdvancedTabs(getBoolValue(FIELD_ADVANCED));
}
private boolean advOptionsSet() {
Parameters params = this.job.getParameters();
return params.getAcceptCookies() != null
|| params.getHandleODataParametersVisited() != null
|| params.getMaxParseSizeBytes() != null
|| params.getParseComments() != null
|| params.getParseGit() != null
|| params.getParseRobotsTxt() != null
|| params.getParseSitemapXml() != null
|| params.getParseSVNEntries() != null
|| params.getPostForm() != null
|| params.getProcessForm() != null
|| params.getRequestWaitTime() != null
|| params.getSendRefererHeader() != null
|| params.getThreadCount() != null
|| params.getUserAgent() != null;
}
private void setAdvancedTabs(boolean visible) {
// Show/hide all except from the first tab
this.setTabsVisible(
new String[] {
"automation.dialog.spider.tab.parse", "automation.dialog.spider.tab.adv"
},
visible);
}
@Override
public void save() {
this.job.getData().setName(this.getStringValue(NAME_PARAM));
this.job.getParameters().setContext(this.getStringValue(CONTEXT_PARAM));
this.job.getParameters().setUrl(this.getStringValue(URL_PARAM));
this.job.getParameters().setMaxDuration(this.getIntValue(MAX_DURATION_PARAM));
this.job.getParameters().setMaxDepth(this.getIntValue(MAX_DEPTH_PARAM));
this.job.getParameters().setMaxChildren(this.getIntValue(MAX_CHILDREN_PARAM));
if (this.getBoolValue(FIELD_ADVANCED)) {
this.job.getParameters().setAcceptCookies(this.getBoolValue(ACCEPT_COOKIES_PARAM));
this.job
.getParameters()
.setHandleODataParametersVisited(this.getBoolValue(HANDLE_ODATA_PARAM));
this.job.getParameters().setMaxParseSizeBytes(this.getIntValue(MAX_PARSE_PARAM));
this.job.getParameters().setParseComments(this.getBoolValue(PARSE_COMMENTS_PARAM));
this.job.getParameters().setParseGit(this.getBoolValue(PARSE_GIT_PARAM));
this.job.getParameters().setParseRobotsTxt(this.getBoolValue(PARSE_ROBOTS_PARAM));
this.job.getParameters().setParseSitemapXml(this.getBoolValue(PARSE_SITEMAP_PARAM));
this.job.getParameters().setParseSVNEntries(this.getBoolValue(PARSE_SVN_PARAM));
this.job.getParameters().setPostForm(this.getBoolValue(POST_FORM_PARAM));
this.job.getParameters().setProcessForm(this.getBoolValue(PROCESS_FORM_PARAM));
this.job.getParameters().setRequestWaitTime(this.getIntValue(REQ_WAIT_TIME_PARAM));
this.job.getParameters().setSendRefererHeader(this.getBoolValue(SEND_REFERER_PARAM));
this.job.getParameters().setUserAgent(this.getStringValue(USER_AGENT_PARAM));
Object hpoObj = handleParamsModel.getSelectedItem();
if (hpoObj instanceof SpiderParam.HandleParametersOption) {
SpiderParam.HandleParametersOption hpo =
(SpiderParam.HandleParametersOption) hpoObj;
this.job.getParameters().setHandleParameters(hpo.name());
}
} else {
this.job.getParameters().setAcceptCookies(null);
this.job.getParameters().setHandleODataParametersVisited(null);
this.job.getParameters().setMaxParseSizeBytes(null);
this.job.getParameters().setParseComments(null);
this.job.getParameters().setParseGit(null);
this.job.getParameters().setParseRobotsTxt(null);
this.job.getParameters().setParseSitemapXml(null);
this.job.getParameters().setParseSVNEntries(null);
this.job.getParameters().setPostForm(null);
this.job.getParameters().setProcessForm(null);
this.job.getParameters().setRequestWaitTime(null);
this.job.getParameters().setSendRefererHeader(null);
this.job.getParameters().setUserAgent(null);
this.job.getParameters().setHandleParameters(null);
}
this.job.setChanged();
}
@Override
public String validateFields() {
// Nothing to do TODO validate url - coping with envvars :O
return null;
}
}
|
secdec/zap-extensions
|
addOns/automation/src/main/java/org/zaproxy/addon/automation/gui/SpiderJobDialog.java
|
Java
|
apache-2.0
| 14,619
|
package cz.atlascon.travny.graphql.output;
import cz.atlascon.travny.schemas.Field;
import graphql.schema.DataFetcher;
/**
* Create DataFetcher for given field and Travny source object
*/
public interface TravnyFieldDataFetcherFactory {
DataFetcher create(Field field);
}
|
atlascon/travny
|
travny-graphql/src/main/java/cz/atlascon/travny/graphql/output/TravnyFieldDataFetcherFactory.java
|
Java
|
apache-2.0
| 282
|
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter.
public class ELe extends PureExp {
public final PureExp pureexp_1, pureexp_2;
public ELe(PureExp p1, PureExp p2) { pureexp_1 = p1; pureexp_2 = p2; }
public <R,A> R accept(bnfc.abs.Absyn.PureExp.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof bnfc.abs.Absyn.ELe) {
bnfc.abs.Absyn.ELe x = (bnfc.abs.Absyn.ELe)o;
return this.pureexp_1.equals(x.pureexp_1) && this.pureexp_2.equals(x.pureexp_2);
}
return false;
}
public int hashCode() {
return 37*(this.pureexp_1.hashCode())+this.pureexp_2.hashCode();
}
}
|
CrispOSS/jabsc
|
src/main/java/bnfc/abs/Absyn/ELe.java
|
Java
|
apache-2.0
| 711
|
# -*- coding: utf-8 -*-
import pytest
# ``py.test --runslow`` causes the entire testsuite to be run, including test
# that are decorated with ``@@slow`` (scaffolding tests).
# see http://pytest.org/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option # Noqa
## def pytest_addoption(parser):
## parser.addoption("--runslow", action="store_true", help="run slow tests")
## slow = pytest.mark.skipif(
## not pytest.config.getoption("--runslow"),
## reason="need --runslow option to run"
## )
|
bird-house/pyramid-phoenix
|
phoenix/tests/conftest.py
|
Python
|
apache-2.0
| 542
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>OR-Tools</title>
<meta http-equiv="Content-Type" content="text/html;"/>
<meta charset="utf-8"/>
<!--<link rel='stylesheet' type='text/css' href="https://fonts.googleapis.com/css?family=Ubuntu:400,700,400italic"/>-->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="banner-container">
<div id="banner">
<span id="sfml">Google OR-Tools 9.2</span>
</div>
</div>
<div id="content" style="width: 100%; overflow: hidden;">
<div style="margin-left: 15px; margin-top: 5px; float: left; color: #145A32;">
<h2>C++ Reference</h2>
<ul>
<li><a href="../cpp_algorithms/annotated.html">Algorithms</a></li>
<li><a href="../cpp_sat/annotated.html">CP-SAT</a></li>
<li><a href="../cpp_graph/annotated.html">Graph</a></li>
<li><a href="../cpp_routing/annotated.html">Routing</a></li>
<li><a href="../cpp_linear/annotated.html">Linear solver</a></li>
</ul>
</div>
<div id="content">
<div align="center">
<h1 style="color: #145A32;">C++ Reference: Routing</h1>
</div>
<!-- Generated by Doxygen 1.9.2 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search",'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(document).ready(function(){initNavTree('classoperations__research_1_1_decision_builder.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="classoperations__research_1_1_decision_builder-members.html">List of all members</a> </div>
<div class="headertitle"><div class="title">DecisionBuilder<span class="mlabels"><span class="mlabel">abstract</span></span></div></div>
</div><!--header-->
<div class="contents">
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p >A <a class="el" href="classoperations__research_1_1_decision_builder.html" title="A DecisionBuilder is responsible for creating the search tree.">DecisionBuilder</a> is responsible for creating the search tree. </p>
<p >The important method is <a class="el" href="classoperations__research_1_1_decision_builder.html#a56fb7470075432c3b0870a1a1d1fcb02" title="This is the main method of the decision builder class.">Next()</a>, which returns the next decision to execute. </p>
<p class="definition">Definition at line <a class="el" href="constraint__solver_8h_source.html#l03285">3285</a> of file <a class="el" href="constraint__solver_8h_source.html">constraint_solver.h</a>.</p>
</div><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a id="pub-methods" name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:ac822e3c8055eeace0165357c9b35a490"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#ac822e3c8055eeace0165357c9b35a490">DecisionBuilder</a> ()</td></tr>
<tr class="separator:ac822e3c8055eeace0165357c9b35a490"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad3bd886b44a7c315a2ed7b5da09798aa"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#ad3bd886b44a7c315a2ed7b5da09798aa">~DecisionBuilder</a> () override</td></tr>
<tr class="separator:ad3bd886b44a7c315a2ed7b5da09798aa"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a56fb7470075432c3b0870a1a1d1fcb02"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classoperations__research_1_1_decision.html">Decision</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#a56fb7470075432c3b0870a1a1d1fcb02">Next</a> (<a class="el" href="classoperations__research_1_1_solver.html">Solver</a> *const s)=0</td></tr>
<tr class="memdesc:a56fb7470075432c3b0870a1a1d1fcb02"><td class="mdescLeft"> </td><td class="mdescRight">This is the main method of the decision builder class. <a href="classoperations__research_1_1_decision_builder.html#a56fb7470075432c3b0870a1a1d1fcb02">More...</a><br /></td></tr>
<tr class="separator:a56fb7470075432c3b0870a1a1d1fcb02"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aed804747c45a7e1caf81461f9e45dd91"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#aed804747c45a7e1caf81461f9e45dd91">DebugString</a> () const override</td></tr>
<tr class="separator:aed804747c45a7e1caf81461f9e45dd91"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a952c3ef185d196855cc6c5f2b7ab749c"><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#a952c3ef185d196855cc6c5f2b7ab749c">AppendMonitors</a> (<a class="el" href="classoperations__research_1_1_solver.html">Solver</a> *const solver, std::vector< <a class="el" href="classoperations__research_1_1_search_monitor.html">SearchMonitor</a> * > *const extras)</td></tr>
<tr class="memdesc:a952c3ef185d196855cc6c5f2b7ab749c"><td class="mdescLeft"> </td><td class="mdescRight">This method will be called at the start of the search. <a href="classoperations__research_1_1_decision_builder.html#a952c3ef185d196855cc6c5f2b7ab749c">More...</a><br /></td></tr>
<tr class="separator:a952c3ef185d196855cc6c5f2b7ab749c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:afcde421cf076575a27bed81c80093ac8"><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#afcde421cf076575a27bed81c80093ac8">Accept</a> (<a class="el" href="classoperations__research_1_1_model_visitor.html">ModelVisitor</a> *const visitor) const</td></tr>
<tr class="separator:afcde421cf076575a27bed81c80093ac8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad5260b9627048b854b45d05ed34adc22"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#ad5260b9627048b854b45d05ed34adc22">set_name</a> (const std::string &name)</td></tr>
<tr class="separator:ad5260b9627048b854b45d05ed34adc22"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9a98946a64f3893b085f650932c9dfee"><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_decision_builder.html#a9a98946a64f3893b085f650932c9dfee">GetName</a> () const</td></tr>
<tr class="separator:a9a98946a64f3893b085f650932c9dfee"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a id="ac822e3c8055eeace0165357c9b35a490" name="ac822e3c8055eeace0165357c9b35a490"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ac822e3c8055eeace0165357c9b35a490">◆ </a></span>DecisionBuilder()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classoperations__research_1_1_decision_builder.html">DecisionBuilder</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p class="definition">Definition at line <a class="el" href="constraint__solver_8h_source.html#l03287">3287</a> of file <a class="el" href="constraint__solver_8h_source.html">constraint_solver.h</a>.</p>
</div>
</div>
<a id="ad3bd886b44a7c315a2ed7b5da09798aa" name="ad3bd886b44a7c315a2ed7b5da09798aa"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ad3bd886b44a7c315a2ed7b5da09798aa">◆ </a></span>~DecisionBuilder()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">~<a class="el" href="classoperations__research_1_1_decision_builder.html">DecisionBuilder</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p class="definition">Definition at line <a class="el" href="constraint__solver_8h_source.html#l03288">3288</a> of file <a class="el" href="constraint__solver_8h_source.html">constraint_solver.h</a>.</p>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a id="afcde421cf076575a27bed81c80093ac8" name="afcde421cf076575a27bed81c80093ac8"></a>
<h2 class="memtitle"><span class="permalink"><a href="#afcde421cf076575a27bed81c80093ac8">◆ </a></span>Accept()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual void Accept </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classoperations__research_1_1_model_visitor.html">ModelVisitor</a> *const </td>
<td class="paramname"><em>visitor</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Reimplemented in <a class="el" href="classoperations__research_1_1_profiled_decision_builder.html#aa30c84aec5e60d6b74e1e1eb15011d4a">ProfiledDecisionBuilder</a>.</p>
</div>
</div>
<a id="a952c3ef185d196855cc6c5f2b7ab749c" name="a952c3ef185d196855cc6c5f2b7ab749c"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a952c3ef185d196855cc6c5f2b7ab749c">◆ </a></span>AppendMonitors()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual void AppendMonitors </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classoperations__research_1_1_solver.html">Solver</a> *const </td>
<td class="paramname"><em>solver</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">std::vector< <a class="el" href="classoperations__research_1_1_search_monitor.html">SearchMonitor</a> * > *const </td>
<td class="paramname"><em>extras</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>This method will be called at the start of the search. </p>
<p >It asks the decision builder if it wants to append search monitors to the list of active monitors for this search. Please note there are no checks at this point for duplication. </p>
<p>Reimplemented in <a class="el" href="classoperations__research_1_1_profiled_decision_builder.html#a5be468994928418ddc2cbb43742d781b">ProfiledDecisionBuilder</a>.</p>
</div>
</div>
<a id="aed804747c45a7e1caf81461f9e45dd91" name="aed804747c45a7e1caf81461f9e45dd91"></a>
<h2 class="memtitle"><span class="permalink"><a href="#aed804747c45a7e1caf81461f9e45dd91">◆ </a></span>DebugString()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">std::string DebugString </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Reimplemented from <a class="el" href="classoperations__research_1_1_base_object.html#a8eba5d533fa9df4617c1868d3ec2afc4">BaseObject</a>.</p>
<p>Reimplemented in <a class="el" href="classoperations__research_1_1_profiled_decision_builder.html#aed804747c45a7e1caf81461f9e45dd91">ProfiledDecisionBuilder</a>.</p>
</div>
</div>
<a id="a9a98946a64f3893b085f650932c9dfee" name="a9a98946a64f3893b085f650932c9dfee"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a9a98946a64f3893b085f650932c9dfee">◆ </a></span>GetName()</h2>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string GetName </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a id="a56fb7470075432c3b0870a1a1d1fcb02" name="a56fb7470075432c3b0870a1a1d1fcb02"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a56fb7470075432c3b0870a1a1d1fcb02">◆ </a></span>Next()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="classoperations__research_1_1_decision.html">Decision</a> * Next </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classoperations__research_1_1_solver.html">Solver</a> *const </td>
<td class="paramname"><em>s</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">pure virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>This is the main method of the decision builder class. </p>
<p >It must return a decision (an instance of the class <a class="el" href="classoperations__research_1_1_decision.html" title="A Decision represents a choice point in the search tree.">Decision</a>). If it returns nullptr, this means that the decision builder has finished its work. </p>
<p>Implemented in <a class="el" href="classoperations__research_1_1_profiled_decision_builder.html#ad7f92654b8e5be833b185bd72f6c1e24">ProfiledDecisionBuilder</a>.</p>
</div>
</div>
<a id="ad5260b9627048b854b45d05ed34adc22" name="ad5260b9627048b854b45d05ed34adc22"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ad5260b9627048b854b45d05ed34adc22">◆ </a></span>set_name()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void set_name </td>
<td>(</td>
<td class="paramtype">const std::string & </td>
<td class="paramname"><em>name</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p class="definition">Definition at line <a class="el" href="constraint__solver_8h_source.html#l03304">3304</a> of file <a class="el" href="constraint__solver_8h_source.html">constraint_solver.h</a>.</p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="constraint__solver_8h_source.html">constraint_solver.h</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
</div>
</div>
<div id="footer-container">
<div id="footer">
</div>
</div>
</body>
</html>
|
google/or-tools
|
docs/cpp_routing/classoperations__research_1_1_decision_builder.html
|
HTML
|
apache-2.0
| 18,388
|
# AUTOGENERATED FILE
FROM balenalib/generic-alpine:3.11-build
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.7-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.7-openjdk/jre/bin:/usr/lib/jvm/java-1.7-openjdk/bin
RUN set -x \
&& apk add --no-cache \
openjdk7 \
&& [ "$JAVA_HOME" = "$(docker-java-home)" ]
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Alpine Linux 3.11 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v7-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/openjdk/generic/alpine/3.11/7-jdk/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 1,771
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
import org.bson.BsonDocument;
import org.bson.Document;
import com.flipkart.zjsonpatch.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
/**
* Created by sundarvenkata on 06/02/17.
*/
public class CreateCombinedAnnotation {
public static void CreateCombinedAnnotationSnappy ()
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
MainApp.recreateCollection(db, "var_annot_comb_85_87_snappy", null);
MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
MongoCollection<Document> combinedColl = db.getCollection("var_annot_comb_85_87_snappy");
int counter = 0;
for (Document doc:
annotColl2.find()) {
String idString = doc.get("_id").toString();
Document coll1AnnotObj = (Document)(annotColl1.find(eq("_id",idString)).first());
Document combinedDoc = new Document();
Document combinedAnnotDoc = new Document();
coll1AnnotObj.remove("_id");
doc.remove("_id");
combinedAnnotDoc.put("ver1", coll1AnnotObj);
combinedAnnotDoc.put("ver2", doc);
combinedDoc.put("_id", idString);
combinedDoc.put("annot", combinedAnnotDoc);
combinedColl.insertOne(combinedDoc);
counter += 1;
}
mongoClient.close();
}
public static void CreateCombinedAnnotationZlib ()
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
CreateCollectionOptions options = new CreateCollectionOptions();
options.storageEngineOptions(BsonDocument.parse("{'wiredTiger':{'configString':'block_compressor=zlib'}}"));
MainApp.recreateCollection(db, "var_annot_comb_85_87_zlib", options);
MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
MongoCollection<Document> combinedColl = db.getCollection("var_annot_comb_85_87_zlib");
int counter = 0;
for (Document doc:
annotColl2.find()) {
String idString = doc.get("_id").toString();
Document coll1AnnotObj = (Document)(annotColl1.find(eq("_id",idString)).first());
Document combinedDoc = new Document();
Document combinedAnnotDoc = new Document();
coll1AnnotObj.remove("_id");
doc.remove("_id");
combinedAnnotDoc.put("ver1", coll1AnnotObj);
combinedAnnotDoc.put("ver2", doc);
combinedDoc.put("_id", idString);
combinedDoc.put("annot", combinedAnnotDoc);
combinedColl.insertOne(combinedDoc);
counter += 1;
}
mongoClient.close();
}
public static void CreateCombinedAnnotationZlibSep ()
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
CreateCollectionOptions options = new CreateCollectionOptions();
options.storageEngineOptions(BsonDocument.parse("{'wiredTiger':{'configString':'block_compressor=zlib'}}"));
MainApp.recreateCollection(db, "var_annot_comb_85_87_zlib_sep", options);
MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
MongoCollection<Document> combinedColl = db.getCollection("var_annot_comb_85_87_zlib_sep");
int counter = 0;
for (Document doc:
annotColl2.find()) {
String idString = doc.get("_id").toString();
Document coll1AnnotObj = (Document)(annotColl1.find(eq("_id",idString)).first());
Document combinedDoc = new Document();
Document combinedAnnotDoc = new Document();
combinedDoc.put("_id", idString + "_85_85");
combinedDoc.put("ct", doc.get("ct"));
combinedDoc.put("xrefs", doc.get("xrefs"));
combinedColl.insertOne(combinedDoc);
combinedDoc.put("_id", idString + "_87_87");
combinedDoc.put("ct", coll1AnnotObj.get("ct"));
combinedDoc.put("xrefs", coll1AnnotObj.get("xrefs"));
combinedColl.insertOne(combinedDoc);
counter += 1;
}
mongoClient.close();
}
public static void CreateCombinedAnnotationPatchSnappy () throws IOException
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
MainApp.recreateCollection(db, "var_annot_comb_85_87_patch_snappy", null);
MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
MongoCollection<Document> combinedColl = db.getCollection("var_annot_comb_85_87_patch_snappy");
final ObjectMapper mapper = new ObjectMapper();
int counter = 0;
for (Document doc:
annotColl2.find()) {
String idString = doc.get("_id").toString();
Document coll1AnnotObj = (Document)(annotColl1.find(eq("_id",idString)).first());
coll1AnnotObj.remove("_id");
doc.remove("_id");
String patchString = JsonDiff.asJson(mapper.readTree(doc.toJson()), mapper.readTree(coll1AnnotObj.toJson())).toString();
Document combinedDoc = new Document();
Document combinedAnnotDoc = new Document();
combinedAnnotDoc.put("ver1", coll1AnnotObj);
combinedAnnotDoc.put("ver2", patchString);
combinedDoc.put("_id", idString);
combinedDoc.put("annot", combinedAnnotDoc);
combinedColl.insertOne(combinedDoc);
counter += 1;
}
mongoClient.close();
}
public static void CreateCombinedAnnotationPatchZlib () throws IOException
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
CreateCollectionOptions options = new CreateCollectionOptions();
options.storageEngineOptions(BsonDocument.parse("{'wiredTiger':{'configString':'block_compressor=zlib'}}"));
MainApp.recreateCollection(db, "var_annot_comb_85_87_patch_zlib", options);
MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
MongoCollection<Document> combinedColl = db.getCollection("var_annot_comb_85_87_patch_zlib");
final ObjectMapper mapper = new ObjectMapper();
int counter = 0;
for (Document doc:
annotColl2.find()) {
String idString = doc.get("_id").toString();
Document coll1AnnotObj = (Document)(annotColl1.find(eq("_id",idString)).first());
coll1AnnotObj.remove("_id");
doc.remove("_id");
String patchString = JsonDiff.asJson(mapper.readTree(doc.toJson()), mapper.readTree(coll1AnnotObj.toJson())).toString();
Document combinedDoc = new Document();
Document combinedAnnotDoc = new Document();
combinedAnnotDoc.put("ver1", coll1AnnotObj);
combinedAnnotDoc.put("ver2", patchString);
combinedDoc.put("_id", idString);
combinedDoc.put("annot", combinedAnnotDoc);
combinedColl.insertOne(combinedDoc);
counter += 1;
}
mongoClient.close();
}
public static void MoveAnnotToZlibCollection () throws IOException
{
MongoClient mongoClient = new MongoClient(new MongoClientURI(String.format("mongodb://%s:%s@%s:27017/admin",System.getenv("MONGODEV_UNAME"), System.getenv("MONGODEV_PASS"), System.getenv("MONGODEV_HOST"))));
MongoDatabase db = mongoClient.getDatabase("eva_testing");
//CreateCollectionOptions options = new CreateCollectionOptions();
//options.storageEngineOptions(BsonDocument.parse("{'wiredTiger':{'configString':'block_compressor=zlib'}}"));
//MainApp.recreateCollection(db, "variants_annot_85_85_zlib", options);
//MainApp.recreateCollection(db, "variants_annot_85_85_zlib", options);
//MongoCollection<Document> annotColl1 = db.getCollection("variants_annot_87_87");
MongoCollection<Document> annotColl2 = db.getCollection("variants_annot_85_85");
//MongoCollection<Document> annotColl1Zlib = db.getCollection("variants_annot_87_87_zlib");
MongoCollection<Document> annotColl2Zlib = db.getCollection("variants_annot_85_85_zlib");
for (Document doc: annotColl2.find()) {annotColl2Zlib.insertOne(doc);}
mongoClient.close();
}
}
|
EBIvariation/examples
|
JavaMongo/src/main/java/CreateCombinedAnnotation.java
|
Java
|
apache-2.0
| 10,154
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.workbench.common.stunner.bpmn.client.forms.fields.timerEditor;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.kie.workbench.common.stunner.bpmn.client.forms.util.FieldEditorPresenter;
import org.kie.workbench.common.stunner.bpmn.client.forms.util.FieldEditorPresenterBaseTest;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.timer.TimerSettingsValue;
import org.mockito.ArgumentCaptor;
import static org.junit.Assert.assertEquals;
import static org.kie.workbench.common.stunner.bpmn.client.forms.fields.timerEditor.TimerSettingsFieldEditorPresenter.TIME_CYCLE_LANGUAGE;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class TimerSettingsFieldEditorPresenterTest
extends FieldEditorPresenterBaseTest<TimerSettingsValue, TimerSettingsFieldEditorPresenter, TimerSettingsFieldEditorPresenter.View> {
private static final String VALUE_1 = "VALUE_1";
private static final String VALUE_2 = "VALUE_2";
@Before
public void setUp() {
super.setUp();
verify(view,
times(1)).setTimeCycleLanguageOptions(anyList(),
eq(TIME_CYCLE_LANGUAGE.ISO.value()));
verifyHideParams(1);
verifyDurationTimerDisplayMode(1,
true);
}
@Override
public ArgumentCaptor<TimerSettingsValue> newArgumentCaptor() {
return ArgumentCaptor.forClass(TimerSettingsValue.class);
}
@Override
public TimerSettingsFieldEditorPresenter.View mockEditorView() {
return mock(TimerSettingsFieldEditorPresenter.View.class);
}
@Override
public TimerSettingsFieldEditorPresenter newEditorPresenter(TimerSettingsFieldEditorPresenter.View view) {
return new TimerSettingsFieldEditorPresenter(view);
}
@SuppressWarnings("unchecked")
@Override
public FieldEditorPresenter.ValueChangeHandler<TimerSettingsValue> mockChangeHandler() {
return mock(FieldEditorPresenter.ValueChangeHandler.class);
}
@Test
public void testSetDurationTimerValue() {
TimerSettingsValue value = new TimerSettingsValue();
value.setTimeDuration(VALUE_1);
editor.setValue(value);
verify(view,
times(1)).clear();
verifyHideParams(3);
verifyDurationTimerDisplayMode(3,
true);
verify(view,
times(1)).setTimeDuration(VALUE_1);
}
@Test
public void testSetTimeDateTimerValue() {
TimerSettingsValue value = new TimerSettingsValue();
value.setTimeDate(VALUE_1);
editor.setValue(value);
verifyHideParams(3);
verify(view,
times(1)).clear();
verifyDurationTimerDisplayMode(2,
true);
verifyTimeDateTimerDisplayMode(1,
true);
verify(view,
times(1)).setTimeDate(VALUE_1);
}
@Test
public void testTimeCycleTimerValue() {
TimerSettingsValue value = new TimerSettingsValue();
value.setTimeCycleLanguage(TIME_CYCLE_LANGUAGE.ISO.value());
value.setTimeCycle(VALUE_1);
editor.setValue(value);
verifyHideParams(3);
verify(view,
times(1)).clear();
verifyDurationTimerDisplayMode(2,
true);
verifyMultipleTimerDisplayMode(1,
true);
verify(view,
times(1)).setTimeCycleLanguage(TIME_CYCLE_LANGUAGE.ISO.value());
verify(view,
times(1)).setTimeCycle(VALUE_1);
}
@Test
public void testOnTimerDurationChange() {
TimerSettingsValue value = new TimerSettingsValue();
editor.setValue(value);
when(view.getTimeDuration()).thenReturn(VALUE_1);
editor.onTimerDurationChange();
verify(changeHandler,
times(1)).onValueChange(oldValueCaptor.capture(),
newValueCaptor.capture());
assertEquals(value,
oldValueCaptor.getValue());
value.setTimeDuration(VALUE_1);
assertEquals(value,
newValueCaptor.getValue());
}
@Test
public void testOnTimeCycleChange() {
TimerSettingsValue value = new TimerSettingsValue();
editor.setValue(value);
when(view.getTimeCycle()).thenReturn(VALUE_1);
when(view.getTimeCycleLanguage()).thenReturn(VALUE_2);
editor.onTimeCycleChange();
verifyMultipleTimerChange(value);
}
@Test
public void testOnTimeCycleLanguage() {
TimerSettingsValue value = new TimerSettingsValue();
editor.setValue(value);
when(view.getTimeCycle()).thenReturn(VALUE_1);
when(view.getTimeCycleLanguage()).thenReturn(VALUE_2);
editor.onTimeCycleLanguageChange();
verifyMultipleTimerChange(value);
}
private void verifyMultipleTimerChange(TimerSettingsValue oldValue) {
verify(changeHandler,
times(1)).onValueChange(oldValueCaptor.capture(),
newValueCaptor.capture());
assertEquals(oldValue,
oldValueCaptor.getValue());
oldValue.setTimeCycle(VALUE_1);
oldValue.setTimeCycleLanguage(VALUE_2);
assertEquals(oldValue,
newValueCaptor.getValue());
}
@Test
public void testOnTimeDateChange() {
TimerSettingsValue value = new TimerSettingsValue();
editor.setValue(value);
when(view.getTimeDate()).thenReturn(VALUE_1);
editor.onTimeDateChange();
verify(changeHandler,
times(1)).onValueChange(oldValueCaptor.capture(),
newValueCaptor.capture());
assertEquals(value,
oldValueCaptor.getValue());
value.setTimeDate(VALUE_1);
assertEquals(value,
newValueCaptor.getValue());
}
@Test
public void testOnMultipleTimerSelected() {
editor.onMultipleTimerSelected();
verifyHideParams(2);
verifyMultipleTimerDisplayMode(1,
false);
verify(editor,
times(1)).onMultipleTimerValuesChange();
}
@Test
public void testOnDurationTimerSelected() {
editor.onDurationTimerSelected();
verifyHideParams(2);
verifyDurationTimerDisplayMode(2,
false);
verify(editor,
times(1)).onTimerDurationChange();
}
@Test
public void testOnDateTimerSelected() {
editor.onDateTimerSelected();
verifyHideParams(2);
verifyTimeDateTimerDisplayMode(1,
false);
verify(editor,
times(1)).onTimeDateChange();
}
@Test
public void testOnShowTimeDateTimePickerWithValidDate() {
Date date = new Date();
when(view.getTimeDate()).thenReturn(VALUE_1);
when(view.parseFromISO(VALUE_1)).thenReturn(date);
editor.onShowTimeDateTimePicker();
verify(view,
times(1)).setTimeDateTimePickerValue(date);
verify(view,
times(1)).showTimeDate(false);
}
@Test
public void testOnShowTimeDateTimePickerWithInValidDate() {
when(view.getTimeDate()).thenReturn(VALUE_1);
when(view.parseFromISO(VALUE_1)).thenThrow(new IllegalArgumentException("irrelevant"));
editor.onShowTimeDateTimePicker();
verify(view,
times(1)).setTimeDateTimePickerValue(VALUE_1);
verify(view,
times(1)).showTimeDate(false);
}
@Test
public void testOnTimeDateTimePickerChange() {
Date value = new Date();
when(view.getTimeDateTimePickerValue()).thenReturn(value);
when(view.formatToISO(value)).thenReturn(VALUE_1);
editor.onTimeDateTimePickerChange();
verify(view,
times(1)).formatToISO(value);
verify(view,
times(1)).setTimeDate(VALUE_1);
}
@Test
public void testOnTimeDateTimePickerHidden() {
editor.onTimeDateTimePickerHidden();
verify(view,
times(1)).showTimeDate(true);
verify(view,
times(2)).showTimeDateTimePicker(false);
}
private void verifyDurationTimerDisplayMode(int times,
boolean setRadioChecked) {
verify(view,
times(times)).showDurationTimerParams(true);
if (setRadioChecked) {
verify(view,
times(times)).setDurationTimerChecked(true);
}
}
private void verifyTimeDateTimerDisplayMode(int times,
boolean setRadioChecked) {
verify(view,
times(times)).showDateTimerParams(true);
if (setRadioChecked) {
verify(view,
times(times)).setDateTimerChecked(true);
}
}
private void verifyMultipleTimerDisplayMode(int times,
boolean setRadioChecked) {
verify(view,
times(times)).showMultipleTimerParams(true);
if (setRadioChecked) {
verify(view,
times(times)).setMultipleTimerChecked(true);
}
}
private void verifyHideParams(int times) {
verify(view,
times(times)).showDurationTimerParams(false);
verify(view,
times(times)).showMultipleTimerParams(false);
verify(view,
times(times)).showDateTimerParams(false);
}
}
|
etirelli/kie-wb-common
|
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-client/src/test/java/org/kie/workbench/common/stunner/bpmn/client/forms/fields/timerEditor/TimerSettingsFieldEditorPresenterTest.java
|
Java
|
apache-2.0
| 10,677
|
package xworker.http.actions.jfreechart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.xmeta.ActionContext;
import org.xmeta.ActionException;
import org.xmeta.Bindings;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.util.UtilData;
import org.xmeta.util.UtilMap;
import ognl.OgnlException;
import xworker.chart.jfree.dataobject.DataObjectChart;
import xworker.chart.jfree.dataobject.DataObjectChartFactory;
import xworker.dataObject.DataObject;
public class JFreechartActions {
@SuppressWarnings("unchecked")
public static byte[] exportImage(ActionContext actionContext) throws OgnlException, IOException{
Thing self = (Thing) actionContext.get("self");
List<DataObject> doAction = (List<DataObject>) self.doAction("getDatas", actionContext);
List<DataObject> datas = doAction;
if(datas == null){
throw new ActionException("datas is null, path=" + self.getMetadata().getPath());
}
JFreeChart chart = (JFreeChart) self.doAction("getJFreechart", actionContext, UtilMap.toMap("datas", datas));
if(chart == null){
throw new ActionException("jfreechart is null, path=" + self.getMetadata().getPath());
}
int width = self.getInt("width", 100, actionContext);
int height = self.getInt("height", 200, actionContext);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ChartUtilities.writeChartAsPNG(bout, chart, width, height);
byte[] bytes = bout.toByteArray();
if(self.getBoolean("exportToServlet")){
HttpServletResponse response = (HttpServletResponse) actionContext.get("response");
response.setContentType("image/x-png;image/png");
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
}
return bytes;
}
@SuppressWarnings("unchecked")
public static List<DataObject> getDatas(ActionContext actionContext) throws OgnlException{
Thing self = (Thing) actionContext.get("self");
//去变量
String datasStr = self.getStringBlankAsNull("datas");
if(datasStr != null){
return (List<DataObject>) UtilData.getData(self, "datas", actionContext);
}
//通过query查询
Thing query = null;
if(self.getStringBlankAsNull("queryPath") != null){
query = World.getInstance().getThing(self.getString("queryPath"));
}else{
query = self.getThing("Query@0");
}
if(query != null){
return (List<DataObject>) query.getAction().run(actionContext);
}
return null;
}
@SuppressWarnings("unchecked")
public static JFreeChart getJFreechart(ActionContext actionContext) throws IOException{
Thing self = (Thing) actionContext.get("self");
List<DataObject> datas = (List<DataObject>) actionContext.get("datas");
Thing jfree = null;
if(self.getStringBlankAsNull("jfreechartPath") != null){
jfree = World.getInstance().getThing(self.getString("jfreechartPath"));
}else{
jfree = self.getThing("JFreechart@0");
}
if(jfree != null){
try{
Bindings bindings = actionContext.push();
bindings.put("self", jfree);
DataObjectChart chart = DataObjectChartFactory.create(actionContext, datas);
if(chart != null){
return chart.chart;
}
}finally{
actionContext.pop();
}
}
return null;
}
}
|
x-meta/xworker
|
xworker_jfreechart/src/main/java/xworker/http/actions/jfreechart/JFreechartActions.java
|
Java
|
apache-2.0
| 3,501
|
// //
// Copyright 2019 Mirko Raner //
// //
// 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 pro.projo.internal;
import java.lang.reflect.Method;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PredicatesTest
{
static interface Complex
{
Number getReal();
void setReal(Number real);
Number getImaginary();
void setImaginary(Number imaginary);
default Number getZero()
{
return 0;
}
@Override
int hashCode();
}
@Test
public void testGetterPredicate() throws Exception
{
Method setReal = Complex.class.getDeclaredMethod("setReal", Number.class);
assertFalse(Predicates.getter.test(setReal));
}
@Test
public void testGetterPredicateIsGetter() throws Exception
{
Method getZero = Complex.class.getDeclaredMethod("getZero");
assertFalse(Predicates.getter.test(getZero));
}
@Test
public void testDefaultMethodIsNotAGetter() throws Exception
{
Method getReal = Complex.class.getDeclaredMethod("getReal");
assertTrue(Predicates.getter.test(getReal));
}
@Test
public void testGetterPredicateObjectHashCodeIsNotGetter() throws Exception
{
Method hashCode = Object.class.getDeclaredMethod("hashCode");
assertFalse(Predicates.getter.test(hashCode));
}
@Test
public void testGetterPredicateHashCodeIsNotGetter() throws Exception
{
Method hashCode = Complex.class.getDeclaredMethod("hashCode");
assertFalse(Predicates.getter.test(hashCode));
}
@Test
public void testGetterPredicateNotifyIsNotGetter() throws Exception
{
Method notify = Object.class.getDeclaredMethod("notify");
assertFalse(Predicates.getter.test(notify));
}
@Test
public void testSetterPredicate() throws Exception
{
Method setReal = Complex.class.getDeclaredMethod("setReal", Number.class);
assertTrue(Predicates.setter.test(setReal));
}
@Test
public void testSetterPredicateWaitIsNotSetter() throws Exception
{
Method wait = Object.class.getDeclaredMethod("wait", long.class);
assertFalse(Predicates.setter.test(wait));
}
}
|
raner/projo
|
projo/src/test/java/pro/projo/internal/PredicatesTest.java
|
Java
|
apache-2.0
| 3,414
|
/*
* Copyright 2012-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.
*/
package com.amazonaws.services.ec2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* CreateDhcpOptionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateDhcpOptionsResultStaxUnmarshaller implements Unmarshaller<CreateDhcpOptionsResult, StaxUnmarshallerContext> {
public CreateDhcpOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
CreateDhcpOptionsResult createDhcpOptionsResult = new CreateDhcpOptionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return createDhcpOptionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("dhcpOptions", targetDepth)) {
createDhcpOptionsResult.setDhcpOptions(DhcpOptionsStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return createDhcpOptionsResult;
}
}
}
}
private static CreateDhcpOptionsResultStaxUnmarshaller instance;
public static CreateDhcpOptionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new CreateDhcpOptionsResultStaxUnmarshaller();
return instance;
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CreateDhcpOptionsResultStaxUnmarshaller.java
|
Java
|
apache-2.0
| 2,496
|
// Code generated by protoc-gen-go.
// source: go-micro/examples/server/proto/example/example.proto
// DO NOT EDIT!
/*
Package go_micro_srv_example is a generated protocol buffer package.
It is generated from these files:
go-micro/examples/server/proto/example/example.proto
It has these top-level messages:
Message
Request
Response
StreamingRequest
StreamingResponse
Ping
Pong
*/
package go_micro_srv_example
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import (
client "github.com/micro/go-micro/client"
server "github.com/micro/go-micro/server"
context "golang.org/x/net/context"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
type Message struct {
Say string `protobuf:"bytes,1,opt,name=say" json:"say,omitempty"`
}
func (m *Message) Reset() { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage() {}
func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
type Request struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}
func (m *Request) Reset() { *m = Request{} }
func (m *Request) String() string { return proto.CompactTextString(m) }
func (*Request) ProtoMessage() {}
func (*Request) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
type Response struct {
Msg string `protobuf:"bytes,1,opt,name=msg" json:"msg,omitempty"`
}
func (m *Response) Reset() { *m = Response{} }
func (m *Response) String() string { return proto.CompactTextString(m) }
func (*Response) ProtoMessage() {}
func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
type StreamingRequest struct {
Count int64 `protobuf:"varint,1,opt,name=count" json:"count,omitempty"`
}
func (m *StreamingRequest) Reset() { *m = StreamingRequest{} }
func (m *StreamingRequest) String() string { return proto.CompactTextString(m) }
func (*StreamingRequest) ProtoMessage() {}
func (*StreamingRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
type StreamingResponse struct {
Count int64 `protobuf:"varint,1,opt,name=count" json:"count,omitempty"`
}
func (m *StreamingResponse) Reset() { *m = StreamingResponse{} }
func (m *StreamingResponse) String() string { return proto.CompactTextString(m) }
func (*StreamingResponse) ProtoMessage() {}
func (*StreamingResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
type Ping struct {
Stroke int64 `protobuf:"varint,1,opt,name=stroke" json:"stroke,omitempty"`
}
func (m *Ping) Reset() { *m = Ping{} }
func (m *Ping) String() string { return proto.CompactTextString(m) }
func (*Ping) ProtoMessage() {}
func (*Ping) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
type Pong struct {
Stroke int64 `protobuf:"varint,1,opt,name=stroke" json:"stroke,omitempty"`
}
func (m *Pong) Reset() { *m = Pong{} }
func (m *Pong) String() string { return proto.CompactTextString(m) }
func (*Pong) ProtoMessage() {}
func (*Pong) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
func init() {
proto.RegisterType((*Message)(nil), "go.micro.srv.example.Message")
proto.RegisterType((*Request)(nil), "go.micro.srv.example.Request")
proto.RegisterType((*Response)(nil), "go.micro.srv.example.Response")
proto.RegisterType((*StreamingRequest)(nil), "go.micro.srv.example.StreamingRequest")
proto.RegisterType((*StreamingResponse)(nil), "go.micro.srv.example.StreamingResponse")
proto.RegisterType((*Ping)(nil), "go.micro.srv.example.Ping")
proto.RegisterType((*Pong)(nil), "go.micro.srv.example.Pong")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ client.Option
var _ server.Option
// Client API for Example service
type ExampleClient interface {
Call(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error)
Stream(ctx context.Context, in *StreamingRequest, opts ...client.CallOption) (Example_StreamClient, error)
PingPong(ctx context.Context, opts ...client.CallOption) (Example_PingPongClient, error)
}
type exampleClient struct {
c client.Client
serviceName string
}
func NewExampleClient(serviceName string, c client.Client) ExampleClient {
if c == nil {
c = client.NewClient()
}
if len(serviceName) == 0 {
serviceName = "go.micro.srv.example"
}
return &exampleClient{
c: c,
serviceName: serviceName,
}
}
func (c *exampleClient) Call(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error) {
req := c.c.NewRequest(c.serviceName, "Example.Call", in)
out := new(Response)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *exampleClient) Stream(ctx context.Context, in *StreamingRequest, opts ...client.CallOption) (Example_StreamClient, error) {
req := c.c.NewRequest(c.serviceName, "Example.Stream", &StreamingRequest{})
stream, err := c.c.Stream(ctx, req, opts...)
if err != nil {
return nil, err
}
if err := stream.Send(in); err != nil {
return nil, err
}
return &exampleStreamClient{stream}, nil
}
type Example_StreamClient interface {
RecvR() (*StreamingResponse, error)
client.Streamer
}
type exampleStreamClient struct {
client.Streamer
}
func (x *exampleStreamClient) RecvR() (*StreamingResponse, error) {
m := new(StreamingResponse)
err := x.Recv(m)
if err != nil {
return nil, err
}
return m, nil
}
func (c *exampleClient) PingPong(ctx context.Context, opts ...client.CallOption) (Example_PingPongClient, error) {
req := c.c.NewRequest(c.serviceName, "Example.PingPong", &Ping{})
stream, err := c.c.Stream(ctx, req, opts...)
if err != nil {
return nil, err
}
return &examplePingPongClient{stream}, nil
}
type Example_PingPongClient interface {
SendR(*Ping) error
RecvR() (*Pong, error)
client.Streamer
}
type examplePingPongClient struct {
client.Streamer
}
func (x *examplePingPongClient) SendR(m *Ping) error {
return x.Send(m)
}
func (x *examplePingPongClient) RecvR() (*Pong, error) {
m := new(Pong)
err := x.Recv(m)
if err != nil {
return nil, err
}
return m, nil
}
// Server API for Example service
type ExampleHandler interface {
Call(context.Context, *Request, *Response) error
Stream(context.Context, *StreamingRequest, Example_StreamStream) error
PingPong(context.Context, Example_PingPongStream) error
}
func RegisterExampleHandler(s server.Server, hdlr ExampleHandler) {
s.Handle(s.NewHandler(&Example{hdlr}))
}
type Example struct {
ExampleHandler
}
func (h *Example) Call(ctx context.Context, in *Request, out *Response) error {
return h.ExampleHandler.Call(ctx, in, out)
}
func (h *Example) Stream(ctx context.Context, stream server.Streamer) error {
m := new(StreamingRequest)
if err := stream.Recv(m); err != nil {
return err
}
return h.ExampleHandler.Stream(ctx, m, &exampleStreamStream{stream})
}
type Example_StreamStream interface {
SendR(*StreamingResponse) error
server.Streamer
}
type exampleStreamStream struct {
server.Streamer
}
func (x *exampleStreamStream) SendR(m *StreamingResponse) error {
return x.Streamer.Send(m)
}
func (h *Example) PingPong(ctx context.Context, stream server.Streamer) error {
return h.ExampleHandler.PingPong(ctx, &examplePingPongStream{stream})
}
type Example_PingPongStream interface {
SendR(*Pong) error
RecvR() (*Ping, error)
server.Streamer
}
type examplePingPongStream struct {
server.Streamer
}
func (x *examplePingPongStream) SendR(m *Pong) error {
return x.Streamer.Send(m)
}
func (x *examplePingPongStream) RecvR() (*Ping, error) {
m := new(Ping)
if err := x.Streamer.Recv(m); err != nil {
return nil, err
}
return m, nil
}
var fileDescriptor0 = []byte{
// 270 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x91, 0x5f, 0x4b, 0xc3, 0x30,
0x14, 0xc5, 0x17, 0x56, 0xdb, 0x79, 0xfd, 0x83, 0x06, 0x99, 0x52, 0x50, 0x34, 0x0f, 0xba, 0x17,
0xd3, 0xa1, 0x7e, 0x03, 0x11, 0x7d, 0x11, 0x64, 0x3e, 0xfb, 0x10, 0xc7, 0x25, 0x0c, 0x9b, 0xa6,
0xe6, 0x66, 0x43, 0x3f, 0xbb, 0x2f, 0x6e, 0x69, 0x3b, 0xc6, 0xec, 0xf0, 0x29, 0x70, 0x7e, 0xe7,
0x5c, 0xce, 0x21, 0x70, 0xa7, 0xed, 0xb5, 0x99, 0x8c, 0x9d, 0xcd, 0xf0, 0x4b, 0x99, 0x32, 0x47,
0xca, 0x08, 0xdd, 0x0c, 0x5d, 0x56, 0x3a, 0xeb, 0x97, 0x6a, 0xf3, 0xca, 0xa0, 0xf2, 0x23, 0x6d,
0x65, 0x48, 0x49, 0x72, 0x33, 0x59, 0x33, 0xd1, 0x87, 0xe4, 0x19, 0x89, 0x94, 0x46, 0xbe, 0x03,
0x5d, 0x52, 0xdf, 0x27, 0xec, 0x9c, 0x0d, 0xb6, 0xc5, 0x31, 0x24, 0x23, 0xfc, 0x9c, 0x22, 0x79,
0xbe, 0x0b, 0x51, 0xa1, 0x0c, 0x2e, 0x41, 0x6f, 0x84, 0x54, 0xda, 0x82, 0x42, 0xc2, 0x90, 0xae,
0xc1, 0x05, 0x1c, 0xbc, 0x7a, 0x87, 0xca, 0x4c, 0x0a, 0xdd, 0x44, 0xf7, 0x60, 0x6b, 0x6c, 0xa7,
0x85, 0x0f, 0x96, 0xae, 0x10, 0x70, 0xb8, 0x62, 0xa9, 0x8f, 0xac, 0x79, 0xfa, 0x10, 0xbd, 0xcc,
0x31, 0xdf, 0x87, 0x98, 0xbc, 0xb3, 0x1f, 0xb8, 0xa2, 0xdb, 0xbf, 0xfa, 0xcd, 0x0f, 0x83, 0xe4,
0xa1, 0x1a, 0xc3, 0x1f, 0x21, 0xba, 0x57, 0x79, 0xce, 0x4f, 0x65, 0xdb, 0x56, 0x59, 0xb7, 0x4a,
0xcf, 0x36, 0xe1, 0xaa, 0x91, 0xe8, 0xf0, 0x37, 0x88, 0xab, 0xa2, 0xfc, 0xb2, 0xdd, 0xbb, 0xbe,
0x34, 0xbd, 0xfa, 0xd7, 0xd7, 0x1c, 0x1f, 0x32, 0xfe, 0x04, 0xbd, 0xc5, 0xc6, 0xb0, 0x27, 0x6d,
0x0f, 0x2e, 0x78, 0xba, 0x89, 0xcd, 0x73, 0xa2, 0x33, 0x60, 0x43, 0xf6, 0x1e, 0x87, 0xbf, 0xbd,
0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x53, 0xb5, 0xeb, 0x31, 0x13, 0x02, 0x00, 0x00,
}
|
iheitlager/go-micro
|
examples/server/proto/example/example.pb.go
|
GO
|
apache-2.0
| 9,819
|
package ru.stqa.pft.addressbook.model;
import com.google.common.collect.ForwardingSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Groups extends ForwardingSet<GroupData> {
private Set<GroupData> delegate;
public Groups(Groups groups) {
this.delegate = new HashSet<GroupData>(groups.delegate);
}
public Groups() {
this.delegate = new HashSet<GroupData>();
}
public Groups(Collection<GroupData> groups) {
this.delegate = new HashSet<GroupData>(groups);
}
@Override
protected Set<GroupData> delegate() {
return delegate;
}
public Groups withAdded (GroupData group) {
Groups groups = new Groups(this);
groups.add(group);
return groups;
}
public Groups without (GroupData group) {
Groups groups = new Groups(this);
groups.remove(group);
return groups;
}
}
|
valshevtsova/java_pft
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Groups.java
|
Java
|
apache-2.0
| 969
|
/*
* 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.jmeter.testbeans.gui;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestFieldStringEditor {
private void testSetGet(ComboStringEditor e, Object value) throws Exception {
e.setValue(value);
assertEquals(value, e.getValue());
}
private void testSetGetAsText(ComboStringEditor e, String text) throws Exception {
e.setAsText(text);
assertEquals(text, e.getAsText());
}
@Test
public void testSetGet() throws Exception {
@SuppressWarnings("deprecation") // test code, intentional
ComboStringEditor e = new ComboStringEditor();
testSetGet(e, "any string");
testSetGet(e, "");
testSetGet(e, "${var}");
}
@Test
public void testSetGetAsText() throws Exception {
@SuppressWarnings("deprecation") // test code, intentional
ComboStringEditor e = new ComboStringEditor();
testSetGetAsText(e, "any string");
testSetGetAsText(e, "");
testSetGetAsText(e, "${var}");
}
}
|
yuyupapa/OpenSource
|
apache-jmeter-3.0/test/src/org/apache/jmeter/testbeans/gui/TestFieldStringEditor.java
|
Java
|
apache-2.0
| 2,018
|
package org.mesba.globalvariable;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
mdislam/Android-Showcase
|
Showcase/global_variable/src/androidTest/java/org/mesba/globalvariable/ApplicationTest.java
|
Java
|
apache-2.0
| 355
|
<?php
require 'functions.php';
date_default_timezone_set("PRC");
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'language' => 'zh-CN',
'sourceLanguage' => 'zh-CN',
'timeZone' => 'Asia/Chongqing',
'version' => '1.0',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'suffix' => '.html',
'rules' => [
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
],
];
|
codekissyoung/filmfest
|
yii2/common/config/main.php
|
PHP
|
apache-2.0
| 648
|
package site.hanschen.pretty.ui.picture;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import site.hanschen.pretty.R;
import site.hanschen.pretty.application.PrettyApplication;
import site.hanschen.pretty.base.BaseActivity;
import site.hanschen.pretty.db.bean.Picture;
import site.hanschen.pretty.db.repository.PrettyRepository;
import site.hanschen.pretty.eventbus.NewPictureEvent;
import site.hanschen.pretty.service.TaskManager;
/**
* @author HansChen
*/
public class PictureListActivity extends BaseActivity {
private static final String KEY_QUESTION_ID = "KEY_QUESTION_ID";
private static final String KEY_TITLE = "KEY_TITLE";
public static void open(Context context, int questionId, String title) {
Intent intent = new Intent(context, PictureListActivity.class);
intent.putExtra(KEY_QUESTION_ID, questionId);
intent.putExtra(KEY_TITLE, title);
context.startActivity(intent);
}
@BindView(R.id.picture_list_toolbar)
Toolbar mToolbar;
@BindView(R.id.picture_list_pictures)
RecyclerView mPictureView;
@BindView(R.id.picture_list_refresh)
FloatingActionButton mFabBtn;
@BindView(R.id.picture_list_progress)
ProgressBar mProgressBar;
private PictureAdapter mAdapter;
private List<Picture> mPictures;
private PrettyRepository mPrettyRepository;
private TaskManager mTaskManager;
private int mQuestionId;
private String mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture_list);
ButterKnife.bind(PictureListActivity.this);
EventBus.getDefault().register(this);
mPrettyRepository = PrettyApplication.getInstance().getPrettyRepository();
mTaskManager = PrettyApplication.getInstance().getTaskManager();
parseData();
initViews();
initData();
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
private void parseData() {
Bundle bundle = getIntent().getExtras();
if (bundle == null
|| (mQuestionId = bundle.getInt(KEY_QUESTION_ID)) == 0
|| (mTitle = bundle.getString(KEY_TITLE)) == null) {
throw new IllegalArgumentException("bundle must contain QuestionId");
}
}
private int getPhotoSize(int column) {
int margin = getResources().getDimensionPixelOffset(R.dimen.grid_margin);
return getResources().getDisplayMetrics().widthPixels / column - 2 * margin;
}
private void initViews() {
mToolbar.setTitle(mTitle);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_close_black_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mPictureView.setLayoutManager(new GridLayoutManager(this, 3));
mPictureView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int margin = getResources().getDimensionPixelOffset(R.dimen.grid_margin);
outRect.set(margin, margin, margin, margin);
}
});
mAdapter = new PictureAdapter(this, getPhotoSize(3));
mAdapter.setItemClickListener(mOnItemClickListener);
mPictureView.setAdapter(mAdapter);
if (mTaskManager.isFetching(mQuestionId)) {
displayFetchingState();
} else {
displayNoFetchingState();
}
}
private PictureAdapter.OnItemClickListener mOnItemClickListener = new PictureAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position, Picture picture) {
GalleryActivity.open(PictureListActivity.this, mQuestionId, position);
}
};
private void initData() {
Observable.create(new ObservableOnSubscribe<List<Picture>>() {
@Override
public void subscribe(ObservableEmitter<List<Picture>> e) throws Exception {
e.onNext(mPrettyRepository.getPictures(mQuestionId));
e.onComplete();
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<Picture>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(List<Picture> pictures) {
mPictures = pictures;
mAdapter.setData(mPictures);
if (mPictures.size() <= 0) {
showFetchDialog();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
private void showFetchDialog() {
new MaterialDialog.Builder(this).title("抓取图片")
.content("抓取该话题下所有图片?请尽量使用Wi-Fi,土豪随意")
.positiveText("抓取")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
mTaskManager.startFetchPicture(mQuestionId);
displayFetchingState();
}
})
.negativeText("取消")
.build()
.show();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(NewPictureEvent event) {
if (event.questionId != mQuestionId || event.pictures.size() <= 0) {
return;
}
mAdapter.notifyDataSetChanged();
}
@OnClick(R.id.picture_list_refresh)
void onFabClick() {
if (mTaskManager.isFetching(mQuestionId)) {
mTaskManager.stopFetchPicture(mQuestionId);
displayNoFetchingState();
Toast.makeText(getApplicationContext(), "已停止抓取图片", Toast.LENGTH_SHORT).show();
} else {
showFetchDialog();
}
}
private void displayFetchingState() {
mProgressBar.setVisibility(View.VISIBLE);
mFabBtn.setImageResource(R.drawable.ic_close_black_24dp);
}
private void displayNoFetchingState() {
mProgressBar.setVisibility(View.GONE);
mFabBtn.setImageResource(R.drawable.ic_refresh_black_24dp);
}
}
|
shensky711/Pretty-Zhihu
|
app/src/main/java/site/hanschen/pretty/ui/picture/PictureListActivity.java
|
Java
|
apache-2.0
| 8,110
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2019.02.03 um 11:14:53 PM CET
//
package net.opengis.gml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* A 1D coordinate reference system used for recording heights or depths. Vertical CRSs make use of the direction of gravity to define the concept of height or depth, but the relationship with gravity may not be straightforward. By implication, ellipsoidal heights (h) cannot be captured in a vertical coordinate reference system. Ellipsoidal heights cannot exist independently, but only as an inseparable part of a 3D coordinate tuple defined in a geographic 3D coordinate reference system.
*
* <p>Java-Klasse für VerticalCRSType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="VerticalCRSType">
* <complexContent>
* <extension base="{http://www.opengis.net/gml}AbstractReferenceSystemType">
* <sequence>
* <element ref="{http://www.opengis.net/gml}usesVerticalCS"/>
* <element ref="{http://www.opengis.net/gml}usesVerticalDatum"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VerticalCRSType", propOrder = {
"usesVerticalCS",
"usesVerticalDatum"
})
public class VerticalCRSType
extends AbstractReferenceSystemType
{
@XmlElement(required = true)
protected VerticalCSRefType usesVerticalCS;
@XmlElement(required = true)
protected VerticalDatumRefType usesVerticalDatum;
/**
* Ruft den Wert der usesVerticalCS-Eigenschaft ab.
*
* @return
* possible object is
* {@link VerticalCSRefType }
*
*/
public VerticalCSRefType getUsesVerticalCS() {
return usesVerticalCS;
}
/**
* Legt den Wert der usesVerticalCS-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link VerticalCSRefType }
*
*/
public void setUsesVerticalCS(VerticalCSRefType value) {
this.usesVerticalCS = value;
}
public boolean isSetUsesVerticalCS() {
return (this.usesVerticalCS!= null);
}
/**
* Ruft den Wert der usesVerticalDatum-Eigenschaft ab.
*
* @return
* possible object is
* {@link VerticalDatumRefType }
*
*/
public VerticalDatumRefType getUsesVerticalDatum() {
return usesVerticalDatum;
}
/**
* Legt den Wert der usesVerticalDatum-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link VerticalDatumRefType }
*
*/
public void setUsesVerticalDatum(VerticalDatumRefType value) {
this.usesVerticalDatum = value;
}
public boolean isSetUsesVerticalDatum() {
return (this.usesVerticalDatum!= null);
}
}
|
citygml4j/citygml4j
|
src-gen/main/java/net/opengis/gml/VerticalCRSType.java
|
Java
|
apache-2.0
| 3,415
|
# Malus toringo f. toringo FORM
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Malus/Malus toringo/Malus toringo toringo/README.md
|
Markdown
|
apache-2.0
| 163
|
from steps.bdd_test_util import cli_call
def after_scenario(context, scenario):
if 'doNotDecompose' in scenario.tags:
print("Not going to decompose after scenario {0}, with yaml '{1}'".format(scenario.name, context.compose_yaml))
else:
if 'compose_yaml' in context:
print("Decomposing with yaml '{0}' after scenario {1}, ".format(context.compose_yaml, scenario.name))
context.compose_output, context.compose_error, context.compose_returncode = \
cli_call(context, ["docker-compose", "-f", context.compose_yaml, "kill"], expect_success=True)
context.compose_output, context.compose_error, context.compose_returncode = \
cli_call(context, ["docker-compose", "-f", context.compose_yaml, "rm","-f"], expect_success=True)
# now remove any other containers (chaincodes)
context.compose_output, context.compose_error, context.compose_returncode = \
cli_call(context, ["docker", "ps", "-qa"], expect_success=True)
if context.compose_returncode == 0:
# Remove each container
for containerId in context.compose_output.splitlines():
#print("docker rm {0}".format(containerId))
context.compose_output, context.compose_error, context.compose_returncode = \
cli_call(context, ["docker", "rm", containerId], expect_success=True)
|
ghaskins/obc-peer
|
openchain/peer/bddtests/environment.py
|
Python
|
apache-2.0
| 1,357
|
# Omphalospora beijerinckii Oudem. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Omphalospora beijerinckii Oudem.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Dothideales/Dothideaceae/Omphalospora/Omphalospora beijerinckii/README.md
|
Markdown
|
apache-2.0
| 193
|
package sagex.miniclient.desktop;
import com.google.common.eventbus.DeadEvent;
import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sagex.miniclient.IBus;
public class DesktopBus implements IBus {
Logger log = LoggerFactory.getLogger(DesktopBus.class);
EventBus bus = new EventBus();
public DesktopBus() {
bus.register(this);
}
@Override
public void register(Object object) {
bus.register(object);
}
@Override
public void unregister(Object object) {
bus.unregister(object);
}
@Override
public void post(Object event) {
bus.post(event);
}
public void handleDeadEvent(DeadEvent event) {
log.warn("Unhandled Event: ", event);
}
}
|
OpenSageTV/sagetv-miniclient
|
desktop/app/src/main/java/sagex/miniclient/desktop/DesktopBus.java
|
Java
|
apache-2.0
| 789
|
scheduletrace
=============
Scheduletrace is a utility to graphically display the scheduling of a set of ad-hoc periodic tasks running on a Linux system.
Its purpose is mainly didactic. Should you happen to find it useful in any other context, I'd be glad to be informed.
Written by Davide Kirchner for the _Real-Time systems_ course held by
professor Giorgio Buttazzo at TeCIP / Scuola Superiore Sant'Anna
di Studi Universitari e Perfezionamento (Pisa, Italy).
Project requirements:
Visualize the schedule of a task set (with D ≤ T). Each task displays its execution.
Time scale must be variable by the user. The execution of the main function has to be also
visualized as idle time. Also visualize periodic activation times and absolute deadlines as longer
vertical bars with different colors. Visualize critical sections protected by different semaphores
using different colors. Build a task set in such a way a priority inversion occurs. Then run the
same example using Priority Inheritance and Priority Ceiling to show that priority inversion
disappears. Also visualize the instantaneous workload as a function of time.
Other than in this file, a description of the software is available in LaTeX _and_ pre-compiled in PDF in the `docs` folder.
Compiling
---------
This is written in C99 and heavily relies on linux-only libraries. Thus, if
you're missing linux or a C99 compiler, install them or give up.
If you have SCons installed, simply cd to the project root and run
scons
If, instead, you don't have SCons, there is a Makefile available that will
fetch a user-space installation and run it. Simply invoke it with:
make
Running
-------
For a sample task set and default configuration, run it with
./scheduletrace -f ./taskset1
For a complete list of command-line arguments see
./scheduletrace --help
Taskset format
--------------
A taskset file is a simple file describing 1 task per line. Empty lines and lines starting with `#` are ignored.
A task is (not strictly formally) described as follows:
TASK ::= T=<PERIOD>,D=<DEADLINE>,pr=<PRIORITY>,ph=<PHASE>[<SECTION>*]
SECTION ::= (R<RESOURCE>,<OP_COUNT>)
- `PERIOD`: Task period in _ms_
- `DEADLINE`: Relative deadline in _ms_
- `PRIORITY`: Scheduling priority. Use the range [3,99], because 1 and 2 are used internally
- `PHASE`: A positive offset for the first activation of the task.
- `RESOURCE`: Integer id of a resource. `R0` means no resource at all. From `R1` on, they are actual resources.
- `OP_COUNT`: Average number of operations in this section (while owning the corresponding resource)
Example:
T=1000,D=500,pr=5,ph=100,[(R1,800000)(R0,200000)]
TODOs
-----
* Properly detect and show deadline misses
* Increased plot precision (currently 1ms, for some reasons I don't remember)
* Differently display "acquire/release" events?
* Priority-based task lock? Could avoid IDLE to wake up when it is not idle time at all...
* Load a saved trace
In case you're actually interested in one or more of these (or other) TODOs to become real, you are welcome to contact me. Unless there is some interest, this will most likely be abandoned shortly after taking my exam.
Authors
-------
Davide Kirchner davide dot kirchner at yahoo dot it
Licence
-------
The core of this program is distrubuted under the Apache Licence, version 2.
A copy of the licence is shipped whith this code.
The `src/bsearch_left.c` file is distributed under the terms of the GNU General Public License, as published by the Free Software Foundation; version 2.
The `Makefile`, which wraps the SCons scripts, is released under the terms of the MIT licence (see into the file itself)
|
davidek/scheduletrace
|
README.md
|
Markdown
|
apache-2.0
| 3,710
|
/**
* 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.oozie.server;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.service.ConfigurationService;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
/**
* Factory that is used to configure SSL settings for the Oozie server.
*/
class SSLServerConnectorFactory {
private static final Logger LOG = LoggerFactory.getLogger(SSLServerConnectorFactory.class);
public static final String OOZIE_HTTPS_KEYSTORE_PASS = "oozie.https.keystore.pass";
public static final String OOZIE_HTTPS_KEYSTORE_FILE = "oozie.https.keystore.file";
public static final String OOZIE_HTTPS_EXCLUDE_PROTOCOLS = "oozie.https.exclude.protocols";
public static final String OOZIE_HTTPS_INCLUDE_PROTOCOLS = "oozie.https.include.protocols";
public static final String OOZIE_HTTPS_INCLUDE_CIPHER_SUITES = "oozie.https.include.cipher.suites";
public static final String OOZIE_HTTPS_EXCLUDE_CIPHER_SUITES = "oozie.https.exclude.cipher.suites";
private SslContextFactory sslContextFactory;
private Configuration conf;
@Inject
public SSLServerConnectorFactory(final SslContextFactory sslContextFactory) {
this.sslContextFactory = Preconditions.checkNotNull(sslContextFactory, "sslContextFactory is null");
}
/**
* Construct a ServerConnector object with SSL settings
*
* @param oozieHttpsPort Oozie HTTPS port
* @param conf Oozie configuration
* @param server jetty Server which the connector is attached to
*
* @return ServerConnector
*/
public ServerConnector createSecureServerConnector(int oozieHttpsPort, Configuration conf, Server server) {
this.conf = Preconditions.checkNotNull(conf, "conf is null");
Preconditions.checkNotNull(server, "server is null");
Preconditions.checkState(oozieHttpsPort >= 1 && oozieHttpsPort <= 65535,
String.format("Invalid port number specified: \'%d\'. It should be between 1 and 65535.", oozieHttpsPort));
setIncludeProtocols();
setExcludeProtocols();
setIncludeCipherSuites();
setExludeCipherSuites();
setKeyStoreFile();
setKeystorePass();
HttpConfiguration httpsConfiguration = getHttpsConfiguration();
ServerConnector secureServerConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfiguration));
secureServerConnector.setPort(oozieHttpsPort);
LOG.info(String.format("Secure server connector created, listening on port %d", oozieHttpsPort));
return secureServerConnector;
}
private void setExludeCipherSuites() {
String excludeCipherList = conf.get(OOZIE_HTTPS_EXCLUDE_CIPHER_SUITES);
String[] excludeCipherSuites = excludeCipherList.split(",");
sslContextFactory.setExcludeCipherSuites(excludeCipherSuites);
LOG.info(String.format("SSL context - excluding cipher suites: %s", Arrays.toString(excludeCipherSuites)));
}
private void setIncludeCipherSuites() {
String includeCipherList = conf.get(OOZIE_HTTPS_INCLUDE_CIPHER_SUITES);
if (includeCipherList == null || includeCipherList.isEmpty()) {
return;
}
String[] includeCipherSuites = includeCipherList.split(",");
sslContextFactory.setIncludeCipherSuites(includeCipherSuites);
LOG.info(String.format("SSL context - including cipher suites: %s", Arrays.toString(includeCipherSuites)));
}
private void setIncludeProtocols() {
String enabledProtocolsList = conf.get(OOZIE_HTTPS_INCLUDE_PROTOCOLS);
String[] enabledProtocols = enabledProtocolsList.split(",");
sslContextFactory.setIncludeProtocols(enabledProtocols);
LOG.info(String.format("SSL context - including protocols: %s", Arrays.toString(enabledProtocols)));
}
private void setExcludeProtocols() {
String excludedProtocolsList = conf.get(OOZIE_HTTPS_EXCLUDE_PROTOCOLS);
if (excludedProtocolsList == null || excludedProtocolsList.isEmpty()) {
return;
}
String[] excludedProtocols = excludedProtocolsList.split(",");
sslContextFactory.setExcludeProtocols(excludedProtocols);
LOG.info(String.format("SSL context - excluding protocols: %s", Arrays.toString(excludedProtocols)));
}
private void setKeystorePass() {
String keystorePass = ConfigurationService.getPassword(conf, OOZIE_HTTPS_KEYSTORE_PASS);
Preconditions.checkNotNull(keystorePass, "keystorePass is null");
sslContextFactory.setKeyManagerPassword(keystorePass);
}
private void setKeyStoreFile() {
String keystoreFile = conf.get(OOZIE_HTTPS_KEYSTORE_FILE);
Preconditions.checkNotNull(keystoreFile, "keystoreFile is null");
sslContextFactory.setKeyStorePath(keystoreFile);
}
private HttpConfiguration getHttpsConfiguration() {
HttpConfiguration https = new HttpConfigurationWrapper(conf).getDefaultHttpConfiguration();
https.setSecureScheme("https");
https.addCustomizer(new SecureRequestCustomizer());
return https;
}
}
|
cbaenziger/oozie
|
server/src/main/java/org/apache/oozie/server/SSLServerConnectorFactory.java
|
Java
|
apache-2.0
| 6,556
|
package org.elasticsoftware.elasticactors.broadcast;
import org.elasticsoftware.elasticactors.Actor;
import org.elasticsoftware.elasticactors.ActorRef;
import org.elasticsoftware.elasticactors.TypedActor;
import org.elasticsoftware.elasticactors.base.serialization.JacksonSerializationFramework;
import org.elasticsoftware.elasticactors.broadcast.messages.HelloThrottled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Joost van de Wijgerd
*/
@Actor(serializationFramework = JacksonSerializationFramework.class)
public class SessionThrottledActor extends TypedActor<HelloThrottled> {
private final static Logger staticLogger = LoggerFactory.getLogger(SessionThrottledActor.class);
@Override
public void onReceive(ActorRef sender, HelloThrottled message) throws Exception {
sender.tell(new HelloThrottled("I'm fine thank you"), getSelf());
}
@Override
protected Logger initLogger() {
return staticLogger;
}
}
|
elasticsoftwarefoundation/elasticactors-systems
|
broadcast/src/test/java/org/elasticsoftware/elasticactors/broadcast/SessionThrottledActor.java
|
Java
|
apache-2.0
| 983
|
---
title: Working with Recurring Appointments
page_title: Working with Recurring Appointments - WinForms Scheduler Control
description: WinForms Scheduler supports recurring events on minutely, hourly, weekly, daily, monthly and yearly basis. Learn how to define them.
slug: winforms/scheduler/appointments-and-dialogs/working-with-recurring-appointments
tags: working,with,recurring,appointments
published: True
position: 1
previous_url: scheduler-appointments-and-dialogs-working-with-recurring-appointments
---
# Working with Recurring Appointments
__RadScheduler__ includes support for recurring events on minutely, hourly, weekly, daily, monthly and yearly basis. __Exceptions__ to the recurrence rules are also permitted. To support this recurrence behavior, the __IEvent__ interface (which the __Appointment__ class implements) includes the __RecurrenceRule__, __MasterEvent__, __Occurrences__ and __Exceptions__ properties. When an appointment is assigned a recurrence rule it becomes a recurring appointment.
If the user modifies an individual appointment occurrence, this creates an __exception__, sets its __MasterEvent__ property to the original recurring appointment and puts it in its __Exceptions__ collection so that no occurrence is generated for the exception occurrence. This way the exception is still linked to the original recurrence series.
The __RecurrenceRule__ class is the engine for creating and evaluating recurrence rules. It serves as a base class to several specialized classes and cannot be instantiated directly. The specialized classes are:
* MinutelyRecurrenceRule
* HourlyRecurrenceRule
* DailyRecurrenceRule
* WeeklyRecurrenceRule
* MonthlyRecurrenceRule
* YearlyRecurrenceRule
Using the specialized classes makes it easier to define recurrence rules because only relevant parameters are specified in their constructors.
## Recurring Appointments
One of several constructor overloads lets you set the start time, duration and number of occurences. Then the rule can be assigned to the appointments __RecurrenceRule__ property. The snippet below defines a rule that starts "now" and recurs every two hours and stops after the tenth occurence.
#### RecurrenceRule Property
{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=addingRecRule}}
{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=addingRecRule}}
````C#
radScheduler1.Appointments[0].RecurrenceRule = new HourlyRecurrenceRule(DateTime.Now, 2, 10);
````
````VB.NET
RadScheduler1.Appointments(0).RecurrenceRule = New HourlyRecurrenceRule(Date.Now, 2, 10)
````
{{endregion}}
The Appointment __Occurrences__ property lets you iterate a list of __IEvent__ instances. To get only some occurrences between specific starting and stopping times, use the Appointment __GetOccurrences()__ method.
#### Retrieving Occurrences
{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=iterating}}
{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=iterating}}
````C#
// iterate all appointment occurrances
foreach (IEvent ev in recurringAppointment.Occurrences)
{
//...
}
// iterate only occurrances after 10am
IEnumerable<IEvent> occurrencesAfter10AM = recurringAppointment.GetOccurrences(
new DateTime(2008, 10, 1, 10, 0, 0), DateTime.Now);
foreach (IEvent ev in occurrencesAfter10AM)
{
//...
}
````
````VB.NET
' iterate all appointment occurrances
For Each ev As IEvent In recurringAppointment.Occurrences
'...
Next ev
' iterate only occurrances after 10am
Dim occurrencesAfter10AM As IEnumerable(Of IEvent) = recurringAppointment.GetOccurrences(New Date(2008, 10, 1, 10, 0, 0), Date.Now)
For Each ev As IEvent In occurrencesAfter10AM
'...
Next ev
````
{{endregion}}
When the user changes a specific occurrence and not the entire series, an "Exception" is created. "Exceptions" in this context refer to "Exceptions to a rule", not the .NET Exception class related to error handling. You can create exceptions programmatically by adding to the IEvent __MasterEvent.Exceptions__ collection. The snippet below changes the background and status of an IEvent instance and adds the IEvent to its own MasterEvent Exceptions collection.
#### Recurrence Rule Exception
{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=addingExceptions}}
{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=addingExceptions}}
````C#
myEvent.BackgroundId = (int)AppointmentBackground.Important;
myEvent.StatusId = (int)AppointmentStatus.Tentative;
myEvent.MasterEvent.Exceptions.Add(myEvent);
````
````VB.NET
myEvent.BackgroundId = CInt(Fix(AppointmentBackground.Important))
myEvent.StatusId = CInt(Fix(AppointmentStatus.Tentative))
myEvent.MasterEvent.Exceptions.Add(myEvent)
````
{{endregion}}
## Examples
Here is an example using the __HourlyRecurrenceRule__ class:
#### Setting HourlyReccurrenceRule
{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=console}}
{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=console}}
````C#
// Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour.
Appointment recurringAppointment = new Appointment(new DateTime(2008, 10, 1, 3, 30, 0),
TimeSpan.FromHours(1.0), "Appointment Subject");
// Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences.
HourlyRecurrenceRule rrule = new HourlyRecurrenceRule(recurringAppointment.Start, 2, 10);
//Assign the hourly recurrence rule to the appointment
recurringAppointment.RecurrenceRule = rrule;
Console.WriteLine("The appointment recurrs at the following times");
foreach (IEvent ev in recurringAppointment.Occurrences)
{
Console.WriteLine("\t{0}", ev);
}
IEnumerable<IEvent> occurrencesAfter10AM = recurringAppointment.GetOccurrences(
new DateTime(2008, 10, 1, 10, 0, 0), DateTime.Now);
Console.WriteLine("And here are the occurrences after 10 AM:");
foreach (IEvent ev in occurrencesAfter10AM)
{
Console.WriteLine("\t{0}", ev);
}
````
````VB.NET
' Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour.
Dim recurringAppointment As New Appointment(New Date(2008, 10, 1, 3, 30, 0), TimeSpan.FromHours(1.0), "Appointment Subject")
' Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences.
Dim rrule As New HourlyRecurrenceRule(recurringAppointment.Start, 2, 10)
'Assign the hourly recurrence rule to the appointment
recurringAppointment.RecurrenceRule = rrule
Console.WriteLine("The appointment recurrs at the following times")
For Each ev As IEvent In recurringAppointment.Occurrences
Console.WriteLine(vbTab & "{0}", ev)
Next ev
Dim occurrencesAfter10AM As IEnumerable(Of IEvent) = recurringAppointment.GetOccurrences(New Date(2008, 10, 1, 10, 0, 0), Date.Now)
Console.WriteLine("And here are the occurrences after 10 AM:")
For Each ev As IEvent In occurrencesAfter10AM
Console.WriteLine(vbTab & "{0}", ev)
Next ev
````
{{endregion}}
The __Occurrences__ property of the __Appointment__ class returns an enumerator that can be used to retrieve all the occurrences defined by the rule. Similarly the __GetOccurrences__ method of the __Appointment__ class can be used to retrieve all occurrences in a given interval. The example above produces the following output:
>caption Figure 1: Appointment Occurrences

# See Also
* [Reccurrence Rule Walkthrough]({%slug winforms/scheduler/appointments-and-dialogs/recurrence-rule-walkthrough%})
* [Views]({%slug winforms/scheduler/views/overview-and-structure%})
* [Data Binding Introduction]({%slug winforms/scheduler/data-binding/introduction%})
* [Formatting Appointments]({%slug winforms/scheduler/appearance/formatting-appointments%})
* [Scheduler Element Provider]({%slug winforms/scheduler/fundamentals/scheduler-element-provider-%})
|
telerik/winforms-docs
|
controls/scheduler/appointments-and-dialogs/working-with-recurring-appointments.md
|
Markdown
|
apache-2.0
| 8,277
|
package pl.warsjawa.android2.model.gmapsapi.directions;
import pl.warsjawa.android2.model.gmapsapi.Coords;
public class Step {
private ValueWithDescription distance;
private ValueWithDescription duration;
private Coords endLocation;
private EncodedPolyline polyline;
private Coords startLocation;
private String travelMode;
public EncodedPolyline getPolyline() {
return polyline;
}
}
|
mg6maciej/warsjawa2013-android-squared-googled-preparation
|
Android2/Android2/src/main/java/pl/warsjawa/android2/model/gmapsapi/directions/Step.java
|
Java
|
apache-2.0
| 428
|
package com.jetbrains.edu.learning.actions;
import com.intellij.icons.AllIcons;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.tabs.TabInfo;
import com.intellij.ui.tabs.TabsListener;
import com.intellij.ui.tabs.impl.JBEditorTabs;
import com.intellij.util.PlatformIcons;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.learning.core.EduNames;
import com.jetbrains.edu.learning.core.EduUtils;
import com.jetbrains.edu.learning.courseFormat.Task;
import com.jetbrains.edu.learning.courseFormat.TaskFile;
import com.jetbrains.edu.learning.courseFormat.UserTest;
import com.jetbrains.edu.learning.editor.StudyEditor;
import com.jetbrains.edu.learning.ui.StudyTestContentPanel;
import icons.InteractiveLearningIcons;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudyEditInputAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance(StudyEditInputAction.class.getName());
private JBEditorTabs tabbedPane;
private Map<TabInfo, UserTest> myEditableTabs = new HashMap<>();
public StudyEditInputAction() {
super("Watch Test Input", "Watch test input", InteractiveLearningIcons.WatchInput);
}
public void showInput(final Project project) {
final Editor selectedEditor = StudyUtils.getSelectedEditor(project);
if (selectedEditor != null) {
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
final VirtualFile openedFile = fileDocumentManager.getFile(selectedEditor.getDocument());
final StudyTaskManager studyTaskManager = StudyTaskManager.getInstance(project);
assert openedFile != null;
TaskFile taskFile = StudyUtils.getTaskFile(project, openedFile);
assert taskFile != null;
final Task currentTask = taskFile.getTask();
tabbedPane = new JBEditorTabs(project, ActionManager.getInstance(), IdeFocusManager.findInstance(), project);
tabbedPane.addListener(new TabsListener.Adapter() {
@Override
public void selectionChanged(TabInfo oldSelection, TabInfo newSelection) {
if (newSelection.getIcon() != null) {
int tabCount = tabbedPane.getTabCount();
VirtualFile taskDir = StudyUtils.getTaskDir(openedFile);
VirtualFile testsDir = taskDir.findChild(EduNames.USER_TESTS);
assert testsDir != null;
UserTest userTest = createUserTest(testsDir, currentTask, studyTaskManager);
userTest.setEditable(true);
StudyTestContentPanel testContentPanel = new StudyTestContentPanel(userTest);
TabInfo testTab = addTestTab(tabbedPane.getTabCount(), testContentPanel, currentTask, true);
myEditableTabs.put(testTab, userTest);
tabbedPane.addTabSilently(testTab, tabCount - 1);
tabbedPane.select(testTab, true);
}
}
});
List<UserTest> userTests = studyTaskManager.getUserTests(currentTask);
int i = 1;
for (UserTest userTest : userTests) {
String inputFileText = StudyUtils.getFileText(null, userTest.getInput(), false, "UTF-8");
String outputFileText = StudyUtils.getFileText(null, userTest.getOutput(), false, "UTF-8");
StudyTestContentPanel myContentPanel = new StudyTestContentPanel(userTest);
myContentPanel.addInputContent(inputFileText);
myContentPanel.addOutputContent(outputFileText);
TabInfo testTab = addTestTab(i, myContentPanel, currentTask, userTest.isEditable());
tabbedPane.addTabSilently(testTab, i - 1);
if (userTest.isEditable()) {
myEditableTabs.put(testTab, userTest);
}
i++;
}
TabInfo plusTab = new TabInfo(new JPanel());
plusTab.setIcon(PlatformIcons.ADD_ICON);
tabbedPane.addTabSilently(plusTab, tabbedPane.getTabCount());
final JBPopup hint =
JBPopupFactory.getInstance().createComponentPopupBuilder(tabbedPane.getComponent(), tabbedPane.getComponent())
.setResizable(true)
.setMovable(true)
.setRequestFocus(true)
.createPopup();
StudyEditor selectedStudyEditor = StudyUtils.getSelectedStudyEditor(project);
assert selectedStudyEditor != null;
hint.showInCenterOf(selectedStudyEditor.getComponent());
hint.addListener(new HintClosedListener(currentTask, studyTaskManager));
}
}
private static void flushBuffer(@NotNull final StringBuilder buffer, @NotNull final File file) {
PrintWriter printWriter = null;
try {
//noinspection IOResourceOpenedButNotSafelyClosed
printWriter = new PrintWriter(new FileOutputStream(file));
printWriter.print(buffer.toString());
}
catch (FileNotFoundException e) {
LOG.error(e);
}
finally {
StudyUtils.closeSilently(printWriter);
}
EduUtils.synchronize();
}
private static UserTest createUserTest(@NotNull final VirtualFile testsDir,
@NotNull final Task currentTask,
StudyTaskManager studyTaskManager) {
UserTest userTest = new UserTest();
List<UserTest> userTests = studyTaskManager.getUserTests(currentTask);
int testNum = userTests.size() + 1;
String inputName = EduNames.USER_TEST_INPUT + testNum;
File inputFile = new File(testsDir.getPath(), inputName);
String outputName = EduNames.USER_TEST_OUTPUT + testNum;
File outputFile = new File(testsDir.getPath(), outputName);
userTest.setInput(inputFile.getPath());
userTest.setOutput(outputFile.getPath());
studyTaskManager.addUserTest(currentTask, userTest);
return userTest;
}
private TabInfo addTestTab(int nameIndex, final StudyTestContentPanel contentPanel, @NotNull final Task currentTask, boolean toBeClosable) {
TabInfo testTab = toBeClosable ? createClosableTab(contentPanel, currentTask) : new TabInfo(contentPanel);
return testTab.setText(EduNames.TEST_TAB_NAME + String.valueOf(nameIndex));
}
private TabInfo createClosableTab(StudyTestContentPanel contentPanel, Task currentTask) {
TabInfo closableTab = new TabInfo(contentPanel);
final DefaultActionGroup tabActions = new DefaultActionGroup();
tabActions.add(new CloseTab(closableTab, currentTask));
closableTab.setTabLabelActions(tabActions, ActionPlaces.EDITOR_TAB);
return closableTab;
}
public void actionPerformed(AnActionEvent e) {
showInput(e.getProject());
}
private static class HintClosedListener extends JBPopupAdapter {
private final Task myTask;
private final StudyTaskManager myStudyTaskManager;
private HintClosedListener(@NotNull final Task task, StudyTaskManager studyTaskManager) {
myTask = task;
myStudyTaskManager = studyTaskManager;
}
@Override
public void onClosed(LightweightWindowEvent event) {
for (final UserTest userTest : myStudyTaskManager.getUserTests(myTask)) {
ApplicationManager.getApplication().runWriteAction(() -> {
if (userTest.isEditable()) {
File inputFile = new File(userTest.getInput());
File outputFile = new File(userTest.getOutput());
flushBuffer(userTest.getInputBuffer(), inputFile);
flushBuffer(userTest.getOutputBuffer(), outputFile);
}
});
}
}
}
private class CloseTab extends AnAction implements DumbAware {
private final TabInfo myTabInfo;
private final Task myTask;
public CloseTab(final TabInfo info, @NotNull final Task task) {
myTabInfo = info;
myTask = task;
}
@Override
public void update(final AnActionEvent e) {
e.getPresentation().setIcon(AllIcons.Actions.Close);
e.getPresentation().setHoveredIcon(AllIcons.Actions.CloseHovered);
e.getPresentation().setVisible(UISettings.getInstance().SHOW_CLOSE_BUTTON);
e.getPresentation().setText("Delete test");
}
@Override
public void actionPerformed(final AnActionEvent e) {
tabbedPane.removeTab(myTabInfo);
UserTest userTest = myEditableTabs.get(myTabInfo);
File testInputFile = new File(userTest.getInput());
File testOutputFile = new File(userTest.getOutput());
if (testInputFile.delete() && testOutputFile.delete()) {
EduUtils.synchronize();
} else {
LOG.error("failed to delete user tests");
}
final Project project = e.getProject();
if (project != null) {
StudyTaskManager.getInstance(project).removeUserTest(myTask, userTest);
}
}
}
@Override
public void update(final AnActionEvent e) {
EduUtils.enableAction(e, false);
final Project project = e.getProject();
if (project != null) {
StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project);
if (studyEditor != null) {
final List<UserTest> userTests = StudyTaskManager.getInstance(project).getUserTests(studyEditor.getTaskFile().getTask());
if (!userTests.isEmpty()) {
EduUtils.enableAction(e, true);
}
}
}
}
}
|
youdonghai/intellij-community
|
python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyEditInputAction.java
|
Java
|
apache-2.0
| 10,012
|
package info.mornlight.gw2s.android.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.InjectView;
import info.mornlight.gw2s.android.R;
import info.mornlight.gw2s.android.billing.InAppProducts;
import info.mornlight.gw2s.android.billing.PurchasingHelper;
import info.mornlight.gw2s.android.util.DefaultAsyncTask;
import info.mornlight.gw2s.android.util.ToastUtils;
import java.util.Set;
public class MainActivity extends BaseActivity
{
private static final String TAG = "MainActivity";
@InjectView(R.id.wvw)
protected View wvw;
@InjectView(R.id.items)
protected View items;
@InjectView(R.id.recipes)
protected View recipes;
@InjectView(R.id.map)
protected View map;
private PurchasingHelper purchasingHelper = new PurchasingHelper();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.inject(this);
App.instance().loadSkuStates();
wvw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, WvwActivity.class));
}
});
items.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ItemsActivity.class));
}
});
recipes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RecipesActivity.class));
}
});
map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MapActivity.class));
}
});
purchasingHelper.init(this, new PurchasingHelper.ServiceListener() {
@Override
public void onServiceConnected() {
refreshSkuStates();
}
@Override
public void onServiceDisconnected() {
}
});
AppRater rater = new AppRater(getResources().getText(R.string.app_name).toString(), getPackageName());
rater.appLaunched(this);
}
private void refreshSkuStates() {
DefaultAsyncTask task = new DefaultAsyncTask<Void, Set<String>>(this, R.string.refresh_purchasing_error) {
@Override
public Set<String> call() throws Exception {
return purchasingHelper.queryOwnedItems();
}
@Override
protected void onSuccess(Set<String> skus) {
App app = App.instance();
app.updatePurchasedSkus(skus);
}
};
task.execute();
}
/*private void checkCrawler() {
ConnectionManager conMgr = new ConnectionManager(this);
if(!conMgr.hasInternet()) {
return;
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean onlyWithWifi = prefs.getBoolean(Prefs.UPDATE_DATABASE_ONLY_WITH_WIFI, true);
if(!conMgr.isWifi() && onlyWithWifi) {
return;
}
App.instance().startDatabaseCrawler();
}*/
@Override
public boolean onCreateOptionsMenu(Menu optionMenu) {
getMenuInflater().inflate(R.menu.main_activity, optionMenu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem miRemoveAd = menu.findItem(R.id.m_removead);
miRemoveAd.setVisible(App.instance().needPurchaseAdRemoval());
miRemoveAd.setEnabled(App.instance().needPurchaseAdRemoval());
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.m_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.m_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
case R.id.m_removead:
try {
purchasingHelper.purchaseItem(this, InAppProducts.AdRemoval);
} catch (Exception e) {
Log.e(TAG, "Start purchase ad_removal error", e);
ToastUtils.show(this, R.string.unknown_error);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RequestCodes.PURCHASE_SKU) {
try {
purchasingHelper.processPurchaseResult(data);
//TODO send purchase info to google analytics
/*getTracker().send(
new HitBuilders.ItemBuilder()
.setTransactionId(getOrderId())
.setName(getItemName(1))
.setSku(getItemSku(1))
.setCategory(getItemCategory(1))
.setPrice(getItemPrice(getView(), 1))
.setQuantity(getItemQuantity(getView(), 1))
.setCurrencyCode("USD")
.build());)*/
} catch (Exception e) {
ToastUtils.show(this, R.string.unknown_error);
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
purchasingHelper.uninit();
}
}
|
xiaodongw/gw2s
|
android/src/main/java/info/mornlight/gw2s/android/app/MainActivity.java
|
Java
|
apache-2.0
| 6,166
|
/*******************************************************************************
* Copyright 2016 Net Wolf UK
*
* 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 debrepo.teamcity;
import com.intellij.openapi.diagnostic.Logger;
/**
* An easy way to access the TeamCity loggers.
*
*/
public final class Loggers {
public static final Logger SERVER = Logger.getInstance("jetbrains.buildServer.SERVER");
public static final Logger ACTIVITIES = Logger.getInstance("jetbrains.buildServer.ACTIVITIES");
private Loggers(){}
}
|
tcplugins/tcDebRepository
|
tcdebrepo-server/src/main/java/debrepo/teamcity/Loggers.java
|
Java
|
apache-2.0
| 1,130
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="./assets/imgs/favicons/favicon.ico" />
<link rel="icon" type="image/png" href="./assets/imgs/favicons/favicon.png" />
<link rel="apple-touch-icon" sizes="57x57" href="./assets/imgs/favicons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="./assets/imgs/favicons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="./assets/imgs/favicons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="./assets/imgs/favicons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="./assets/imgs/favicons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="./assets/imgs/favicons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="./assets/imgs/favicons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="./assets/imgs/favicons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="./assets/imgs/favicons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="./assets/imgs/favicons/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="./assets/imgs/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="./assets/imgs/favicons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="./assets/imgs/favicons/favicon-16x16.png">
<link rel="manifest" href="./assets/imgs/favicons/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="./assets/imgs/favicons/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<title>Trash Connect / Codefest 2016</title>
<meta name="description" content="Trash Connect / Codefest 2016">
<!-- Schema.org markup for Google+ -->
<meta itemprop="name" content="Trash Connect / Codefest 2016 / ">
<meta itemprop="description" content="Trash Connect / Codefest 2016">
<meta itemprop="image" content="./assets/imgs/social-sharing.jpg">
<!-- Twitter Card data -->
<meta name="twitter:title" content="Trash Connect / Codefest 2016 / ">
<meta name="twitter:description" content="Trash Connect / Codefest 2016">
<!-- Open Graph data -->
<meta property="og:site_name" content="Trash Connect / Codefest 2016" />
<meta property="og:title" content="Trash Connect / Codefest 2016 / " />
<meta property="og:description" content="Trash Connect / Codefest 2016" />
<meta property="og:url" content="/pdp-admin.html" />
<meta property="og:image" content="./assets/imgs/social-sharing.jpg" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./assets/css/style.css">
<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="./assets/js/modal.js"></script>
</head>
<body>
<header class="clearfix">
<img src="./assets/imgs/logo_white.svg" onerror="this.src='./assets/imgs/logo_white.png'; this.onerror=null;" class="logo pull-left">
<button class="pull-right">LOGOUT</button>
</header>
<!-- MAP START -->
<style type="text/css">
#map {
height: 100%;
}
</style>
<div id="map"></div>
<script>
var markers = [];
var map;
function initMap() {
var mapOpts = [
{
featureType: "administrative",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "water",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "transit",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: { "lat":40.4405, "lng":-80.00015},
mapTypeId: 'nolabels',
disableDefaultUI: true
});
map.mapTypes.set('nolabels', new google.maps.StyledMapType(mapOpts, { name: 'No Labels' }));
redrawMarkers();
}
function redrawMarkers() {
$.getJSON("http://2016.pgh.codes/api/cans.php", function(json){
oldMarkers = markers;
newMarkers = [];
for (index in json.cans) doAddMarker(json.cans[index]);
function doAddMarker(_data) {
var marker = new google.maps.Marker({
position: { lat: _data.lat, lng: _data.lng },
map: map,
icon: { path: google.maps.SymbolPath.CIRCLE, scale: 3, strokeWeight: 1, fillOpacity: 1, fillColor: _data.color },
title: "Can ID: " + _data.id + ", Type: " + _data.type,
});
marker.canId = _data.id;
marker.addListener('click', function() {
displayCanModal(this.canId);
});
newMarkers.push(marker);
}
markers = newMarkers;
setTimeout(removeMarkers, 500, oldMarkers);
newMarkers = null;
});
}
function removeMarkers(markerArr) {
for (var i=0;i<markerArr.length;i++) {
markerArr[i].setMap(null);
}
}
function displayCanModal(canId) {
$.get(
"http://2016.pgh.codes/api/cans.php?",
{ canId: canId },
function(response) {
can = response.cans[0];
//populate the modal
$('#last-pickup').html(can.lastPickup);
$('#approx-location').html(can.approxLocation);
$('#recent-notes').html("");
$.each(can.recentNotes, function(index, note) {
$('#recent-notes').append(
'<li>' + note + '</li>'
);
});
$('#can-id').val(canId);
$('.on').removeClass('on');
switch(can.type) {
case 1:
$('.fa-trash.gray').addClass('on');
break;
case 2:
$('.fa-trash.black').addClass('on');
break;
case 3:
$('.fa-fire').addClass('on');
break;
case 4:
$('.fa-recycle').addClass('on');
break;
case 5:
$('.fa-certificate').addClass('on');
break;
}
//Do the thing that makes the modal appear
openModal('#trash-can-info');
},
"json"
);
}
$(document).ready(function() {
$('#logout-btn').click(function() {
$.get(
"http://2016.pgh.codes/api/auth/logout.php",
{ },
function(response) {
location.href = "index.html";
},
"json"
);
});
$('#start-event').click(function(event) {
event.preventDefault();
var body = { canId: $('#can-id').val(), bags: $('#bag-number').val(), note: $('#comments').val() };
console.log(JSON.stringify(body));
$.post(
"http://2016.pgh.codes/api/event/new.php",
JSON.stringify(body),
function(response) {
console.log(response);
if(response.success == "true") {
alert('Pickup Scheduled!');
}
else {
alert("Please make sure you've set the correct number of bags.");
}
},
"json"
);
});
});
var refreshCanInterval = setInterval(redrawMarkers, 30000);
</script>
<script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBEnFUGKXAcUT2CcCfYo8DpZ-CRG4-U6FA&callback=initMap">
</script>
<!-- MAP END -->
<div class="btn-group-3">
<button class="large view-team-btn"><i class="fa fa-users"></i></button>
<button class="large middle add-team-btn"><i class="fa fa-user-plus"></i></button>
<button class="large export-data-btn"><i class="fa fa-bar-chart"></i></button>
</div>
<!-- Manage Teams -->
<div id="view-team" class="slide-container transition">
<div class="slide-header">
<h2 class="pull-left"><i class="fa fa-users"></i> Team Directory</h2>
<a href="#" class="close pull-right">×</a>
<div class="clearfix"></div>
</div>
<div class="slide-body">
<ul class="list-names">
<li><a href="#" class="team-info-btn">John Doe</a></li>
<li><a href="#">Bobby Smith</a></li>
<li><a href="#">Amy DePalma</a></li>
<li><a href="#">Matthew Cipperly</a></li>
<li><a href="#">Robert Collini</a></li>
<li><a href="#">John Doe</a></li>
<li><a href="#">Bobby Smith</a></li>
<li><a href="#">Amy DePalma</a></li>
<li><a href="#">Matthew Cipperly</a></li>
<li><a href="#">Robert Collini</a></li>
</ul>
</div>
</div>
<!-- Team Info -->
<div id="team-info" class="slide-container transition">
<div class="slide-header">
<h2 class="pull-left"><i class="fa fa-user"></i> John Doe</h2>
<a href="#" class="close pull-right">×</a>
<div class="clearfix"></div>
</div>
<div class="slide-body">
<ul class="list-icon-group">
<li><i class="fa fa-clock-o"></i> Avg. Response Time: <span class="highlight">#### mins.</span></li>
<li><i class="fa fa-trash"></i> Avg. Bags Collected Per Shift: <span class="highlight">###</span></li>
</ul>
<button class="pull-right edit-member-btn"><i class="fa fa-pencil-square-o"></i> Edit</button>
<div class="clearfix"> </div>
</div>
</div>
<!-- Edit Member -->
<div id="edit-member" class="slide-container transition">
<div class="slide-header">
<h2 class="pull-left"><i class="fa fa-pencil-square-o"></i> Edit Team Member Info</h2>
<a href="#" class="close pull-right">×</a>
<div class="clearfix"></div>
</div>
<div class="slide-body">
<h2>John Doe</h2>
<form>
<label for="name">Update Name</label>
<input class="required-field full-width" type="text" name="name" id="name" placeholder="John Doe" />
<label for="reset">Lost Password?</label>
<button name="reset" class="secondary full-width">Reset Password</button>
<div class="clearfix"> </div>
<button class="warning pull-right"><i class="fa fa-times"></i> Delete</button>
<button class="pull-right"><i class="fa fa-check"></i> Submit</button>
<div class="clearfix"> </div>
</form>
</div>
</div>
<!-- Add Team Members -->
<div id="add-team" class="slide-container transition">
<div class="slide-header">
<h2 class="pull-left"><i class="fa fa-user-plus"></i> Add Team Member</h2>
<a href="#" class="close pull-right">×</a>
<div class="clearfix"></div>
</div>
<div class="slide-body">
<form>
<label for="name">New Team Member Name</label>
<input class="required-field full-width" type="text" name="name" id="first-name" placeholder="First" />
<input class="required-field full-width" type="text" name="name" id="last-name" placeholder="Last" />
<label for="name">User Type</label>
<select class="full-width">
<option value="pdp-staff">DPW Staff</option>
<option value="pdp-admin">DPW Admin</option>
</select>
<div class="clearfix"> </div>
<button class="pull-right"><i class="fa fa-plus"></i> Add</button>
<div class="clearfix"> </div>
</form>
</div>
</div>
<!-- Export Data -->
<div id="export-data" class="slide-container transition">
<div class="slide-header">
<h2 class="pull-left"><i class="fa fa-bar-chart"></i> Export Data</h2>
<a href="#" class="close pull-right">×</a>
<div class="clearfix"></div>
</div>
<div class="slide-body">
<form>
<label for="name">Where should this data be sent?</label>
<input class="required-field full-width" type="email" name="email" id="email" placeholder="email@website.com" />
<label for="export">Export Options</label>
- export all data<br>
<h3>or filter by:</h3>
- can type<br>
- date range<br>
- team member<br>
- shifts<br>
<div class="clearfix"> </div>
<button class="pull-right"><i class="fa fa-check"></i> Submit</button>
<div class="clearfix"> </div>
</form>
</div>
</div>
<script src="./assets/js/slideScreens.js"></script>
</body>
</html>
|
pgh-codes/codefest-2016
|
www/dpw-admin.html
|
HTML
|
apache-2.0
| 15,057
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.