repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Esri/arcobjects-sdk-community-samples
|
Net/Framework/RecentFilesCommands/CSharp/RecentFilesRegistryHelper.cs
|
1930
|
/*
Copyright 2019 Esri
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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.Framework;
using Microsoft.Win32;
namespace RecentFilesCommandsCS
{
/// <summary>
/// Helper class to process recent file lists stored in the registry
/// </summary>
class RecentFilesRegistryHelper
{
const string RecentFileRegistryKeyPath = @"Software\ESRI\Desktop{0}\{1}\Recent File List";
public static string[] GetRecentFiles(IApplication app)
{
List<string> recentFilePaths = new List<string>();
//Read the registry to get the recent file list
string version = ESRI.ArcGIS.RuntimeManager.ActiveRuntime.Version;
string openKey = string.Format(RecentFileRegistryKeyPath, version, app.Name);
RegistryKey recentListKey = Registry.CurrentUser.OpenSubKey(openKey);
if (recentListKey != null)
{
string[] listNames = recentListKey.GetValueNames();
foreach (string name in listNames)
{
string fileName = recentListKey.GetValue(name, string.Empty).ToString();
if (!string.IsNullOrEmpty(fileName))
recentFilePaths.Add(fileName);
}
}
return recentFilePaths.ToArray();
}
}
}
|
apache-2.0
|
istopwg/website
|
blog/w3c-workshop-september-2013.html
|
4481
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9">
<title>W3C Workshop on Publishing and the Open Web Platform - Printer Working Group</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css">
<link rel="stylesheet" type="text/css" href="../pwg.css">
<link rel="shortcut icon" href="../pwg.png" type="image/png">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="../pwg.js"></script>
</head>
<body onload="load_sidebar('../');">
<div id="PWGPage">
<div id="PWGHeader">
<div id="PWGHeaderBody">
<div id="PWGLogo"><img src="../pwg.png" alt="PWG Logo" height="78" width="75"></div>
<div id="PWGSearchForm">Google Custom Search</div>
<div id="PWGTitle">W3C Workshop on Publishing and the Open Web Platform<br>
<small>October 8, 2013</small></div>
</div>
</div>
<div id="PWGBody">
<div id="PWGSearchResults"></div>
<div id="PWGSideBar">
<div id="PWGSideBody">Loading...</div>
</div>
<div id="PWGContent">
<div id="PWGContentBody">
<p>A representative from the IEEE-ISTO Printer Working Group (PWG) attended the World Wide Web Consortium (W3C) <a href="http://www.w3.org/2012/12/global-publisher/Overview.html">"Publishing and the Open Web Platform"</a> workshop in September 2013 and participated in the "Standards Bodies: Who does what?" panel.</p>
<p>This W3C Workshop on publishing workflow was the third in a series of industry consultation events on publishing using the Open Web Platform. The specific goal of this workshop was to identify difficulties faced by existing professional publishing organizations in using tools based on the Open Web platform, including the production of printed books, and to find ways to eliminate or ameliorate those difficulties. Some of the topics listed were print-on-demand, color management, ink control, specifying media, binding, trimming, and finishing, all areas of interest to the PWG. The conclusions of these workshops will be communicated to the applicable W3C workgroups, particularly the Cascading Style Sheets (CSS) working group to address limitations in CSS design and implementation.</p>
<p>The PWG initially submitted a <a href="ftp://pwg.org/pub/pwg/general/proposals/w3c-publishing-august-2013.pdf">position paper</a> prepared by Paul Tykodi. Once accepted, PWG representative Bill Wagner gave a <a href="http://www.w3.org/2012/12/global-publisher/slides/Day1/P3-pwg-w3c-properties-20130823-2.pdf">presentation</a> outlining PWG credentials as a printing standards body and the PWG position with respect to including PWG Print Job Ticket production specification elements along with content and format information in the Open Web publishing workflow.</p>
<p>The workshop identified areas needing attention that were within the purview of the W3C, possibly in conjunction with other organizations. However, it was observed that the schedule and plans of the CSS working group are very full and that their priorities are dictated by requirements identified by major user communities. Although no specific conclusions were drawn with respect to print production aspects, such as the PWG proposal, one resolution of the workshop was that:</p>
<blockquote>"Liaisons should be established where needed with other standards bodies and industry organizations, and contact maintained in order to avoid duplication of effort or needless competition."</blockquote>
<p>The PWG will support such contact with Digital Publishing Interest Group within the Digital Publishing Activity at W3C and the CSS working group.</p>
</div>
</div>
</div>
<div id="PWGFooter">
<div id="PWGFooterBody">Comments are owned by the poster. All
other material is Copyright © 2001-2013 The Printer Working
Group. All rights reserved. IPP Everywhere, the IPP Everywhere logo, and the PWG logo are trademarks of the IEEE-ISTO. Please contact the <a
href="mailto:[email protected]">PWG Webmaster</a> to report
problems with this site.</div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum lasiocarpum/ Syn. Solanum ferox lasiocarpum/README.md
|
200
|
# Solanum ferox var. lasiocarpum (Dunal) Miq. VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
euniceschoi/euniceschoi
|
blog/arrays-hashes.html
|
10680
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Eunice Choi - About</title>
<!-- Bootstrap Core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/business-casual.css" rel="stylesheet">
<!-- Fonts -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">
</head>
<body>
<div class="brand">Eunice Choi</div>
<div class="address-bar">Web Development Student | Dev BootCamp SF </div>
<!-- Navigation -->
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-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>
<!-- navbar-brand is hidden on larger screens, but visible when the menu is collapsed -->
<a class="navbar-brand" href="index.html">Eunice Choi</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="../index.html">Home</a>
</li>
<li>
<a href="../about.html">About</a>
</li>
<li>
<a href="../blog1.html">Blog</a>
</li>
<li>
<a href="../projects.html">Projects</a>
</li>
<li>
<a href="../contact.html">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
<strong>[Arrays] vs. {Hashes}</strong>
</h2>
<hr>
</div>
<div class="col-lg-12 text-center">
<!-- <img class="img-responsive img-border img-full" src="img/slide-1.jpg" alt=""> -->
<small>September 13, 2015</small>
<br>
<br>
<p>
Which do you think is harder: learning Ruby or teaching a class of kindergarteners? I think they are equally challenging, but in this blog, I'd like you to do both at once in order to understand arrays and hashes.
</p>
<br>
<p>
Arrays and hashes are both <b>indexed collections</b>. Collection means that they can store objects such as strings and integers. Indexed means that they have "keys" to access each of their stored objects. Like a key to a classroom door, you can only access an object in an array or a hash with its indexed key! Now let's unlock the door to your classroom and prepare for your first kindergarten lesson. First thing on the list: get to know your students' names.
</p>
<hr>
<h3 style="color:white">[Arrays]</h3>
<br>
<p>
Let's create an array with your class roster. You could call your array "students" and store all of your students' names. It would look something like this:
</p>
<pre>students = ['James', 'Peter', 'Emily', 'Sam', 'Brian', 'Karen', 'Claire']
</pre>
<br>
<p>
Remember how I said that arrays and hashes are indexed? Arrays are unique in that they are integer-indexed, starting with 0. In the array above, an index of 0 would indicate James. An index of 1 would represent Peter, an index of 2 would represent Emily, so on and so forth. To access each element in your array, you need to type the array name next to the index integer in brackets. For instance, you would type the following code to access the first name on the list:
</p>
<pre>students[0]</pre>
<br>
<p>
Arrays have many useful built in methods. For instance, you could alphabetize the students names by using:
<pre>students.sort</pre>
</p>
<br>
<p>
or even find the number of students in your class by typing:
</p>
<pre>students.count</pre>.
<p>
You can even have empty arrays!
</p>
<pre>students = []</pre>
<hr>
<h3 style="color:white">{Hashes}</h3>
<br>
<p>Now that you are familiar with your students' names, why don't we assign your students their cubbies?</p>
<img style="width:500px; height:400px" src="http://3.bp.blogspot.com/-2YPmEGDH3V8/UCaDt7P9AEI/AAAAAAAAAJo/wvbDusib6Uo/s1600/cubbies.JPG">
<br>
<br>
<p>
Since your cubbies have number labels on them, why don't we just assign each student a number? Let's create a hash called "cubbies_assignment" to do this job:
</p>
<pre>cubbies_assignment = {<br> 1 => 'James',<br> 2 => 'Peter',<br> 3 => 'Emily',<br> 4 => 'Sam',<br> 5 => 'Brian',<br> 6 => 'Karen',<br> 7 => 'Claire'<br>}</pre>
<br>
<p>
As you can see, hashes are similar to arrays in that they store objects. The hash above stores your students' names along with their cubby numbers. So what makes hashes so different from arrays? One thing for sure, you can see that hashes use {braces} in stead of [brackets]. They also hold two objects for every entry: a key and a value. Earlier, arrays were integer-indexed starting from 0. Hashes, on the other hand, are indexed by the key you label them with. The left side of the "=>"" represents the key while the right side represents the value:
</p>
<pre>key => value</pre>
<br>
<p>In order to index each value you would type:</p>
<pre>hash_name[key]</pre>
<br>
<p>To index Karen, you would input:
</p>
<pre>cubbies_assignment[6]</pre>
<br>
<p>
Like arrays, hashes also have great build-in methods. To print just the keys of your hash, you can type:</p>
<pre>cubbies_assignment.keys</pre>
<pre>=> [1, 2, 3, 4, 5, 6, 7]</pre>
<br>
<p>To get the number of cubbies, you could type:</p>
<pre>cubbies_assignment.length</pre>
<br>
<p>What if you want to assign a new student a cubby? You could add to an existing hash by typing:</p>
<pre>hash[:8] = 'Diane'</pre>
<hr>
<br>
<p>
In your classroom, hashes and arrays were used for storing important data: students' names and cubby numbers. In programming, they are used in the same way. Arrays are useful for storing values that can be accessed through "implied" keys from 0 up. Hashes are useful for look up actions. For instance, you are able look up a student's name by typing in his or her cubby number. Both arrays and hashes are powerful tools, and I hope you found this blog helpful for understanding their uses!
</p>
</div>
<hr>
</div>
<div class="col-lg-12 text-center">
<ul class="pager">
<li class="previous"><a href="css-concepts.html">← Older</a>
</li>
<li class="next"><a href="issues-tech.html">Newer →</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<ul class="soc">
<li><a href="https://twitter.com/euniceesc"><img src="../img/twitter.png" alt="Twitter Icon"></a></li>
<li><a href="https://www.facebook.com/EuniceSChoi"><img src="../img/facebook.png" alt="Facebook Icon"></a></li>
<li><a href="https://plus.google.com/u/0/113732345844394468529"><img src="../img/googleplus.png" alt="Google Icon"></a></li>
<li><a href="https://www.linkedin.com/in/euniceschoi"><img src="../img/linkedin.png" alt="Linked In Icon"></a></li>
<li><a href="mailto:[email protected]"><img src="../img/email.png" alt="GitHub Icon"></a></li>
</ul>
<p><!-- Copyright © Eunice Choi 2015 --></p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
apache-2.0
|
rsertelon/habitat
|
components/core/src/os/signals.rs
|
1060
|
//! Contains the cross-platform signal behavior.
// If signal handling ever becomes part of the rust stdlib, consider removing
// our homespun implementation. Check for status of that here:
// https://github.com/rust-lang/rfcs/issues/1368
use std::sync::atomic::{AtomicBool,
Ordering};
#[cfg(unix)]
mod unix;
#[cfg(unix)]
pub use self::unix::{init,
pending_sigchld,
pending_sighup};
static SHUTDOWN: AtomicBool = AtomicBool::new(false);
// NOTE: The Unix implementation of `init` also establishes a similar
// handler for shutdown signals, but also does some other stuff, as
// well. Seems best for now to keep all those implementation details
// in the `unix` module.
#[cfg(windows)]
pub fn init() {
ctrlc::set_handler(move || {
SHUTDOWN.store(true, Ordering::SeqCst);
}).expect("Error setting Ctrl-C handler");
}
/// Returns `true` if we have received a signal to shut down.
pub fn pending_shutdown() -> bool { SHUTDOWN.compare_and_swap(true, false, Ordering::SeqCst) }
|
apache-2.0
|
greghogan/flink
|
flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/planner/plan/stream/table/PythonAggregateTest.scala
|
4608
|
/*
* 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.flink.table.planner.plan.stream.table
import org.apache.flink.api.java.tuple.Tuple1
import org.apache.flink.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.dataview.{ListView, MapView}
import org.apache.flink.table.planner.plan.nodes.common.CommonPythonAggregate
import org.apache.flink.table.planner.runtime.utils.JavaUserDefinedAggFunctions.TestPythonAggregateFunction
import org.apache.flink.table.planner.typeutils.DataViewUtils.{DataViewSpec, ListViewSpec, MapViewSpec}
import org.apache.flink.table.planner.utils.TableTestBase
import org.apache.flink.table.types.DataType
import org.junit.Assert.assertEquals
import org.junit.Test
class PythonAggregateTest extends TableTestBase {
@Test
def testPythonGroupAggregateWithoutKeys(): Unit = {
val util = streamTestUtil()
val sourceTable = util.addTableSource[(Int, Long, Int)]("MyTable", 'a, 'b, 'c)
val func = new TestPythonAggregateFunction
val resultTable = sourceTable.select(func('a, 'c))
util.verifyPlan(resultTable)
}
@Test
def testPythonGroupAggregate(): Unit = {
val util = streamTestUtil()
val sourceTable = util.addTableSource[(Int, Long, Int)]("MyTable", 'a, 'b, 'c)
val func = new TestPythonAggregateFunction
val resultTable = sourceTable.groupBy('b)
.select('b, func('a, 'c))
util.verifyPlan(resultTable)
}
@Test
def testMixedUsePythonAggAndJavaAgg(): Unit = {
val util = streamTestUtil()
val sourceTable = util.addTableSource[(Int, Long, Int)]("MyTable", 'a, 'b, 'c)
val func = new TestPythonAggregateFunction
val resultTable = sourceTable.groupBy('b)
.select('b, func('a, 'c), 'a.count())
util.verifyPlan(resultTable)
}
@Test
def testExtractDataViewSpecs(): Unit = {
val accType = DataTypes.ROW(
DataTypes.FIELD("f0", DataTypes.STRING()),
DataTypes.FIELD("f1", ListView.newListViewDataType(DataTypes.STRING())),
DataTypes.FIELD("f2", MapView.newMapViewDataType(DataTypes.STRING(), DataTypes.BIGINT())))
val specs = TestCommonPythonAggregate.extractDataViewSpecs(accType)
val expected = Array(
new ListViewSpec(
"agg0$f1",
1,
DataTypes.ARRAY(DataTypes.STRING()).bridgedTo(classOf[java.util.List[_]])),
new MapViewSpec(
"agg0$f2",
2,
DataTypes.MAP(
DataTypes.STRING(), DataTypes.BIGINT()).bridgedTo(classOf[java.util.Map[_, _]]),
false))
assertEquals(expected(0).getClass, specs(0).getClass)
assertEquals(expected(0).getDataType, specs(0).getDataType)
assertEquals(expected(0).getStateId, specs(0).getStateId)
assertEquals(expected(0).getFieldIndex, specs(0).getFieldIndex)
assertEquals(expected(1).getClass, specs(1).getClass)
assertEquals(expected(1).getDataType, specs(1).getDataType)
assertEquals(expected(1).getStateId, specs(1).getStateId)
assertEquals(expected(1).getFieldIndex, specs(1).getFieldIndex)
}
@Test(expected = classOf[TableException])
def testExtractSecondLevelDataViewSpecs(): Unit = {
val accType = DataTypes.ROW(
DataTypes.FIELD("f0", DataTypes.ROW(
DataTypes.FIELD("f0", ListView.newListViewDataType(DataTypes.STRING())))))
TestCommonPythonAggregate.extractDataViewSpecs(accType)
}
@Test(expected = classOf[TableException])
def testExtractDataViewSpecsFromStructuredType(): Unit = {
val accType = DataTypes.STRUCTURED(
classOf[Tuple1[_]],
DataTypes.FIELD("f0", ListView.newListViewDataType(DataTypes.STRING())))
TestCommonPythonAggregate.extractDataViewSpecs(accType)
}
}
object TestCommonPythonAggregate extends CommonPythonAggregate {
def extractDataViewSpecs(accType: DataType): Array[DataViewSpec] = {
extractDataViewSpecs(0, accType)
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Sophora/Sophora tonkinensis/ Syn. Cephalostigmaton tonkinense/README.md
|
203
|
# Cephalostigmaton tonkinense (Gagnep.) Yakovlev SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
GoogleCloudPlatform/stackdriver-reverse-proxy
|
cmd/stackdriver-reverse-proxy/main.go
|
3169
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Program stackdriver-reverse-proxy provides a Stackdriver reverse
// proxy that creates traces for the incoming requests, logs request
// details, and reports errors.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"go.opencensus.io/exporter/stackdriver"
"go.opencensus.io/exporter/stackdriver/propagation"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
)
var (
projectID string
listen string
target string
tlsCert string
tlsKey string
traceFrac float64
disableMonitoring bool
monitoringPeriod string
)
const usage = `stackdriver-reverse-proxy [opts...] -target=<host:port>
For example, to start at localhost:6996 to proxy requests to localhost:6060,
$ stackdriver-reverse-proxy -target=http://localhost:6060
Options:
-http hostname:port to start the proxy server, by default localhost:6996.
-target hostname:port where the app server is running.
-project Google Cloud Platform project ID if running outside of GCP.
Tracing options:
-trace-sampling Tracing sampling fraction, between 0 and 1.0.
HTTPS options:
-tls-cert TLS cert file to start an HTTPS proxy.
-tls-key TLS key file to start an HTTPS proxy.
`
func main() {
flag.Usage = func() {
fmt.Println(usage)
}
flag.StringVar(&projectID, "project", "", "")
flag.StringVar(&listen, "http", ":6996", "host:port proxy listens")
flag.StringVar(&target, "target", "", "target server")
flag.Float64Var(&traceFrac, "trace-sampling", 1, "sampling fraction for tracing")
flag.StringVar(&tlsCert, "tls-cert", "", "TLS cert file to start an HTTPS proxy")
flag.StringVar(&tlsKey, "tls-key", "", "TLS key file to start an HTTPS proxy")
flag.Parse()
if target == "" {
usageExit()
}
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: projectID,
})
if err != nil {
log.Fatal(err)
}
view.RegisterExporter(exporter)
trace.RegisterExporter(exporter)
view.Subscribe(ochttp.DefaultViews...)
trace.SetDefaultSampler(trace.ProbabilitySampler(traceFrac))
url, err := url.Parse(target)
if err != nil {
log.Fatalf("Cannot URL parse -target: %v", err)
}
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.Transport = &ochttp.Transport{
Propagation: &propagation.HTTPFormat{},
}
if tlsCert != "" && tlsKey != "" {
log.Fatal(http.ListenAndServeTLS(listen, tlsCert, tlsKey, proxy))
} else {
log.Fatal(http.ListenAndServe(listen, proxy))
}
}
func usageExit() {
flag.Usage()
os.Exit(1)
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/DescribeInventoryDeletionsRequestProtocolMarshaller.java
|
2897
|
/*
* Copyright 2014-2019 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.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeInventoryDeletionsRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeInventoryDeletionsRequestProtocolMarshaller implements
Marshaller<Request<DescribeInventoryDeletionsRequest>, DescribeInventoryDeletionsRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AmazonSSM.DescribeInventoryDeletions").serviceName("AWSSimpleSystemsManagement").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DescribeInventoryDeletionsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DescribeInventoryDeletionsRequest> marshall(DescribeInventoryDeletionsRequest describeInventoryDeletionsRequest) {
if (describeInventoryDeletionsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DescribeInventoryDeletionsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, describeInventoryDeletionsRequest);
protocolMarshaller.startMarshalling();
DescribeInventoryDeletionsRequestMarshaller.getInstance().marshall(describeInventoryDeletionsRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
apache-2.0
|
UW-Madison-DoIT/widget-creator
|
src/main/webapp/my-app/navigation/drawer.html
|
1221
|
<md-menu-item>
<md-button href="/" ng-click="vm.closeMainMenu();" layout="row" layout-align="start center">
<span>
<md-icon>home</md-icon>
</span>
<span>Widget creator home</span>
</md-button>
</md-menu-item>
<md-menu-item>
<md-button href="/about" ng-click="vm.closeMainMenu();" layout="row" layout-align="start center">
<span>
<md-icon>details</md-icon>
</span>
<span>About</span>
</md-button>
</md-menu-item>
<md-menu-item>
<md-button href="/version-info" ng-click="vm.closeMainMenu();" layout="row" layout-align="start center">
<span>
<md-icon>info</md-icon>
</span>
<span>Version info</span>
</md-button>
</md-menu-item>
<md-menu-item>
<md-button href="https://tools.my.wisc.edu/home/" ng-click="vm.closeMainMenu();" layout="row" layout-align="start center">
<span>
<md-icon>widgets</md-icon>
</span>
<span>Other tools</span>
</md-button>
</md-menu-item>
<md-menu-item>
<md-button href="https://uw-madison-doit.github.io/widget-creator/" ng-click="vm.closeMainMenu();" layout="row" layout-align="start center">
<span>
<md-icon>book</md-icon>
</span>
<span>Documentation</span>
</md-button>
</md-menu-item>
|
apache-2.0
|
asakusafw/asakusafw
|
core-project/asakusa-runtime/src/main/java/com/asakusafw/runtime/flow/ListBuffer.java
|
3339
|
/**
* Copyright 2011-2021 Asakusa Framework 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 com.asakusafw.runtime.flow;
import java.util.List;
/**
* A List interface for reusing instances of element objects.
<pre><code>
Iterator<Hoge> iter = ...;
ListBuffer<Hoge> hoges = ...;
...
hoges.begin();
while (iter.hasNext()) {
Hoge hoge = iter.next();
if (hoges.isExpandRequired()) {
hoges.expand(new Hoge());
}
hoges.advance().set(hoge);
}
hoges.end();
// use hoges as List
hoges.shrink();
</code></pre>
* @param <E> the element type
*/
public interface ListBuffer<E> extends List<E> {
/**
* Begins changing the list buffer.
* Initially, the internal cursor is on the head of this buffer, and clients can move it to the next element
* by invoking {@link #advance()}.
* After changing the buffer, then clients must invoke {@link #end()} and the buffer can be used as the
* unmodifiable list.
* @see #advance()
* @throws BufferException if failed to prepare buffer
*/
void begin();
/**
* Ends changing the list buffer.
* After this, clients should not change the buffer contents.
* If clients want to change the buffer, must invoke {@link #begin()} once more.
* @throws BufferException if failed to prepare buffer
*/
void end();
/**
* Returns whether a new element object is required for the buffer or not.
* If it required, clients must use {@link #expand(Object)} to add a new object before invoke {@link #advance()}.
* This method must be invoked between {@link #begin()} and {@link #end()}.
* @return {@code true} if a new element object is required, otherwise {@code false}
* @see #expand(Object)
* @throws BufferException if failed to prepare buffer
*/
boolean isExpandRequired();
/**
* Adds a new element object into the tail of this buffer.
* This method must be invoked between {@link #begin()} and {@link #end()}.
* @param value the object
* @see #isExpandRequired()
* @throws IndexOutOfBoundsException if expand is not required (optional operation)
* @see #isExpandRequired()
* @throws BufferException if failed to prepare buffer
*/
void expand(E value);
/**
* Returns the next element object on the internal cursor, and then move the cursor to the next element.
* This method must be invoked between {@link #begin()} and {@link #end()}.
* @return the next element object
* @throws IndexOutOfBoundsException if the next element object is not prepared
* @see #isExpandRequired()
* @see #expand(Object)
* @throws BufferException if failed to prepare buffer
*/
E advance();
/**
* Shrinks this buffer.
*/
void shrink();
}
|
apache-2.0
|
wanhao/IRIndex
|
docs/apidocs/org/apache/hadoop/hbase/master/metrics/package-use.html
|
8449
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Jan 10 21:37:07 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.apache.hadoop.hbase.master.metrics (HBase 0.94.16 API)
</TITLE>
<META NAME="date" CONTENT="2014-01-10">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.apache.hadoop.hbase.master.metrics (HBase 0.94.16 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/hbase/master/metrics/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>org.apache.hadoop.hbase.master.metrics</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/hadoop/hbase/master/metrics/package-summary.html">org.apache.hadoop.hbase.master.metrics</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.hbase.master"><B>org.apache.hadoop.hbase.master</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.hbase.master.snapshot"><B>org.apache.hadoop.hbase.master.snapshot</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.hbase.master"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../../org/apache/hadoop/hbase/master/metrics/package-summary.html">org.apache.hadoop.hbase.master.metrics</A> used by <A HREF="../../../../../../org/apache/hadoop/hbase/master/package-summary.html">org.apache.hadoop.hbase.master</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/hadoop/hbase/master/metrics/class-use/MasterMetrics.html#org.apache.hadoop.hbase.master"><B>MasterMetrics</B></A></B>
<BR>
This class is for maintaining the various master statistics
and publishing them through the metrics interfaces.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.hbase.master.snapshot"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../../org/apache/hadoop/hbase/master/metrics/package-summary.html">org.apache.hadoop.hbase.master.metrics</A> used by <A HREF="../../../../../../org/apache/hadoop/hbase/master/snapshot/package-summary.html">org.apache.hadoop.hbase.master.snapshot</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../../org/apache/hadoop/hbase/master/metrics/class-use/MasterMetrics.html#org.apache.hadoop.hbase.master.snapshot"><B>MasterMetrics</B></A></B>
<BR>
This class is for maintaining the various master statistics
and publishing them through the metrics interfaces.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/hbase/master/metrics/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.3.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/jose/class-use/VerificationOutput.html
|
10621
|
<!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_151) on Sat Mar 16 04:11:58 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.jose.VerificationOutput (BOM: * : All 2.3.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-03-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 Class org.wildfly.swarm.jose.VerificationOutput (BOM: * : All 2.3.1.Final-SNAPSHOT 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="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-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">Thorntail API, 2.3.1.Final-SNAPSHOT</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/jose/class-use/VerificationOutput.html" target="_top">Frames</a></li>
<li><a href="VerificationOutput.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.wildfly.swarm.jose.VerificationOutput" class="title">Uses of Class<br>org.wildfly.swarm.jose.VerificationOutput</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="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</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.jose">org.wildfly.swarm.jose</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.jose.provider">org.wildfly.swarm.jose.provider</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.jose">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a> in <a href="../../../../../org/wildfly/swarm/jose/package-summary.html">org.wildfly.swarm.jose</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/wildfly/swarm/jose/package-summary.html">org.wildfly.swarm.jose</a> that return <a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></code></td>
<td class="colLast"><span class="typeNameLabel">Jose.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/jose/Jose.html#verification-java.lang.String-">verification</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> jws)</code>
<div class="block">Verify the signed data in the JWS compact or JSON (optional) format.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></code></td>
<td class="colLast"><span class="typeNameLabel">Jose.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/jose/Jose.html#verificationDetached-java.lang.String-java.lang.String-">verificationDetached</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> jws,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> detachedData)</code>
<div class="block">Verify the signed and detached data in the JWS compact or JSON (optional) format.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.jose.provider">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a> in <a href="../../../../../org/wildfly/swarm/jose/provider/package-summary.html">org.wildfly.swarm.jose.provider</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/wildfly/swarm/jose/provider/package-summary.html">org.wildfly.swarm.jose.provider</a> that return <a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></code></td>
<td class="colLast"><span class="typeNameLabel">DefaultJoseImpl.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/jose/provider/DefaultJoseImpl.html#verification-java.lang.String-">verification</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> jws)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">VerificationOutput</a></code></td>
<td class="colLast"><span class="typeNameLabel">DefaultJoseImpl.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/jose/provider/DefaultJoseImpl.html#verificationDetached-java.lang.String-java.lang.String-">verificationDetached</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> jws,
<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> detachedData)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="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="../../../../../org/wildfly/swarm/jose/VerificationOutput.html" title="class in org.wildfly.swarm.jose">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-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">Thorntail API, 2.3.1.Final-SNAPSHOT</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/jose/class-use/VerificationOutput.html" target="_top">Frames</a></li>
<li><a href="VerificationOutput.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 © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
metrilyx/metrilyx-web
|
app/timeselector/time-selector.html
|
1445
|
<table class="table" style="margin-bottom:0px;border:none;" time-selector ng-switch="timeDimension.activeType">
<tr ng-switch-when="Absolute">
<td style="border-left: 1px solid #ccc;padding:0;vertical-align:middle">
<div style="border-left: 1px solid #fff">
<time-range-selector></time-range-selector>
</div>
</td>
<td style="width:55px;border-left:1px solid #ccc;padding:0" ng-click="timeDimension.activeType = 'Relative'">
<div style="border-left:1px solid #fff">
<button type="button" class="btn btn-theme" style="padding: 13px 20px">
<span class="glyphicon glyphicon-time" title="Change to relative time"></span>
</button>
</div>
</td>
</tr>
<tr ng-switch-default>
<td style="vertical-align:middle;text-align:right">
<auto-updater></auto-updater>
<relative-time-selector></relative-time-selector>
</td>
<td style="width:55px;border-left:1px solid #ccc;padding:0" ng-click="timeDimension.activeType = 'Absolute'">
<div style="border-left:1px solid #fff">
<button type="button" class="btn btn-theme" style="padding: 13px 20px">
<span class="glyphicon glyphicon-calendar" title="Change to custom range"></span>
</button>
</div>
</td>
</tr>
</table>
|
apache-2.0
|
yannicl/fba
|
README.md
|
8
|
fba
===
|
apache-2.0
|
luoqii/osgi_android_demos_from_network
|
apkplug/apkplugDemo/bundle/BundleDemoApkplugService/src/net/tsz/afinal/bitmap/core/BaseMemoryCacheImpl.java
|
1471
|
/**
* Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com).
*
* 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 net.tsz.afinal.bitmap.core;
import net.tsz.afinal.utils.Utils;
import android.graphics.Bitmap;
public class BaseMemoryCacheImpl implements IMemoryCache {
private final LruMemoryCache<String, Bitmap> mMemoryCache;
public BaseMemoryCacheImpl(int size) {
mMemoryCache = new LruMemoryCache<String, Bitmap>(size) {
protected int sizeOf(String key, Bitmap bitmap) {
return Utils.getBitmapSize(bitmap);
}
};
}
public void put(String key, Bitmap bitmap) {
mMemoryCache.put(key, bitmap);
}
public Bitmap get(String key) {
return mMemoryCache.get(key);
}
public void evictAll() {
mMemoryCache.evictAll();
}
public void remove(String key) {
mMemoryCache.remove(key);
}
}
|
apache-2.0
|
renmaoting/maze-storm
|
maze storm/Assets/script/level7/monkey7.cs
|
4277
|
using UnityEngine;
using System.Collections;
public class monkey7 : MonoBehaviour {
public float speed = 100f;//英雄速度
public Vector2 current_position;
Animator animator;
public Grid grid = new Grid(14,10);
public AStar astar;
public float time = 0;
public bool finish = false;//是否已经完成
public bool walk = false;//是否已经开始
private bool findroad = false;//是否找到路径
private int hasdone; //已经走过的寻路结点
public background7 bg;//调用脚本background中的地图
// Use this for initialization
void Start () {
GameObject backgd = GameObject.Find ("background"); //调用脚本background中的地图
bg = (background7)backgd.GetComponent (typeof(background7));
}
public void InitGame()//初始化寻路网格
{
hasdone = 1;
astar = new AStar();
animator = GetComponent<Animator> ();
for (int i =0; i< 14; i++) {//初始化地图是否可走
for (int j =0; j< 10; j++) {
if(bg.level7.map [i, j]!= 0)
grid.SetWalkbale(i,j,false);
else
grid.SetWalkbale(i,j,true);
}
}
grid.SetStartNode (10,6);
grid.SetEndNode (7,4);
}
void FixedUpdate()
{
if(bg.stspt.click == true && walk == false) {//开始键被按下
InitGame();
walk = true;
if(astar.findPath(grid) == true)
{
findroad = true;
//print(astar._path.Count);
}
}
else if (walk == true && hasdone < astar._path.Count) {
time += Time.deltaTime;
Vector2 des;//目的地
des.x = astar._path[hasdone].x*64 + 32;
des.y = astar._path[hasdone].y*64 + 50;
if(WalkTo (des) == true)
{
hasdone++;
}
}
if (astar!=null && hasdone >= astar._path.Count)
{
finish = true;
walk = false;
bg.stspt.click = false;
//Destroy(gameObject);
transform.localScale = new Vector3(0,0,0);
}
}
void TurnRight()//向右转弯的时候打开所有通向右方向的动画和关闭从右出去的动画
{
//animator.SetInteger ("etorr", 1);
animator.SetInteger ("rbtorr", 1);
animator.SetInteger ("rftorr", 1);
animator.SetInteger ("rrtorb", 0);
animator.SetInteger ("rrtorf", 0);
}
void TurnLeft()
{
//animator.SetInteger ("etorl", 1);
animator.SetInteger ("rbtorl", 1);
animator.SetInteger ("rftorl", 1);
animator.SetInteger ("rltorb", 0);
animator.SetInteger ("rltorf", 0);
}
void TurnBack()
{
//animator.SetInteger ("etorb", 1);
animator.SetInteger ("rftorb", 1);
animator.SetInteger ("rrtorb", 1);
animator.SetInteger ("rltorb", 1);
animator.SetInteger ("rbtorl", 0);
animator.SetInteger ("rbtorr", 0);
animator.SetInteger ("rbtorf", 0);
}
void TurnFront()
{
//animator.SetInteger ("etorf", 1);
animator.SetInteger ("rbtorf", 1);
animator.SetInteger ("rrtorf", 1);
animator.SetInteger ("rltorf", 1);
animator.SetInteger ("rftorr", 0);
animator.SetInteger ("rftorl", 0);
animator.SetInteger ("rftorb", 0);
}
void GoRight(Vector2 CurPos)
{
TurnRight ();
Vector2 target = Vector2.right*speed+ CurPos;
transform.position = Vector2.Lerp( CurPos, target, Time.deltaTime );
}
void GoLeft(Vector2 CurPos)
{
TurnLeft ();
Vector2 target = -Vector2.right*speed + CurPos;
transform.position = Vector2.Lerp( CurPos, target, Time.deltaTime );
}
void GoBack(Vector2 CurPos)
{
TurnBack ();
Vector2 target = Vector2.up*speed + CurPos;
transform.position = Vector2.Lerp( CurPos, target, Time.deltaTime );
}
void GoFront(Vector2 CurPos)
{
TurnFront ();
Vector2 target = -Vector2.up*speed + CurPos;
transform.position = Vector2.Lerp( CurPos, target, Time.deltaTime );
}
bool WalkTo(Vector2 target)//根据目标点调用向哪个方向走
{
current_position = transform.position;
if (current_position.x < target.x && Mathf.Abs(current_position.x - target.x) >5 ) {
GoRight (current_position);
return false;
}
else if (current_position.x > target.x && Mathf.Abs(current_position.x - target.x) >5) {
GoLeft (current_position);
return false;
}
else if (current_position.y < target.y && Mathf.Abs(current_position.y - target.y) >5) {
GoBack (current_position);
return false;
}
else if (current_position.y > target.y && Mathf.Abs(current_position.y - target.y) >5) {
GoFront(current_position);
return false;
}
return true;
}
}
|
apache-2.0
|
livingvirus/jphp
|
jphp-swing-ext/src/org/develnext/jphp/swing/loader/support/propertyreaders/JToolBarPropertyReaders.java
|
1566
|
package org.develnext.jphp.swing.loader.support.propertyreaders;
import org.develnext.jphp.swing.loader.support.PropertyReader;
import org.develnext.jphp.swing.loader.support.Value;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;
public class JToolBarPropertyReaders extends PropertyReaders<JToolBar> {
protected final Map<String, PropertyReader<JToolBar>> register = new HashMap<String, PropertyReader<JToolBar>>(){{
put("floatable", FLOATABLE);
put("vertical", VERTICAL);
put("rollover", ROLLOVER);
}};
@Override
protected Map<String, PropertyReader<JToolBar>> getRegister() {
return register;
}
@Override
public Class<JToolBar> getRegisterClass() {
return JToolBar.class;
}
public final static PropertyReader<JToolBar> FLOATABLE = new PropertyReader<JToolBar>() {
@Override
public void read(JToolBar component, Value value) {
component.setFloatable(value.asBoolean());
}
};
public final static PropertyReader<JToolBar> VERTICAL = new PropertyReader<JToolBar>() {
@Override
public void read(JToolBar component, Value value) {
component.setOrientation(value.asBoolean() ? SwingConstants.VERTICAL : SwingConstants.HORIZONTAL);
}
};
public final static PropertyReader<JToolBar> ROLLOVER = new PropertyReader<JToolBar>() {
@Override
public void read(JToolBar component, Value value) {
component.setRollover(value.asBoolean());
}
};
}
|
apache-2.0
|
Orange-OpenSource/matos-profiles
|
matos-android/src/main/java/android/nfc/NfcEvent.java
|
842
|
package android.nfc;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public final class NfcEvent
{
// Fields
public final NfcAdapter nfcAdapter = (NfcAdapter) null;
// Constructors
NfcEvent(NfcAdapter arg1){
}
}
|
apache-2.0
|
LiuRanchao/LiuRanchao.github.io
|
_posts/《敏捷技能修炼》.md
|
8816
|
---
layout: post
title: 《敏捷技能修炼》
tags:
- 敏捷开发
categories: Book
description: 《敏捷技能修炼》
---

# 第一部分 最关键的小舵板
## 第1章 意图导向编程
从上至下的一步步实现,先声明好方法,一步步为了最重编译通过而实现。
**优点:**
- 更加内聚(职责单一)
- 更加可读和清晰
- 更易于调试
- 更易于重构和优化,所以只做最少设计,满足当前需要
- 更易于单元测试
- 模式更容易应用到代码中
- 创建的方法可以容易地从一个类移动到另一个类
- 代码更易于维护
## 第2章 分离构造和使用
创建类 和 引用类分离开来
旧的方式:
~~~ java
public class BusinessObject {
public void actionMethod() {
// Other things
Service myServiceObject = new Service();
myServiceObject.doService();
// Other things
}
}
~~~
如果创建Service对象的方式修改了,此时就需要修改BusinessObject
**创建者:关心这个对象是什么**
**使用者:关心这个对象能做什么**
**方案1(通过依赖注入方式):**
~~~ java
public class BusinessObject {
private Service myServiceObject;
public BusinessObject(Service aService) {
myServiceObject = aService;
}
public void actionMethod() {
// Other things
myServiceObject.doService();
// Other things
}
}
~~~
**方案2(通过工厂方式):**
~~~ java
public class BusinessObject {
private Service myServiceObject;
public BusinessObject() {
myServiceObject = ServiceFactory.getService();
}
public void actionMethod() {
// Other things
myServiceObject.doService();
// Other things
}
}
~~~
~~~ java
public class ServiceFactory {
public static Service getService() {
if (someCondition) {
return new ServiceImpl1();
} else {
return new ServiceImpl2();
}
}
}
~~~
~~~ java
interface Service{
void doService();
}
~~~
~~~ java
class ServiceImpl1 implements Service {
void doService(){}
}
~~~
~~~ java
class ServiceImpl2 implements Service {
void doService(){}
}
~~~
**方案3(类似单例):**
如果发生更复杂的变化,则可以变更为方案2
~~~ java
public class BusinessObject {
private Service myServiceObject;
public BusinessObject() {
myServiceObject = Service.getInstance();
}
public void actionMethod() {
// Other things
myServiceObject.doService();
// Other things
}
}
~~~
~~~ java
class Service{
private Service(){
// any needed construction behavior
}
public static Service getInstance(){
return new Service();
}
public void doService() {
// implementation here
}
}
~~~
## 第3章 代码未动,测试先行
步骤如下:
1. 设计测试
2. 编写测试用例
3. 编写代码
4. 执行测试用例
## 第4章 Shalloway法则和Shalloway原则
**冗余的种类:**
- 复制和粘贴
- “魔法”数字
- 其他类型
- 保存到文件
- 保存到数据库
- 冗余信息
- 冗余实现
- 一个概念(数据,算法,带啊妈)
在修改代码的时候,如果对一处做了修改,那么你必须在其他地方也做出相应的改动,这就是冗余。
**使用模式减少冗余:**
- 策略(Strategy)模式处理多种不同的算法
- 桥接(Bridge)模式处理多种代码实现之间的衔接
- 模版(Template Method)模式处理同一种流程下的不同代码实现方案
- 装饰器(Decorator)模式时一个流程中可以加入不同的额外步骤
## 第5章 封装
通过```get()```封装,内部使用也通过``get()``
设计时要考虑可能产生的变化,并把可变的因素封装起来。
## 第6章 面向接口的设计
一个对象可调用方法的集合
一种协议,比如文件传输协议或者邮件传输协议
一种程序接口,比如web服务
**三大定律:**
接口的实现应当正确完成它的方法宣称的事情
接口的实现不得损害系统
实现不能正确完成它的职责,必须通知相关的调用者
避免过早采用继承体系
## 第7章 验收测试驱动开发
针对业务逻辑的测试可以通过多种方法来实现:
- 通过用户界面创建一个调用业务员规则的事务
- 开发一个用户界面,并通过这个界面直接调用业务规则
- 通过某种语言的单元测试框架来实现测试
- 通过自动化的测试用例直接与业务规则模块进行交互
# 第二部分 最关键的小舵板
## 第8章 避免过渡设计或设计不足
- 避免过渡设计或设计不足
- 把复杂度和返工最小化
- 永远不要把代码变得更糟(编码的希波拉底誓言)
- 仅在有目的的情况下降低代码质量
- 使代码容易修改,足够健壮,适应变化并安全可靠
## 第9章 持续集成
- 建立源代码分支
- 将主干内容合并回分支
- 测试驱动开发与合并的成本
- 持续集成
- 持续集成服务器
**小结:**
- 减少合并代码到主干的时间消耗
- 通过尽早地使团队成员所完成的工作被大家所知道来提高团队内部的沟通。这样做使大家有机会观察到刚刚完成的代码库改动并对其作出评价。
# 第三部分 设计问题
## 第10章 共性和可变性分析
> “分析矩阵”
方法:
1. 选择一个将要描述的特定用例
2. 列出完成这个用例所需要的步骤,把第一步放在最上面,后面的步骤依次排列
3. 在每个步骤的左边创建一列
4. 把每一个步骤的概念和意义卸载左边的列里
例子:

小结:
**把不同的实现封装起来**
## 第11章 以开放关闭原则为目标的重构
软件中的实体(类,模块,函数等)应当满足这样的要求:对开展使开发的,对修改是关闭的。
## 第12章 需求与功能接口
**迪米特法则(最少知识原则)**
例子:
~~~ java
public class City {
public String name();
public City twinCity();
public Street[] streets();
}
public class Street {
public String name();
public House[] houses();
}
public class House {
public int number();
public Color color();
}
~~~
我们想知道在Main Street 1374号房屋的颜色,则接下来我们很有可能这样写:
~~~ java
public Foo() {
Color c = Seattle.streets()["Main"].houses()[1374].color();
}
~~~
推荐做法:
~~~ java
public Foo() {
Color c = Seattle.ColorOfHouseInStreet("Main", 1374);
}
~~~
小结:
- 接口通常是指由哪些服务可以提供,它表明服务提供者的能力。
- 直接反应客户端需要的接口,就这是外观模式 或者对简单点的情况采用**适配器模式**。
## 第13章 何时以及如何使用继承
优先委托,策略模式
**一个类必须只能因为一个原因发生改动**。
# 第四部分 附录
## 附录A 统一建模语言概览
类图:
类之间的关系可能为以下几种类型:
- 当一个类是另一个类的”一种”(kind of)时:是”is-a”关系
- 当一个类与另一个类是写作关系时,
- 当一个类”包含”(contains)另一个类时:是”has-a”关系
- 当一个类”用到”(use)另一个类时:是”uses-a”关系
一个类”创建”(creates)另一个类
**聚合关系”has-a”**:

不管有没有包含Aircraft类,Airport类都被称为Airport。
**组合和使用的关系:**

car类如果没有Engine类就不是完整的。只要有汽车的地方,就必须包含发动机。
UML里的注释:

表明其他类所包含的信息:




豆瓣地址:[http://book.douban.com/subject/11614307/]()
PDF:[http://pan.baidu.com/s/1c0L0sUW]()
|
apache-2.0
|
OHDSI/Circe
|
js/modules/cohortdefinitionviewer/main.js
|
2914
|
define(function (require, exports) {
var ko = require('knockout')
var expressionViewer = require('./components/CohortExpressionViewer');
ko.components.register('cohort-expression-viewer', expressionViewer);
var criteriaGroup = require('./components/CriteriaGroup');
ko.components.register('criteria-group-viewer', criteriaGroup);
var conditionOccurrence = require('./components/ConditionOccurrence');
ko.components.register('condition-occurrence-criteria-viewer', conditionOccurrence);
var conditionEra = require('./components/ConditionEra');
ko.components.register('condition-era-criteria-viewer', conditionEra);
var drugExposure = require('./components/DrugExposure');
ko.components.register('drug-exposure-criteria-viewer', drugExposure);
var drugEra = require('./components/DrugEra');
ko.components.register('drug-era-criteria-viewer', drugEra);
var doseEra = require('./components/DoseEra');
ko.components.register('dose-era-criteria-viewer', doseEra);
var procedureOccurrence = require('./components/ProcedureOccurrence');
ko.components.register('procedure-occurrence-criteria-viewer', procedureOccurrence);
var observation = require('./components/Observation');
ko.components.register('observation-criteria-viewer', observation);
var visitOccurrence = require('./components/VisitOccurrence');
ko.components.register('visit-occurrence-criteria-viewer', visitOccurrence);
var deviceExposure = require('./components/DeviceExposure');
ko.components.register('device-exposure-criteria-viewer', deviceExposure);
var measurement = require('./components/Measurement');
ko.components.register('measurement-criteria-viewer', measurement);
var observationPeriod = require('./components/ObservationPeriod');
ko.components.register('observation-period-criteria-viewer', observationPeriod);
var specimen = require('./components/Specimen');
ko.components.register('specimen-criteria-viewer', specimen);
var death = require('./components/Death');
ko.components.register('death-criteria-viewer', death);
var numericRange = require('./components/NumericRange');
ko.components.register('numeric-range-viewer', numericRange);
var dateRange = require('./components/DateRange');
ko.components.register('date-range-viewer', dateRange);
var windowInput = require('./components/WindowInput');
ko.components.register('window-input-viewer',windowInput);
var textFilter = require('./components/TextFilter');
ko.components.register('text-filter-viewer',textFilter);
var conceptList = require('./components/ConceptList');
ko.components.register('concept-list-viewer',conceptList);
var conceptSetReference = require('./components/ConceptSetReference');
ko.components.register('conceptset-reference',conceptSetReference);
var conceptSetViewer = require('./components/ConceptSetViewer');
ko.components.register('conceptset-viewer',conceptSetViewer);
});
|
apache-2.0
|
zinic/jliocc
|
src/main/java/net/jps/lioc/context/ContextReferenceAliaser.java
|
860
|
/*
* Copyright 2010 John Hopper
*
* 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 net.jps.lioc.context;
/**
*
* @author zinic
*/
public interface ContextReferenceAliaser {
/**
* Creates a context sensitive reference alias for the registered element
*
* @param referenceAlias
*/
void as(String referenceAlias);
}
|
apache-2.0
|
Guitjerry/schoolApp
|
src/com/sushe/service/SchoolService.java
|
296
|
package com.sushe.service;
import com.sushe.entity.School;
import java.util.List;
/**
* Created by jiangbin on 15/4/23.
*/
public interface SchoolService {
/**
* 查询学校
* @return
*/
public List<School> selectAll();
public School selectByName(String name);
}
|
apache-2.0
|
wspeirs/sop4j-base
|
src/main/java/com/sop4j/base/google/common/util/concurrent/FutureCallback.java
|
1509
|
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sop4j.base.google.common.util.concurrent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Nullable;
/**
* A callback for accepting the results of a {@link java.util.concurrent.Future}
* computation asynchronously.
*
* <p>To attach to a {@link ListenableFuture} use {@link Futures#addCallback}.
*
* @author Anthony Zana
* @since 10.0
*/
public interface FutureCallback<V> {
/**
* Invoked with the result of the {@code Future} computation when it is
* successful.
*/
void onSuccess(@Nullable V result);
/**
* Invoked when a {@code Future} computation fails or is canceled.
*
* <p>If the future's {@link Future#get() get} method throws an {@link
* ExecutionException}, then the cause is passed to this method. Any other
* thrown object is passed unaltered.
*/
void onFailure(Throwable t);
}
|
apache-2.0
|
liosha2007/temporary-groupdocs-java-sdk
|
src/main/java/com/groupdocs/sdk/common/FileStream.java
|
2541
|
/**
* Copyright 2012 GroupDocs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.groupdocs.sdk.common;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.core.header.ContentDisposition;
public class FileStream {
private InputStream inputStream;
private String contentType;
private String fileName;
private long size = -1;
public FileStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public FileStream(String requestUri, ClientResponse response) {
this.inputStream = response.getEntityInputStream();
if(response.getType() != null){
this.contentType = response.getType().toString();
}
MultivaluedMap<String, String> headers = response.getHeaders();
try {
// http://www.ietf.org/rfc/rfc2183.txt
ContentDisposition cd = new ContentDisposition(headers.getFirst("Content-Disposition"));
fileName = cd.getFileName() == null ? getFileNameFromUrl(requestUri) : cd.getFileName();
size = cd.getSize() == 0 ? response.getLength() : cd.getSize();
} catch (ParseException e) {
}
}
private String getFileNameFromUrl(String requestUri) {
try {
URL url = new URL(requestUri);
String path = url.getPath();
return path.substring(path.lastIndexOf('/') + 1);
} catch (MalformedURLException e) {
return null;
}
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
apache-2.0
|
nischalsheth/contrail-controller
|
src/opserver/alarmgen_cfg.py
|
11029
|
#
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
import argparse, os, ConfigParser, sys, re
from pysandesh.sandesh_base import *
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns.constants import SERVICE_ALARM_GENERATOR, \
ServicesDefaultConfigurationFiles
class CfgParser(object):
def __init__(self, argv):
self._devices = []
self._args = None
self.__pat = None
self._argv = argv or ' '.join(sys.argv[1:])
def parse(self):
'''
command line example
contrail-alarm-gen --log_level SYS_DEBUG
--logging_level DEBUG
--log_category test
--log_file <stdout>
--use_syslog
--syslog_facility LOG_USER
--worker_id 0
--partitions 5
--redis_password
--http_server_port 5995
--redis_server_port 6379
--redis_uve_list 127.0.0.1:6379
--alarmgen_list 127.0.0.1:0
--kafka_broker_list 127.0.0.1:9092
--zk_list 127.0.0.1:2181
--rabbitmq_server_list 127.0.0.1:5672
--conf_file /etc/contrail/contrail-alarm-gen.conf
'''
# Source any specified config/ini file
# Turn off help, so we print all options in response to -h
conf_parser = argparse.ArgumentParser(add_help=False)
conf_parser.add_argument("-c", "--conf_file", action="append",
help="Specify config file", metavar="FILE",
default=ServicesDefaultConfigurationFiles.get(
SERVICE_ALARM_GENERATOR, None))
args, remaining_argv = conf_parser.parse_known_args(self._argv.split())
defaults = {
'host_ip' : '127.0.0.1',
'collectors' : [],
'kafka_broker_list' : ['127.0.0.1:9092'],
'log_local' : False,
'log_level' : SandeshLevel.SYS_DEBUG,
'log_category' : '',
'log_file' : Sandesh._DEFAULT_LOG_FILE,
'use_syslog' : False,
'syslog_facility' : Sandesh._DEFAULT_SYSLOG_FACILITY,
'http_server_port' : 5995,
'worker_id' : '0',
'partitions' : 15,
'zk_list' : None,
'alarmgen_list' : ['127.0.0.1:0'],
'cluster_id' :'',
}
defaults.update(SandeshConfig.get_default_options(['DEFAULTS']))
redis_opts = {
'redis_server_port' : 6379,
'redis_password' : None,
'redis_uve_list' : ['127.0.0.1:6379'],
}
configdb_opts = {
'rabbitmq_server_list': None,
'rabbitmq_port': 5672,
'rabbitmq_user': 'guest',
'rabbitmq_password': 'guest',
'rabbitmq_vhost': None,
'rabbitmq_ha_mode': False,
'rabbitmq_use_ssl': False,
'kombu_ssl_version': '',
'kombu_ssl_keyfile': '',
'kombu_ssl_certfile': '',
'kombu_ssl_ca_certs': '',
'config_db_server_list': None,
'config_db_username': None,
'config_db_password': None
}
sandesh_opts = SandeshConfig.get_default_options()
config = None
if args.conf_file:
config = ConfigParser.SafeConfigParser()
config.optionxform = str
config.read(args.conf_file)
if 'DEFAULTS' in config.sections():
defaults.update(dict(config.items('DEFAULTS')))
if 'REDIS' in config.sections():
redis_opts.update(dict(config.items('REDIS')))
if 'CONFIGDB' in config.sections():
configdb_opts.update(dict(config.items('CONFIGDB')))
SandeshConfig.update_options(sandesh_opts, config)
# Override with CLI options
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
# Don't mess with format of description
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
defaults.update(redis_opts)
defaults.update(configdb_opts)
defaults.update(sandesh_opts)
parser.set_defaults(**defaults)
parser.add_argument("--host_ip",
help="Host IP address")
parser.add_argument("--collectors",
help="List of Collector IP addresses in ip:port format",
nargs="+")
parser.add_argument(
"--log_file",
help="Filename for the logs to be written to")
parser.add_argument("--log_local", action="store_true",
help="Enable local logging of sandesh messages")
parser.add_argument(
"--log_category",
help="Category filter for local logging of sandesh messages")
parser.add_argument(
"--log_level",
help="Severity level for local logging of sandesh messages")
parser.add_argument("--use_syslog",
action="store_true",
help="Use syslog for logging")
parser.add_argument("--syslog_facility",
help="Syslog facility to receive log lines")
parser.add_argument("--http_server_port", type=int,
help="introspect server port")
parser.add_argument("--worker_id",
help="Worker Id")
parser.add_argument("--partitions", type=int,
help="Number of partitions for hashing UVE keys")
parser.add_argument("--redis_server_port",
type=int,
help="Redis server port")
parser.add_argument("--redis_password",
help="Redis server password")
parser.add_argument("--kafka_broker_list",
help="List of bootstrap kafka brokers in ip:port format",
nargs="+")
parser.add_argument("--zk_list",
help="List of zookeepers in ip:port format",
nargs="+")
parser.add_argument("--rabbitmq_server_list", type=str,
help="List of Rabbitmq server ip address separated by comma")
parser.add_argument("--rabbitmq_port",
help="Rabbitmq server port")
parser.add_argument("--rabbitmq_user",
help="Username for Rabbitmq")
parser.add_argument("--rabbitmq_password",
help="Password for Rabbitmq")
parser.add_argument("--rabbitmq_vhost",
help="vhost for Rabbitmq")
parser.add_argument("--rabbitmq_ha_mode",
action="store_true",
help="True if the rabbitmq cluster is mirroring all queue")
parser.add_argument("--config_db_server_list",
help="List of cassandra servers in ip:port format",
nargs='+')
parser.add_argument("--config_db_username",
help="Cassandra user name")
parser.add_argument("--config_db_password",
help="Cassandra password")
parser.add_argument("--redis_uve_list",
help="List of redis-uve in ip:port format. For internal use only",
nargs="+")
parser.add_argument("--alarmgen_list",
help="List of alarmgens in ip:inst format. For internal use only",
nargs="+")
parser.add_argument("--cluster_id",
help="Analytics Cluster Id")
SandeshConfig.add_parser_arguments(parser)
self._args = parser.parse_args(remaining_argv)
if type(self._args.collectors) is str:
self._args.collectors = self._args.collectors.split()
if type(self._args.kafka_broker_list) is str:
self._args.kafka_broker_list= self._args.kafka_broker_list.split()
if type(self._args.zk_list) is str:
self._args.zk_list= self._args.zk_list.split()
if type(self._args.redis_uve_list) is str:
self._args.redis_uve_list = self._args.redis_uve_list.split()
if type(self._args.alarmgen_list) is str:
self._args.alarmgen_list = self._args.alarmgen_list.split()
if type(self._args.config_db_server_list) is str:
self._args.config_db_server_list = \
self._args.config_db_server_list.split()
self._args.conf_file = args.conf_file
def _pat(self):
if self.__pat is None:
self.__pat = re.compile(', *| +')
return self.__pat
def _mklist(self, s):
return self._pat().split(s)
def redis_uve_list(self):
return self._args.redis_uve_list
def alarmgen_list(self):
return self._args.alarmgen_list
def collectors(self):
return self._args.collectors
def kafka_broker_list(self):
return self._args.kafka_broker_list
def zk_list(self):
return self._args.zk_list;
def log_local(self):
return self._args.log_local
def log_category(self):
return self._args.log_category
def log_level(self):
return self._args.log_level
def log_file(self):
return self._args.log_file
def use_syslog(self):
return self._args.use_syslog
def syslog_facility(self):
return self._args.syslog_facility
def http_port(self):
return self._args.http_server_port
def worker_id(self):
return self._args.worker_id
def partitions(self):
return self._args.partitions
def redis_password(self):
return self._args.redis_password
def redis_server_port(self):
return self._args.redis_server_port
def host_ip(self):
return self._args.host_ip
def kafka_prefix(self):
return self._args.cluster_id
def rabbitmq_params(self):
return {'servers': self._args.rabbitmq_server_list,
'port': self._args.rabbitmq_port,
'user': self._args.rabbitmq_user,
'password': self._args.rabbitmq_password,
'vhost': self._args.rabbitmq_vhost,
'ha_mode': self._args.rabbitmq_ha_mode,
'use_ssl': self._args.rabbitmq_use_ssl,
'ssl_version': self._args.kombu_ssl_version,
'ssl_keyfile': self._args.kombu_ssl_keyfile,
'ssl_certfile': self._args.kombu_ssl_certfile,
'ssl_ca_certs': self._args.kombu_ssl_ca_certs}
def cassandra_params(self):
return {'servers': self._args.config_db_server_list,
'user': self._args.config_db_username,
'password': self._args.config_db_password,
'cluster_id': self._args.cluster_id}
# end cassandra_params
def sandesh_config(self):
return SandeshConfig.from_parser_arguments(self._args)
|
apache-2.0
|
carnegiespeech/translations
|
az/book.php
|
4904
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'book', language 'az', branch 'MOODLE_22_STABLE'
*
* @package book
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['addafter'] = 'Yeni fəsil əlavə edin';
$string['book:edit'] = 'Kitabın fəsillərini redaktə edin';
$string['book:read'] = 'Kitabı oxuyun';
$string['book:viewhiddenchapters'] = 'Kitabın gizli fəsillərinə baxış keçirilsin';
$string['chapterscount'] = 'Fəsillərin sayı';
$string['chaptertitle'] = 'Fəsillərin adı';
$string['confchapterdelete'] = 'Siz bu fəsili pozmağa əminsiniz?';
$string['confchapterdeleteall'] = 'Siz bu fəsili və onun məzmununu silməkdə əminsiniz?';
$string['content'] = 'Məzmun';
$string['customtitles'] = 'Qeyri-standart başlıqlar';
$string['customtitles_help'] = 'Fəsillərin qeyd olunmuş adları yalnız başlıqlarda göstərilmişdir';
$string['editingchapter'] = 'Fəslin redaktəsi';
$string['errorchapter'] = 'Kitabın fəsiləsinin oxunması zamanı səhv baş vermişdir.';
$string['faq'] = 'FAQ kitabçası (tez-tez verilən suallar)';
$string['faq_help'] = '* Nə üçün yalnız iki səviyyə? *
Adətən iki səviyyə bütün kitablar üçün kifayətdir. Üç səviyyə sənədin strukturunun korlanmasına səbəb ola bilər. Kitab modulu kiçik həcmli çoxsəhifəli tədris vəsaitinin yaradılması üçün nəzərdə tutulmuşdur. Daha böyük həcmli sənədlər üçün PDF formatından istifadə etmək məsləhət görülür. PDF fayllarının yaradılmasının ən asan yolu virtual printerlərdən istifadə etməkdir (bax. <a href="http://sector7g.wurzel6.de/pdfcreator/index_en.htm" target="_blank">PDFCreator</a>, <a href="http://fineprint.com/products/pdffactory/index.html" target="_blank">PDFFactory</a>, <a href="http://www.adobe.com/products/acrobatstd/main.html" target="_blank">Adobe Acrobat</a>, və s.).
* Tələbə kitabı redaktə edə bilərmi? *
Kitabları yalnız müəllimlər yarada və redaktə edə bilər. Hələ ki, tələbələrə bu imkanı vermək planlaşdırılmayıb. Bunun əsas səbəbi Kitab modulunun mümkün dərəcədə sadə saxlanılmasıdır.
* Mən kitab daxilində axtarış edə bilərəmmi? *
Hal-hazırda yalnız bir üsul mövcuddur - "çap üçün" səhifəsindən, brauzerin imkanlarından istifadə edərək axtarış aparmaq olar. Qobal axtarış hələ ki, yalnız Moodle sisteminin forumlarında mümkündür. Kitab modulu da daxil olmaqla bütün resurslarda axtarış aparmaq imkanı da olsaydı pis olmazdı. Könnüllü vardırmı?
* Fəsilin adı bir Başlıq sətirinə yerləşmir *
Adı qısaltmağa çalışın və ya administratordan Başlıq sətirini genişləndirməyi xahiş edin.O yalnız modul konfiqurasiyası səhifəsindəki bütün kitablar üçün qlobal olaraq təyin olunur.';
$string['modulename'] = 'Kitab';
$string['modulename_help'] = 'Kitab sadə çoxsəhifəli tədris vəsaitidir.';
$string['modulenameplural'] = 'Kitablar';
$string['navexit'] = 'Kitabdan çıxış';
$string['navnext'] = 'Nəvbəti';
$string['navprev'] = 'Əvvəlki';
$string['numbering'] = 'Fəsillərin nömrələnməsi';
$string['numbering0'] = 'Yoxdur';
$string['numbering1'] = 'Nömrələr';
$string['numbering2'] = 'Markerlər';
$string['numbering3'] = 'Boşluq';
$string['numbering_help'] = '*Yoxdur - fəsillər və altbölmələrə nömrələmə və formatlama şamil olunmur. Sizin fəsilələrinizin adlarında artıq nömrələnmə vardırsa bu üsuldan istifadə edin. Məsələn, "1. Birinci fəsil", "1.a Birinci mövzu", ... .
*Nömrələr - fəsillər və altböllmələr rəqəmlərlə nömrələnir (1, 1.1, 2, 2,...).
*Boşluq - altbölmələr boşluqlarla əks olunur.';
$string['numberingoptions'] = 'Mümkün nömrələmə parametrləri';
$string['numberingoptions_help'] = 'Yeni kitablar yaradılarkən əlyetərli olmalı nömrələmə parametrlərini seçin.';
$string['pluginadministration'] = 'Kitab administrasiyası';
$string['pluginname'] = 'Kitab';
$string['subchapter'] = 'Altfəsilələr';
$string['toc'] = 'Mündəricat';
$string['top'] = 'yuxar';
|
apache-2.0
|
lihongzheshuai/shurnim-storage
|
src/main/java/com/coderli/shurnim/storage/plugin/PluginResource.java
|
648
|
package com.coderli.shurnim.storage.plugin;
import java.io.File;
/**
* 插件资源<br>
* 定义了插件的描述信息以及对应的处理器信息(例如: 文件解析器。{@code PluginParser})
*
* @author OneCoder
* @date 2014年4月20日 下午8:53:17
* @website http://www.coderli.com
*/
public interface PluginResource {
/**
* 获取对应的配置文件解析器
*
* @return
* @author OneCoder
* @date 2014年4月20日 下午8:56:32
*/
FileParser getFileParser();
/**
* 获取实际的文件资源
*
* @return
* @author OneCoder
* @date 2014年4月20日 下午8:58:37
*/
File getConfigFile();
}
|
apache-2.0
|
fnproject/fn
|
api/datastore/sql/migrations/migs.go
|
256
|
package migrations
import (
"github.com/fnproject/fn/api/datastore/sql/migratex"
)
// Migrations is the list of fn specific sql migrations to run
var Migrations []migratex.Migration
func vfunc(v int64) func() int64 { return func() int64 { return v } }
|
apache-2.0
|
renyh1013/dp2
|
dp2LibraryXE/LibraryHost.cs
|
17502
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
// using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using Microsoft.Win32;
using dp2Library;
using DigitalPlatform;
using DigitalPlatform.IO;
using DigitalPlatform.Text;
namespace dp2LibraryXE
{
public class LibraryHost : HostBase
{
public static string default_miniserver_urls = "http://localhost:8001/dp2library/xe;net.pipe://localhost/dp2library/xe;rest.http://localhost/dp2library/xe/rest";
public static string default_single_url = "net.pipe://localhost/dp2library/xe";
// ServiceHost _host = null;
List<ServiceHost> m_hosts = new List<ServiceHost>();
public string HostUrl = default_single_url; // "net.pipe://localhost/dp2library/xe";
public override void ThreadMethod()
{
string strError = "";
_running = true;
int nRet = Start(this.DataDir, out strError);
if (nRet == -1)
{
this.ErrorInfo = strError;
// this._host = null;
this.m_hosts.Clear();
}
this._eventStarted.Set();
while (_running)
{
Thread.Sleep(100);
}
this.CloseHosts();
this._thread = null;
this._eventClosed.Set();
}
#if NO
void CloseHosts()
{
if (this._host != null)
{
HostInfo info = _host.Extensions.Find<HostInfo>();
if (info != null)
{
info.Dispose();
_host.Extensions.Remove(info);
}
_host.Close();
_host = null;
}
}
#endif
public override void CloseHosts()
{
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
host.Extensions.Remove(info);
info.Dispose();
}
host.Close();
}
this.m_hosts.Clear();
}
int Start(string strDataDir,
out string strError)
{
strError = "";
CloseHosts();
List<string> urls = StringUtil.SplitList(this.HostUrl, ';');
ServiceHost host = new ServiceHost(typeof(LibraryService));
this.m_hosts.Add(host);
HostInfo info = new HostInfo();
info.DataDir = strDataDir;
host.Extensions.Add(info);
bool bHasWsHttp = false;
int i = 0;
foreach (string strTempUrl in urls)
{
string strUrl = strTempUrl.Trim();
if (string.IsNullOrEmpty(strUrl) == true)
continue;
///
// 绑定协议
Uri uri = null;
try
{
uri = new Uri(strUrl);
}
catch (Exception ex)
{
strError = "dp2Library OnStart() 警告:发现不正确的协议URL '" + strUrl + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。";
return -1;
}
if (uri.Scheme.ToLower() == "net.pipe")
{
host.AddServiceEndpoint(typeof(ILibraryService),
CreateNamedpipeBinding0(),
strUrl);
}
else if (uri.Scheme.ToLower() == "net.tcp")
{
host.AddServiceEndpoint(typeof(ILibraryService),
CreateNetTcpBinding0(),
strUrl);
}
else if (uri.Scheme.ToLower() == "http")
{
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryService),
CreateWsHttpBinding1(),
strUrl);
bHasWsHttp = true;
}
else if (uri.Scheme.ToLower() == "rest.http")
{
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ILibraryServiceREST),
CreateWebHttpBinding1(),
strUrl.Substring(5)); // rest. 这几个字符要去掉
if (endpoint.Behaviors.Find<WebHttpBehavior>() == null)
{
WebHttpBehavior behavior = new WebHttpBehavior();
behavior.DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped;
behavior.DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json;
behavior.AutomaticFormatSelectionEnabled = true;
behavior.HelpEnabled = true;
endpoint.Behaviors.Add(behavior);
}
}
else
{
// 警告不能支持的协议
strError = "dp2Library OnStart() 警告:发现不能支持的协议类型 '" + strUrl + "'";
return -1;
}
info.Protocol = uri.Scheme.ToLower();
// 只有第一个host才有metadata能力
if (// i == 0 //
uri.Scheme.ToLower() == "http"
&& host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
string strMetadataUrl = strUrl; // "http://localhost:8001/dp2library/xe/";
if (strMetadataUrl[strMetadataUrl.Length - 1] != '/')
strMetadataUrl += "/";
strMetadataUrl += "metadata";
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri(strMetadataUrl);
host.Description.Behaviors.Add(behavior);
this.MetadataUrl = strMetadataUrl;
}
i++;
}
// 如果具有ws1/ws2 binding,才启用证书
if (bHasWsHttp == true)
{
try
{
string strCertSN = "";
X509Certificate2 cert = GetCertificate(strCertSN,
out strError);
if (cert == null)
{
strError = "dp2Library OnStart() 准备证书 时发生错误: " + strError;
return -1;
}
else
host.Credentials.ServiceCertificate.Certificate = cert;
}
catch (Exception ex)
{
strError = "dp2Library OnStart() 获取证书时发生错误: " + ExceptionUtil.GetExceptionMessage(ex);
return -1;
}
}
if (host.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null)
{
ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior();
behavior.MaxConcurrentCalls = 50;
behavior.MaxConcurrentInstances = 1000;
behavior.MaxConcurrentSessions = 1000;
host.Description.Behaviors.Add(behavior);
}
// IncludeExceptionDetailInFaults
ServiceDebugBehavior debug_behavior = host.Description.Behaviors.Find<ServiceDebugBehavior>();
if (debug_behavior == null)
{
host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
}
else
{
if (debug_behavior.IncludeExceptionDetailInFaults == false)
debug_behavior.IncludeExceptionDetailInFaults = true;
}
host.Opening += new EventHandler(host_Opening);
host.Closing += new EventHandler(m_host_Closing);
try
{
host.Open();
}
catch (Exception ex)
{
string strInstanceName = "";
strError = "dp2Library OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ExceptionUtil.GetExceptionMessage(ex);
return -1;
}
#if NO
strError = "test error";
return -1;
#endif
return 0;
}
void host_Opening(object sender, EventArgs e)
{
}
void m_host_Closing(object sender, EventArgs e)
{
#if NO
if (this._host != null)
{
HostInfo info = _host.Extensions.Find<HostInfo>();
if (info != null)
{
info.Dispose();
_host.Extensions.Remove(info);
}
}
#endif
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
info.Dispose();
host.Extensions.Remove(info);
}
}
}
public void SetTestMode(bool bTestMode)
{
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
info.TestMode = bTestMode;
if (info.App != null)
info.App.TestMode = bTestMode;
}
}
}
public void SetMaxClients(int nMaxClients)
{
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
info.MaxClients = nMaxClients;
if (info.App != null)
info.App.MaxClients = nMaxClients;
}
}
}
public void SetLicenseType(string strLicenseType)
{
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
info.LicenseType = strLicenseType;
if (info.App != null)
info.App.LicenseType = strLicenseType;
}
}
}
public void SetFunction(string strFunction)
{
foreach (ServiceHost host in this.m_hosts)
{
HostInfo info = host.Extensions.Find<HostInfo>();
if (info != null)
{
info.Function = strFunction;
if (info.App != null)
info.App.Function = strFunction;
}
}
}
static void SetTimeout(System.ServiceModel.Channels.Binding binding)
{
binding.SendTimeout = new TimeSpan(0, 20, 0);
binding.ReceiveTimeout = new TimeSpan(0, 20, 0); // 决定Session存活
binding.CloseTimeout = new TimeSpan(0, 20, 0);
binding.OpenTimeout = new TimeSpan(0, 20, 0);
}
// np0: namedpipe
System.ServiceModel.Channels.Binding CreateNamedpipeBinding0()
{
NetNamedPipeBinding binding = new NetNamedPipeBinding();
binding.Namespace = "http://dp2003.com/dp2library/";
binding.Security.Mode = NetNamedPipeSecurityMode.None;
binding.MaxReceivedMessageSize = 1024 * 1024;
// binding.MessageEncoding = WSMessageEncoding.Mtom;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
quotas.MaxArrayLength = 1024 * 1024;
quotas.MaxStringContentLength = 1024 * 1024;
binding.ReaderQuotas = quotas;
SetTimeout(binding);
// binding.ReliableSession.Enabled = false;
return binding;
}
// nt0: net.tcp
System.ServiceModel.Channels.Binding CreateNetTcpBinding0()
{
NetTcpBinding binding = new NetTcpBinding();
binding.Namespace = "http://dp2003.com/dp2library/";
binding.Security.Mode = SecurityMode.None;
binding.MaxReceivedMessageSize = 1024 * 1024;
// binding.MessageEncoding = WSMessageEncoding.Mtom;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
quotas.MaxArrayLength = 1024 * 1024;
quotas.MaxStringContentLength = 1024 * 1024;
binding.ReaderQuotas = quotas;
SetTimeout(binding);
binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 20, 0);
// binding.ReliableSession.Enabled = false;
return binding;
}
// ws1: anonymouse -- ClientCredentitialType = None
System.ServiceModel.Channels.Binding CreateWsHttpBinding1()
{
WSHttpBinding binding = new WSHttpBinding();
binding.Namespace = "http://dp2003.com/dp2library/";
binding.Security.Mode = SecurityMode.Message;
#if !USERNAME
binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
#else
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
#endif
binding.MaxReceivedMessageSize = 1024 * 1024;
binding.MessageEncoding = WSMessageEncoding.Mtom;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
quotas.MaxArrayLength = 1024 * 1024;
quotas.MaxStringContentLength = 1024 * 1024;
binding.ReaderQuotas = quotas;
SetTimeout(binding);
binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 20, 0);
// binding.ReliableSession.Enabled = false;
binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 20, 0);
return binding;
}
System.ServiceModel.Channels.Binding CreateWebHttpBinding1()
{
WebHttpBinding binding = new WebHttpBinding();
binding.Namespace = "http://dp2003.com/dp2library/";
binding.Security.Mode = WebHttpSecurityMode.None;
// binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
binding.MaxReceivedMessageSize = 1024 * 1024;
// binding.MessageEncoding = WSMessageEncoding.Mtom;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
quotas.MaxArrayLength = 1024 * 1024;
quotas.MaxStringContentLength = 1024 * 1024;
binding.ReaderQuotas = quotas;
SetTimeout(binding);
// binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 20, 0);
// binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 20, 0);
return binding;
}
static X509Certificate2 FindCertificate(
StoreLocation location, StoreName name,
X509FindType findType, string findValue)
{
X509Store store = new X509Store(name, location);
try
{
// create and open store for read-only access
store.Open(OpenFlags.ReadOnly);
// search store
X509Certificate2Collection col = store.Certificates.Find(
findType, findValue, false);
if (col.Count == 0)
return null;
// return first certificate found
return col[0];
}
// always close the store
finally { store.Close(); }
}
X509Certificate2 GetCertificate(
string strCertSN,
out string strError)
{
strError = "";
/*
string strCertSN = GetProductString(
"dp2Library",
"cert_sn");
* */
if (string.IsNullOrEmpty(strCertSN) == false)
{
X509Certificate2 cert = FindCertificate(
StoreLocation.LocalMachine,
StoreName.Root,
X509FindType.FindBySerialNumber,
strCertSN);
if (cert == null)
{
strError = "序列号为 '" + strCertSN + "' 的证书在 StoreLocation.LocalMachine | StoreLocation.CurrentUser / StoreName.Root 中不存在。";
return null;
}
return cert;
}
// 缺省的SubjectName为DigitalPlatform的证书
string strCurrentDir = System.Reflection.Assembly.GetExecutingAssembly().Location; // Environment.CurrentDirectory;
strCurrentDir = PathUtil.PathPart(strCurrentDir);
string strCerFilename = PathUtil.MergePath(strCurrentDir, "digitalplatform.pfx");
return new X509Certificate2(strCerFilename, "setupdp2");
}
}
}
|
apache-2.0
|
NLeSC/Xenon
|
src/main/java/nl/esciencecenter/xenon/filesystems/FileSystem.java
|
63280
|
/*
* Copyright 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
*
* 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 nl.esciencecenter.xenon.filesystems;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import nl.esciencecenter.xenon.InvalidCredentialException;
import nl.esciencecenter.xenon.InvalidLocationException;
import nl.esciencecenter.xenon.InvalidPropertyException;
import nl.esciencecenter.xenon.UnknownAdaptorException;
import nl.esciencecenter.xenon.UnknownPropertyException;
import nl.esciencecenter.xenon.UnsupportedOperationException;
import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.adaptors.AdaptorLoader;
import nl.esciencecenter.xenon.adaptors.NotConnectedException;
import nl.esciencecenter.xenon.adaptors.XenonProperties;
import nl.esciencecenter.xenon.adaptors.filesystems.FileAdaptor;
import nl.esciencecenter.xenon.credentials.Credential;
import nl.esciencecenter.xenon.credentials.DefaultCredential;
import nl.esciencecenter.xenon.utils.DaemonThreadFactory;
/**
* FileSystem represent a (possibly remote) file system that can be used to access data.
*/
public abstract class FileSystem implements AutoCloseable {
private static FileAdaptor getAdaptorByName(String adaptorName) throws UnknownAdaptorException {
return AdaptorLoader.getFileAdaptor(adaptorName);
}
/**
* Gives a list names of the available adaptors.
*
* @return the list
*/
public static String[] getAdaptorNames() {
return AdaptorLoader.getFileAdaptorNames();
}
/**
* Gives the description of the adaptor with the given name.
*
* @param adaptorName
* the type of file system to connect to (e.g. "sftp" or "webdav")
* @return the description
* @throws UnknownAdaptorException
* If the adaptor name is absent in {@link #getAdaptorNames()}.
*/
public static FileSystemAdaptorDescription getAdaptorDescription(String adaptorName) throws UnknownAdaptorException {
return getAdaptorByName(adaptorName);
}
/**
* Gives a list of the descriptions of the available adaptors.
*
* @return the list
*/
public static FileSystemAdaptorDescription[] getAdaptorDescriptions() {
return AdaptorLoader.getFileAdaptorDescriptions();
}
/**
* CopyStatus contains status information for a specific copy operation.
*/
static class CopyStatusImplementation implements CopyStatus {
private final String copyIdentifier;
private final String state;
private final XenonException exception;
private final long bytesToCopy;
private final long bytesCopied;
public CopyStatusImplementation(String copyIdentifier, String state, long bytesToCopy, long bytesCopied, XenonException exception) {
super();
this.copyIdentifier = copyIdentifier;
this.state = state;
this.bytesToCopy = bytesToCopy;
this.bytesCopied = bytesCopied;
this.exception = exception;
}
@Override
public String getCopyIdentifier() {
return copyIdentifier;
}
@Override
public String getState() {
return state;
}
@Override
public XenonException getException() {
return exception;
}
@Override
public void maybeThrowException() throws XenonException {
if (hasException()) {
throw getException();
}
}
@Override
public boolean isRunning() {
return "RUNNING".equals(state);
}
@Override
public boolean isDone() {
return "DONE".equals(state) || "FAILED".equals(state);
}
@Override
public boolean hasException() {
return exception != null;
}
@Override
public long bytesToCopy() {
return bytesToCopy;
}
@Override
public long bytesCopied() {
return bytesCopied;
}
@Override
public String toString() {
return "CopyStatus [copyIdentifier=" + copyIdentifier + ", state=" + state + ", exception=" + exception + ", bytesToCopy=" + bytesToCopy
+ ", bytesCopied=" + bytesCopied + "]";
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CopyStatusImplementation that = (CopyStatusImplementation) o;
return bytesToCopy == that.bytesToCopy && bytesCopied == that.bytesCopied && Objects.equals(copyIdentifier, that.copyIdentifier)
&& Objects.equals(state, that.state) && Objects.equals(exception, that.exception);
}
@Override
public int hashCode() {
return Objects.hash(copyIdentifier, state, exception, bytesToCopy, bytesCopied);
}
}
/**
* Create a new FileSystem using the <code>adaptor</code> that connects to a data store at <code>location</code> using the <code>credentials</code> to get
* access. Use <code>properties</code> to (optionally) configure the FileSystem when it is created.
*
* Make sure to always close {@code FileSystem} instances by calling {@code close(FileSystem)} when you no longer need them, otherwise their associated
* resources remain allocated.
*
* @see <a href="../../../../overview-summary.html#filesystems">Documentation on the supported adaptors and locations.</a>
*
* @param adaptor
* the type of file system to connect to (e.g. "sftp" or "webdav")
* @param location
* the location of the FileSystem.
* @param credential
* the Credentials to use to get access to the FileSystem.
* @param properties
* optional properties to use when creating the FileSystem.
*
* @return the new FileSystem.
*
* @throws UnknownPropertyException
* If a unknown property was provided.
* @throws InvalidPropertyException
* If a known property was provided with an invalid value.
* @throws UnknownAdaptorException
* If the adaptor was invalid.
* @throws InvalidLocationException
* If the location was invalid.
* @throws InvalidCredentialException
* If the credential is invalid to access the location.
*
* @throws XenonException
* If the creation of the FileSystem failed.
* @throws IllegalArgumentException
* If adaptor is null.
*/
public static FileSystem create(String adaptor, String location, Credential credential, Map<String, String> properties) throws XenonException {
return getAdaptorByName(adaptor).createFileSystem(location, credential, properties);
}
/**
* Create a new FileSystem using the <code>adaptor</code> that connects to a data store at <code>location</code> using the <code>credentials</code> to get
* access.
*
* Make sure to always close {@code FileSystem} instances by calling {@code close(FileSystem)} when you no longer need them, otherwise their associated
* resources remain allocated.
*
* @see <a href="../../../../overview-summary.html#filesystems">Documentation on the supported adaptors and locations.</a>
*
* @param adaptor
* the type of file system to connect to (e.g. "sftp" or "webdav")
* @param location
* the location of the FileSystem.
* @param credential
* the Credentials to use to get access to the FileSystem.
*
* @return the new FileSystem.
*
* @throws UnknownPropertyException
* If a unknown property was provided.
* @throws InvalidPropertyException
* If a known property was provided with an invalid value.
* @throws UnknownAdaptorException
* If the adaptor was invalid.
* @throws InvalidLocationException
* If the location was invalid.
* @throws InvalidCredentialException
* If the credential is invalid to access the location.
* @throws XenonException
* If the creation of the FileSystem failed.
* @throws IllegalArgumentException
* If adaptor is null.
*/
public static FileSystem create(String adaptor, String location, Credential credential) throws XenonException {
return create(adaptor, location, credential, new HashMap<>(0));
}
/**
* Create a new FileSystem using the <code>adaptor</code> that connects to a data store at <code>location</code> using the default credentials to get
* access.
*
* Make sure to always close {@code FileSystem} instances by calling {@code close(FileSystem)} when you no longer need them, otherwise their associated
* resources remain allocated.
*
* @see <a href="../../../../overview-summary.html#filesystems">Documentation on the supported adaptors and locations.</a>
*
* @param adaptor
* the type of file system to connect to (e.g. "sftp" or "webdav")
* @param location
* the location of the FileSystem.
*
* @return the new FileSystem.
*
* @throws UnknownPropertyException
* If a unknown property was provided.
* @throws InvalidPropertyException
* If a known property was provided with an invalid value.
* @throws UnknownAdaptorException
* If the adaptor was invalid.
* @throws InvalidLocationException
* If the location was invalid.
* @throws InvalidCredentialException
* If the credential is invalid to access the location.
*
* @throws XenonException
* If the creation of the FileSystem failed.
* @throws IllegalArgumentException
* If adaptor is null.
*/
public static FileSystem create(String adaptor, String location) throws XenonException {
return create(adaptor, location, new DefaultCredential());
}
/**
* Create a new FileSystem using the <code>adaptor</code> that connects to a data store at the default location using the default credentials to get access.
*
* Note that there are very few filesystem adaptors that support a default location. The local filesystem adaptor is the prime example.
*
* Make sure to always close {@code FileSystem} instances by calling {@code close(FileSystem)} when you no longer need them, otherwise their associated
* resources remain allocated.
*
* @see <a href="overview-summary.html#filesystems">Documentation on the supported adaptors and locations.</a>
*
* @param adaptor
* the type of file system to connect to (e.g. "sftp" or "webdav")
*
* @return the new FileSystem.
*
* @throws UnknownPropertyException
* If a unknown property was provided.
* @throws InvalidPropertyException
* If a known property was provided with an invalid value.
* @throws UnknownAdaptorException
* If the adaptor was invalid.
* @throws InvalidLocationException
* If the location was invalid.
* @throws InvalidCredentialException
* If the credential is invalid to access the location.
*
* @throws XenonException
* If the creation of the FileSystem failed.
* @throws IllegalArgumentException
* If adaptor is null.
*/
public static FileSystem create(String adaptor) throws XenonException {
return create(adaptor, null);
}
class CopyCallback {
private long bytesToCopy = 0;
private long bytesCopied = 0;
private boolean started = false;
private boolean cancelled = false;
synchronized void start(long bytesToCopy) {
if (!started) {
started = true;
this.bytesToCopy = bytesToCopy;
}
}
synchronized boolean isStarted() {
return started;
}
synchronized long getBytesCopied() {
return bytesCopied;
}
synchronized long getBytesToCopy() {
return bytesToCopy;
}
synchronized void addBytesCopied(long bytes) {
this.bytesCopied += bytes;
}
synchronized void cancel() {
cancelled = true;
}
synchronized boolean isCancelled() {
return cancelled;
}
}
private class PendingCopy {
Future<Void> future;
CopyCallback callback;
public PendingCopy(Future<Void> future, CopyCallback callback) {
super();
this.future = future;
this.callback = callback;
}
}
private final String uniqueID;
private final String adaptor;
private final String location;
private final Credential credential;
private final XenonProperties properties;
private final ExecutorService pool;
private Path workingDirectory;
private long nextCopyID = 0;
private int bufferSize;
private final HashMap<String, PendingCopy> pendingCopies = new HashMap<>();
protected FileSystem(String uniqueID, String adaptor, String location, Credential credential, Path workDirectory, int bufferSize,
XenonProperties properties) {
if (uniqueID == null) {
throw new IllegalArgumentException("Identifier may not be null!");
}
if (adaptor == null) {
throw new IllegalArgumentException("Adaptor may not be null!");
}
if (location == null) {
throw new IllegalArgumentException("Location may not be null!");
}
if (credential == null) {
throw new IllegalArgumentException("Credential may not be null!");
}
if (workDirectory == null) {
throw new IllegalArgumentException("EntryPath may not be null!");
}
if (bufferSize <= 0) {
throw new IllegalArgumentException("Buffer size may not be 0 or smaller!");
}
this.uniqueID = uniqueID;
this.adaptor = adaptor;
this.location = location;
this.credential = credential;
this.workingDirectory = workDirectory;
this.properties = properties;
this.bufferSize = bufferSize;
this.pool = Executors.newFixedThreadPool(1, new DaemonThreadFactory("CopyThread." + uniqueID));
}
protected int getBufferSize() {
return bufferSize;
}
private synchronized String getNextCopyID() {
return "COPY-" + getAdaptorName() + "-" + nextCopyID++;
}
/**
* Get the name of the adaptor that created this FileSystem.
*
* @return the name of the adaptor.
*/
public String getAdaptorName() {
return adaptor;
}
/**
* Get the location of the FileSystem.
*
* @return the location of the FileSystem.
*/
public String getLocation() {
return location;
}
/**
* Get the credential that this FileSystem is using.
*
* @return the credential this FileSystem is using.
*/
public Credential getCredential() {
return credential;
}
/**
* Get the properties used to create this FileSystem.
*
* @return the properties used to create this FileSystem.
*/
public Map<String, String> getProperties() {
return properties.toMap();
}
/**
* Get the current working directory of this file system.
*
* All relative paths provided to FileSystem methods are resolved against this current working directory.
*
* The current working directory is set when a FileSystem is created using the path specified in the location. If no path is specified in the location, an
* adaptor specific default path is used, for example <code>"/home/username"</code>.
*
* @return the current working directory of this file system.
*/
public Path getWorkingDirectory() {
return workingDirectory;
}
/**
* Get the path separator used by this file system.
*
* The path separator is set when a FileSystem is created.
*
* @return the path separator used by this file system.
*/
public String getPathSeparator() {
return "" + workingDirectory.getSeparator();
}
/**
* Set the current working directory of this file system to <code>directory</code>.
*
* The provided <code>directory</code> must exist and be a directory. Both an absolute or relative path may be provided. In the latter case, the path will
* be resolved against the current working directory.
*
* @param directory
* a path to which the current working directory must be set.
* @throws NoSuchPathException
* if the <code>directory</code> does not exist
* @throws InvalidPathException
* if <code>directory</code> is not a directory
* @throws NotConnectedException
* if file system is closed.
* @throws IllegalArgumentException
* if the argument is null.
* @throws XenonException
* if an I/O error occurred
*/
public void setWorkingDirectory(Path directory) throws XenonException {
Path wd = toAbsolutePath(directory);
assertDirectoryExists(wd);
workingDirectory = wd;
}
/**
* Close this FileSystem. If the adaptor does not support closing this is a no-op.
*
* @throws XenonException
* If the FileSystem failed to close or if an I/O error occurred.
*/
public void close() throws XenonException {
try {
pool.shutdownNow();
} catch (Exception e) {
throw new XenonException(getAdaptorName(), "Failed to cleanly shutdown copy thread pool");
}
}
/**
* Return if the connection to the FileSystem is open. An adaptor which does not support closing is always open.
*
* @throws XenonException
* if the test failed or an I/O error occurred.
* @return if the connection to the FileSystem is open.
*/
public abstract boolean isOpen() throws XenonException;
/**
* Rename an existing source path to a non-existing target path (optional operation).
* <p>
*
* This method only implements a <em>rename</em> operation, not a <em>move</em> operation. Hence, this method will not copy files and should return (almost)
* instantaneously.
*
* The parent of the target path (e.g. <code>target.getParent</code>) must exist.
*
* If the target is equal to the source this method has no effect.
*
* If the source is a link, the link itself will be renamed, not the path to which it refers.
*
* If the source is a directory, it will be renamed to the target. This implies that a moving a directory between physical locations may fail.
* </p>
*
* @param source
* the existing source path.
* @param target
* the non existing target path.
*
* @throws UnsupportedOperationException
* If the adapter does not support renaming.
* @throws NoSuchPathException
* If the source file does not exist or the target parent directory does not exist.
* @throws PathAlreadyExistsException
* If the target file already exists.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* If the move failed.
* @throws IllegalArgumentException
* If one or both of the arguments are null.
*/
public abstract void rename(Path source, Path target) throws XenonException;
/**
* Creates a new directory, failing if the directory already exists. All nonexistent parent directories are also created.
*
* @param dir
* the directory to create.
*
* @throws PathAlreadyExistsException
* If the directory already exists or if a parent directory could not be created because a file with the same name already exists.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* If an I/O error occurred.
* @throws IllegalArgumentException
* If one or both of the arguments are null.
*/
public void createDirectories(Path dir) throws XenonException {
Path absolute = toAbsolutePath(dir);
Path parent = absolute.getParent();
if (parent != null && !exists(parent)) {
// Recursive call
createDirectories(parent);
}
createDirectory(absolute);
}
/**
* Creates a new directory, failing if the directory already exists.
*
* The parent directory of the file must already exists.
*
* @param dir
* the directory to create.
*
* @throws PathAlreadyExistsException
* If the directory already exists.
* @throws NoSuchPathException
* If the parent directory does not exist.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* If an I/O error occurred.
* @throws IllegalArgumentException
* If the argument is null.
*
*/
public abstract void createDirectory(Path dir) throws XenonException;
/**
* Creates a new empty file, failing if the file already exists.
*
* The parent directory of the file must already exists.
*
* @param file
* a path referring to the file to create.
*
* @throws PathAlreadyExistsException
* If the file already exists.
* @throws NoSuchPathException
* If the parent directory does not exist.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* If an I/O error occurred.
* @throws IllegalArgumentException
* If one or both of the arguments are null.
*/
public abstract void createFile(Path file) throws XenonException;
/**
* Creates a new symbolic link, failing if the link already exists (optional operation).
*
* The target is taken as is. It may be absolute, relative path and/or non-normalized path and may or may not exist.
*
* @param link
* the symbolic link to create.
* @param target
* the target the symbolic link should refer to.
*
* @throws PathAlreadyExistsException
* If the link already exists.
* @throws NoSuchPathException
* If the target or parent directory of link does not exist
* @throws InvalidPathException
* If parent of link is not a directory
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* If an I/O error occurred.
* @throws IllegalArgumentException
* If one or both of the arguments are null.
*/
public abstract void createSymbolicLink(Path link, Path target) throws XenonException;
/**
* Deletes an existing path.
*
* If path is a symbolic link the symbolic link is removed and the symbolic link's target is not deleted.
*
* If the path is a directory and <code>recursive</code> is set to true, the contents of the directory will also be deleted. If <code>recursive</code> is
* set to <code>false</code>, a directory will only be removed if it is empty.
*
* @param path
* the path to delete.
* @param recursive
* if the delete must be done recursively
* @throws DirectoryNotEmptyException
* if the directory was not empty (and the delete was not recursive).
* @throws NoSuchPathException
* if the provided path does not exist.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public void delete(Path path, boolean recursive) throws XenonException {
Path absPath = toAbsolutePath(path);
assertPathExists(absPath);
if (getAttributes(absPath).isDirectory()) {
Iterable<PathAttributes> itt = list(absPath, false);
if (recursive) {
for (PathAttributes p : itt) {
delete(p.getPath(), true);
}
} else {
if (itt.iterator().hasNext()) {
throw new DirectoryNotEmptyException(getAdaptorName(), "Directory not empty: " + absPath.toString());
}
}
deleteDirectory(absPath);
} else {
deleteFile(absPath);
}
}
/**
* Tests if a path exists.
*
* @param path
* the path to test.
*
* @return If the path exists.
*
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract boolean exists(Path path) throws XenonException;
/**
* List all entries in the directory <code>dir</code>.
*
* All entries in the directory are returned, but subdirectories will not be traversed by default. Set <code>recursive</code> to <code>true</code>, include
* the listing of all subdirectories.
*
* Symbolic links are not followed.
*
* @param dir
* the target directory.
* @param recursive
* should the list recursively traverse the subdirectories ?
*
* @return a {@link List} of {@link PathAttributes} that iterates over all entries in the directory <code>dir</code>.
*
* @throws NoSuchPathException
* If a directory does not exists.
* @throws InvalidPathException
* If <code>dir</code> is not a directory.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public Iterable<PathAttributes> list(Path dir, boolean recursive) throws XenonException {
Path absolute = toAbsolutePath(dir);
assertDirectoryExists(dir);
ArrayList<PathAttributes> result = new ArrayList<>();
list(absolute, result, recursive);
return result;
}
/**
* Open an existing file and return an {@link InputStream} to read from this file.
*
* @param file
* the to read.
*
* @return the {@link InputStream} to read from the file.
*
* @throws NoSuchPathException
* If the file does not exists.
* @throws InvalidPathException
* If the file is not regular file.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract InputStream readFromFile(Path file) throws XenonException;
/**
* Open a file and return an {@link OutputStream} to write to this file.
* <p>
*
* The size of the file (once all data has been written) must be specified using the <code>size</code> parameter. This is required by some implementations
* (typically blob-stores).
*
* </p>
*
* @param path
* the target file for the OutputStream.
* @param size
* the size of the file once fully written.
*
* @return the {@link OutputStream} to write to the file.
*
* @throws PathAlreadyExistsException
* If the target existed.
* @throws NoSuchPathException
* if a parent directory does not exist.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract OutputStream writeToFile(Path path, long size) throws XenonException;
/**
* Open a file and return an {@link OutputStream} to write to this file. (optional operation)
* <p>
* If the file already exists it will be replaced and its data will be lost.
*
* The amount of data that will be written to the file is not specified in advance. This operation may not be supported by all implementations.
*
* </p>
*
* @param file
* the target file for the OutputStream.
*
* @return the {@link OutputStream} to write to the file.
*
*
* @throws PathAlreadyExistsException
* If the target existed.
* @throws NoSuchPathException
* if a parent directory does not exist.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract OutputStream writeToFile(Path file) throws XenonException;
/**
* Open an existing file and return an {@link OutputStream} to append data to this file. (optional operation)
* <p>
* If the file does not exist, an exception will be thrown.
*
* This operation may not be supported by all implementations.
*
* </p>
*
* @param file
* the target file for the OutputStream.
*
* @return the {@link OutputStream} to write to the file.
*
* @throws PathAlreadyExistsException
* If the target existed.
* @throws NoSuchPathException
* if a parent directory does not exist.
* @throws InvalidPathException
* if not a regular file
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
* @throws UnsupportedOperationException
* if the adaptor does not support appending
*/
public abstract OutputStream appendToFile(Path file) throws XenonException;
/**
* Get the {@link PathAttributes} of an existing path.
*
* @param path
* the existing path.
*
* @return the FileAttributes of the path.
*
* @throws NoSuchPathException
* If the file does not exists.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract PathAttributes getAttributes(Path path) throws XenonException;
/**
* Reads the target of a symbolic link (optional operation).
*
* @param link
* the link to read.
*
* @return a Path representing the target of the link.
*
* @throws NoSuchPathException
* If the link does not exists.
* @throws InvalidPathException
* If the source is not a link.
* @throws UnsupportedOperationException
* If this FileSystem does not support symbolic links.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract Path readSymbolicLink(Path link) throws XenonException;
/**
* Sets the POSIX permissions of a path (optional operation).
*
* @param path
* the target path.
* @param permissions
* the permissions to set.
*
* @throws NoSuchPathException
* If the target path does not exists.
* @throws UnsupportedOperationException
* If this FileSystem does not support symbolic links.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If path is null.
*/
public abstract void setPosixFilePermissions(Path path, Set<PosixFilePermission> permissions) throws XenonException;
/**
* Convert the provided path to an absolute path by (if necessary) resolving a relative path against the working directory of this FileSystem. The resulting
* path is also normalized.
*
* @param path
* the path to convert
* @throws IllegalArgumentException
* if path is null.
* @return an absolute path
*/
protected Path toAbsolutePath(Path path) {
assertNotNull(path);
if (path.isAbsolute()) {
return path.normalize();
}
return workingDirectory.resolve(path).normalize();
}
/**
* Copy data from <code>in</code> to <code>out</code> using a buffer size of <code>buffersize</code>.
*
* After each <code>buffersize</code> block of data, <code>callback.addBytesCopied</code> will be invoked to report the number of bytes copied and
* <code>callback.isCancelled</code> will be invoked to determine if the copy should continue.
*
* @param in
* the stream to copy the data from.
* @param out
* the stream to copy the data to.
* @param buffersize
* the buffer size to use for copying.
* @param callback
* the callback to report bytes copied to and check cancellation from.
* @throws IOException
* if an I/O exception occurred.
* @throws CopyCancelledException
* if the copy was cancelled by the user.
*/
protected void streamCopy(InputStream in, OutputStream out, int buffersize, CopyCallback callback) throws IOException, CopyCancelledException {
byte[] buffer = new byte[buffersize];
int size = in.read(buffer);
while (size > 0) {
out.write(buffer, 0, size);
callback.addBytesCopied(size);
if (callback.isCancelled()) {
throw new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
}
size = in.read(buffer);
}
// Flush the output to ensure all data is written when this method returns.
out.flush();
}
/**
* Copy a symbolic link to another file system (optional operation).
*
* This is a blocking copy operation. It only returns once the link has been copied or the copy has failed.
*
* This operation may be re-implemented by the various implementations of FileSystem.
*
* This default implementation is based on a creating a new link on the destination filesystem. Note that the file the link is referring to is not copied.
* Only the link itself is copied.
*
* @param source
* the link to copy.
* @param destinationFS
* the destination {@link FileSystem} to copy to.
* @param destination
* the destination link on the destination file system.
* @param mode
* selects what should happen if the destination link already exists
* @param callback
* a {@link CopyCallback} used to update the status of the copy, or cancel it while in progress.
*
* @throws InvalidPathException
* if the provide source is not a link.
* @throws NoSuchPathException
* if the source link does not exist or the destination parent directory does not exist.
* @throws PathAlreadyExistsException
* if the destination link already exists.
* @throws UnsupportedOperationException
* if the destination FileSystem does not support symbolic links.
* @throws XenonException
* if the link could not be copied.
*/
protected void copySymbolicLink(Path source, FileSystem destinationFS, Path destination, CopyMode mode, CopyCallback callback) throws XenonException {
PathAttributes attributes = getAttributes(source);
if (!attributes.isSymbolicLink()) {
throw new InvalidPathException(getAdaptorName(), "Source is not a regular file: " + source);
}
destinationFS.assertParentDirectoryExists(destination);
if (destinationFS.exists(destination)) {
switch (mode) {
case CREATE:
throw new PathAlreadyExistsException(getAdaptorName(), "Destination path already exists: " + destination);
case IGNORE:
return;
case REPLACE:
// continue
break;
}
}
Path target = readSymbolicLink(source);
destinationFS.createSymbolicLink(destination, target);
}
/**
* Copy a single file to another file system.
*
* This is a blocking copy operation. It only returns once the file has been copied or the copy has failed.
*
* This operation may be re-implemented by the various implementations of FileSystem. This default implementation is based on a simple stream based copy.
*
* @param source
* the file to copy.
* @param destinationFS
* the destination {@link FileSystem} to copy to.
* @param destination
* the destination file on the destination file system.
* @param mode
* selects what should happen if the destination file already exists
* @param callback
* a {@link CopyCallback} used to update the status of the copy, or cancel it while in progress.
*
* @throws InvalidPathException
* if the provide source is not a regular file.
* @throws NoSuchPathException
* if the source file does not exist or the destination parent directory does not exist.
* @throws PathAlreadyExistsException
* if the destination file already exists.
* @throws XenonException
* If the file could not be copied.
*/
protected void copyFile(Path source, FileSystem destinationFS, Path destination, CopyMode mode, CopyCallback callback) throws XenonException {
PathAttributes attributes = getAttributes(source);
if (!attributes.isRegular()) {
throw new InvalidPathException(getAdaptorName(), "Source is not a regular file: " + source);
}
destinationFS.assertParentDirectoryExists(destination);
if (destinationFS.exists(destination)) {
switch (mode) {
case CREATE:
throw new PathAlreadyExistsException(getAdaptorName(), "Destination path already exists: " + destination);
case IGNORE:
return;
case REPLACE:
destinationFS.delete(destination, true);
// continue
break;
}
}
if (callback.isCancelled()) {
throw new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
}
try (InputStream in = readFromFile(source); OutputStream out = destinationFS.writeToFile(destination, attributes.getSize())) {
streamCopy(in, out, bufferSize, callback);
} catch (Exception e) {
throw new XenonException(getAdaptorName(), "Stream copy failed", e);
}
}
/**
* Perform a (possibly) recursive copy from a path on this filesystem to a path on <code>destinationFS</code>.
*
* @param source
* the source path on this FileSystem.
* @param destinationFS
* the destination FileSystem.
* @param destination
* the destination path.
* @param mode
* the copy mode that determines how to react if the destination already exists.
* @param recursive
* should the copy be performed recursively ?
* @param callback
* a {@link CopyCallback} used to return status information on the copy.
* @throws XenonException
* if an error occurred.
*/
protected void performCopy(Path source, FileSystem destinationFS, Path destination, CopyMode mode, boolean recursive, CopyCallback callback)
throws XenonException {
if (!exists(source)) {
throw new NoSuchPathException(getAdaptorName(), "No such file " + source.toString());
}
PathAttributes attributes = getAttributes(source);
// if (attributes.isRegular() || attributes.isSymbolicLink()) {
if (attributes.isRegular()) {
copyFile(source, destinationFS, destination, mode, callback);
return;
}
if (attributes.isSymbolicLink()) {
copySymbolicLink(source, destinationFS, destination, mode, callback);
return;
}
if (!attributes.isDirectory()) {
throw new InvalidPathException(getAdaptorName(), "Source path is not a file, link or directory: " + source);
}
if (!recursive) {
throw new InvalidPathException(getAdaptorName(), "Source path is a directory: " + source);
}
// From here on we know the source is a directory. We should also check the destination type.
if (destinationFS.exists(destination)) {
switch (mode) {
case CREATE:
throw new PathAlreadyExistsException(getAdaptorName(), "Destination path already exists: " + destination);
case IGNORE:
return;
case REPLACE:
// continue
break;
}
attributes = destinationFS.getAttributes(destination);
if (attributes.isRegular() || attributes.isSymbolicLink()) {
destinationFS.delete(destination, false);
destinationFS.createDirectory(destination);
} else if (!attributes.isDirectory()) {
throw new InvalidPathException(getAdaptorName(), "Existing destination is not a file, link or directory: " + source);
}
} else {
destinationFS.createDirectory(destination);
}
// We are now sure the target directory exists.
copyRecursive(source, destinationFS, destination, mode, callback);
}
private void copyRecursive(Path source, FileSystem destinationFS, Path destination, CopyMode mode, CopyCallback callback) throws XenonException {
long bytesToCopy = 0;
Iterable<PathAttributes> listing = list(source, true);
for (PathAttributes p : listing) {
if (callback.isCancelled()) {
throw new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
}
if (p.isDirectory() && !isDotDot(p.getPath())) {
Path rel = source.relativize(p.getPath());
Path dst = destination.resolve(rel);
if (destinationFS.exists(dst)) {
if (destinationFS.getAttributes(dst).isDirectory()) {
switch (mode) {
case CREATE:
throw new PathAlreadyExistsException(getAdaptorName(), "Directory already exists: " + dst);
case REPLACE:
break; // leave directory
case IGNORE:
return; // ignore subdir
}
} else {
destinationFS.delete(dst, true);
}
} else {
destinationFS.createDirectories(dst);
}
} else if (p.isRegular()) {
bytesToCopy += p.getSize();
}
}
callback.start(bytesToCopy);
for (PathAttributes p : listing) {
if (callback.isCancelled()) {
throw new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
}
if (p.isRegular()) {
Path rel = source.relativize(p.getPath());
Path dst = destination.resolve(rel);
copyFile(p.getPath(), destinationFS, dst, mode, callback);
}
}
}
/**
* Delete a file. Is only called on existing files
*
* This operation must be implemented by the various implementations of FileSystem.
*
* @param file
* the file to remove
* @throws InvalidPathException
* if the provided path is not a file.
* @throws NoSuchPathException
* if the provided file does not exist.
* @throws XenonException
* If the file could not be removed.
*/
protected abstract void deleteFile(Path file) throws XenonException;
/**
* Delete an empty directory. Is only called on empty directories
*
* This operation can only delete empty directories (analogous to <code>rmdir</code> in Linux).
*
* This operation must be implemented by the various implementations of FileSystem.
*
* @param path
* the directory to remove
* @throws InvalidPathException
* if the provided path is not a directory.
* @throws NoSuchPathException
* if the provided path does not exist.
* @throws XenonException
* If the directory could not be removed.
*/
protected abstract void deleteDirectory(Path path) throws XenonException;
/**
* Return the list of entries in a directory.
*
* This operation is non-recursive; any subdirectories in <code>dir</code> will be returned as part of the list, but they will not be listed themselves.
*
* This operation must be implemented by the various implementations of FileSystem.
*
* @param dir
* the directory to list
* @return a {@link Iterable} that iterates over all entries in <code>dir</code>
* @throws XenonException
* If the list could not be retrieved.
*/
protected abstract Iterable<PathAttributes> listDirectory(Path dir) throws XenonException;
/**
* Returns an (optionally recursive) listing of the entries in a directory <code>dir</code>.
*
* This is a generic implementation which relies on <code>listDirectory</code> to provide listings of individual directories.
*
* @param dir
* the directory to list.
* @param list
* the list to which the directory entries will be added.
* @param recursive
* if the listing should be done recursively.
* @throws XenonException
* If the list could not be retrieved.
*/
protected void list(Path dir, ArrayList<PathAttributes> list, boolean recursive) throws XenonException {
Iterable<PathAttributes> tmp = listDirectory(dir);
for (PathAttributes p : tmp) {
if (!isDotDot(p.getPath())) {
list.add(p);
}
}
if (recursive) {
for (PathAttributes current : tmp) {
// traverse subdirs provided they are not "." or "..".
if (current.isDirectory() && !isDotDot(current.getPath())) {
list(dir.resolve(current.getPath().getFileNameAsString()), list, true);
}
}
}
}
/**
* Asynchronously Copy an existing source path to a target path on a different file system.
*
* If the source path is a file, it will be copied to the destination file on the target file system.
*
* If the source path is a directory, it will only be copied if <code>recursive</code> is set to <code>true</code>. Otherwise, an exception will be thrown.
* When copying recursively, the directory and its content (both files and subdirectories with content), will be copied to <code>destination</code>.
*
* Exceptions that occur during copying will not be thrown by this function, but instead are contained in a {@link CopyStatus} object which can be obtained
* with {@link FileSystem#getStatus(String)}
*
* @param source
* the source path (on this filesystem) to copy from.
* @param destinationFS
* the destination filesystem to copy to.
* @param destination
* the destination path (on the destination filesystem) to copy to.
* @param mode
* how to react if the destination already exists.
* @param recursive
* if the copy should be recursive.
*
* @return a {@link String} that identifies this copy and be used to inspect its progress.
*
* @throws IllegalArgumentException
* If source, destinationFS, destination or mode is null.
*/
public synchronized String copy(final Path source, final FileSystem destinationFS, final Path destination, final CopyMode mode, final boolean recursive) {
if (source == null) {
throw new IllegalArgumentException("Source path is null");
}
if (destinationFS == null) {
throw new IllegalArgumentException("Destination filesystem is null");
}
if (destination == null) {
throw new IllegalArgumentException("Destination path is null");
}
if (mode == null) {
throw new IllegalArgumentException("Copy mode is null!");
}
String copyID = getNextCopyID();
final CopyCallback callback = new CopyCallback();
Future<Void> future = pool.submit(() -> {
if (Thread.currentThread().isInterrupted()) {
throw new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
}
performCopy(toAbsolutePath(source), destinationFS, toAbsolutePath(destination), mode, recursive, callback);
return null;
});
pendingCopies.put(copyID, new PendingCopy(future, callback));
return copyID;
}
/**
* Cancel a copy operation. Afterwards, the copy is forgotten and subsequent queries with this copy string will lead to {@link NoSuchCopyException}
*
* @param copyIdentifier
* the identifier of the copy operation which to cancel.
*
* @return a {@link CopyStatus} containing the status of the copy.
*
* @throws NoSuchCopyException
* If the copy is not known.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If the copyIdentifier is null.
*/
public synchronized CopyStatus cancel(String copyIdentifier) throws XenonException {
if (copyIdentifier == null) {
throw new IllegalArgumentException("Copy identifier may not be null");
}
PendingCopy copy = pendingCopies.remove(copyIdentifier);
if (copy == null) {
throw new NoSuchCopyException(getAdaptorName(), "Copy not found: " + copyIdentifier);
}
copy.callback.cancel();
copy.future.cancel(true);
XenonException ex = null;
String state = "DONE";
try {
copy.future.get();
} catch (ExecutionException ee) {
ex = new XenonException(getAdaptorName(), ee.getMessage(), ee);
state = "FAILED";
} catch (CancellationException ce) {
ex = new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
state = "FAILED";
} catch (InterruptedException e) {
ex = new CopyCancelledException(getAdaptorName(), "Copy interrupted by user");
state = "FAILED";
Thread.currentThread().interrupt();
}
return new CopyStatusImplementation(copyIdentifier, state, copy.callback.getBytesToCopy(), copy.callback.getBytesCopied(), ex);
}
/**
* Wait until a copy operation is done or until a timeout expires.
* <p>
* This method will wait until a copy operation is done (either gracefully or by producing an error), or until the timeout expires, whichever comes first.
* If the timeout expires, the copy operation will continue to run.
* </p>
* <p>
* The timeout is in milliseconds and must be >= 0. When timeout is 0, it will be ignored and this method will wait until the copy operation is done.
* </p>
* After this operation, the copy is forgotten and subsequent queries with this copy string will lead to {@link NoSuchCopyException}
* <p>
* A {@link CopyStatus} is returned that can be used to determine why the call returned.
* </p>
*
* @param copyIdentifier
* the identifier of the copy operation to wait for.
* @param timeout
* the maximum time to wait for the copy operation in milliseconds.
*
* @return a {@link CopyStatus} containing the status of the copy.
*
* @throws IllegalArgumentException
* If argument is illegal.
* @throws NoSuchCopyException
* If the copy handle is not known.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If the copyIdentifier is null or if the value of timeout is negative.
*/
public CopyStatus waitUntilDone(String copyIdentifier, long timeout) throws XenonException {
if (copyIdentifier == null) {
throw new IllegalArgumentException("Copy identifier may not be null");
}
PendingCopy copy = pendingCopies.get(copyIdentifier);
if (copy == null) {
throw new NoSuchCopyException(getAdaptorName(), "Copy not found: " + copyIdentifier);
}
XenonException ex = null;
String state = "DONE";
try {
copy.future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
state = "RUNNING";
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause instanceof XenonException) {
ex = (XenonException) cause;
} else {
ex = new XenonException(getAdaptorName(), cause.getMessage(), cause);
}
state = "FAILED";
} catch (CancellationException ce) {
ex = new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
state = "FAILED";
} catch (InterruptedException ie) {
ex = new CopyCancelledException(getAdaptorName(), "Copy interrupted by user");
state = "FAILED";
Thread.currentThread().interrupt();
}
if (copy.future.isDone()) {
pendingCopies.remove(copyIdentifier);
}
return new CopyStatusImplementation(copyIdentifier, state, copy.callback.getBytesToCopy(), copy.callback.getBytesCopied(), ex);
}
/**
* Retrieve the status of an copy. After obtaining the status of a completed copy, the copy is forgotten and subsequent queries with this copy string will
* lead to {@link NoSuchCopyException}.
*
* @param copyIdentifier
* the identifier of the copy for which to retrieve the status.
*
* @return a {@link CopyStatus} containing the status of the asynchronous copy.
*
* @throws NoSuchCopyException
* If the copy is not known.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If the copyIdentifier is null.
*/
public CopyStatus getStatus(String copyIdentifier) throws XenonException {
if (copyIdentifier == null) {
throw new IllegalArgumentException("Copy identifier may not be null");
}
PendingCopy copy = pendingCopies.get(copyIdentifier);
if (copy == null) {
throw new NoSuchCopyException(getAdaptorName(), "Copy not found: " + copyIdentifier);
}
XenonException ex = null;
String state = "PENDING";
if (copy.future.isDone()) {
pendingCopies.remove(copyIdentifier);
// We have either finished, crashed, or cancelled
try {
copy.future.get();
state = "DONE";
} catch (ExecutionException ee) {
ex = new XenonException(getAdaptorName(), ee.getMessage(), ee);
state = "FAILED";
} catch (CancellationException ce) {
ex = new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
state = "FAILED";
} catch (InterruptedException ie) {
ex = new CopyCancelledException(getAdaptorName(), "Copy interrupted by user");
state = "FAILED";
Thread.currentThread().interrupt();
}
} else if (copy.callback.isStarted()) {
state = "RUNNING";
}
return new CopyStatusImplementation(copyIdentifier, state, copy.callback.getBytesToCopy(), copy.callback.getBytesCopied(), ex);
}
protected void assertNotNull(Path path) {
if (path == null) {
throw new IllegalArgumentException("Path is null");
}
}
protected void assertPathExists(Path path) throws XenonException {
assertNotNull(path);
if (!exists(path)) {
throw new NoSuchPathException(getAdaptorName(), "Path does not exist: " + path);
}
}
protected void assertPathNotExists(Path path) throws XenonException {
assertNotNull(path);
if (exists(path)) {
throw new PathAlreadyExistsException(getAdaptorName(), "Path already exists: " + path);
}
}
protected void assertPathIsNotDirectory(Path path) throws XenonException {
assertNotNull(path);
if (exists(path)) {
PathAttributes a = getAttributes(path);
if (a.isDirectory()) {
throw new InvalidPathException(getAdaptorName(), "Was expecting a regular file, but got a directory: " + path.toString());
}
}
}
protected void assertPathIsFile(Path path) throws XenonException {
assertNotNull(path);
if (!getAttributes(path).isRegular()) {
throw new InvalidPathException(getAdaptorName(), "Path is not a file: " + path);
}
}
protected void assertPathIsDirectory(Path path) throws XenonException {
assertNotNull(path);
PathAttributes a = getAttributes(path);
if (a == null) {
throw new InvalidPathException(getAdaptorName(), "Path failed to produce attributes: " + path);
}
if (!a.isDirectory()) {
throw new InvalidPathException(getAdaptorName(), "Path is not a directory: " + path);
}
}
protected void assertFileExists(Path file) throws XenonException {
assertPathExists(file);
assertPathIsFile(file);
}
protected void assertDirectoryExists(Path dir) throws XenonException {
assertPathExists(dir);
assertPathIsDirectory(dir);
}
protected void assertParentDirectoryExists(Path path) throws XenonException {
assertNotNull(path);
Path parent = path.getParent();
if (parent != null) {
assertDirectoryExists(parent);
}
}
protected void assertFileIsSymbolicLink(Path link) throws XenonException {
assertNotNull(link);
assertPathExists(link);
if (!getAttributes(link).isSymbolicLink()) {
throw new InvalidPathException(getAdaptorName(), "Not a symbolic link: " + link);
}
}
protected void assertIsOpen() throws XenonException {
if (!isOpen()) {
throw new NotConnectedException(getAdaptorName(), "Connection is closed");
}
}
// Expects two non-null, normalized absolute paths
protected boolean areSamePaths(Path source, Path target) {
return source.equals(target);
}
protected boolean isDotDot(Path path) {
assertNotNull(path);
String filename = path.getFileNameAsString();
return ".".equals(filename) || "..".equals(filename);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FileSystem that = (FileSystem) o;
return Objects.equals(uniqueID, that.uniqueID);
}
@Override
public int hashCode() {
return Objects.hash(uniqueID);
}
}
|
apache-2.0
|
lejandro83/AdMint
|
Publicidad.html
|
2963
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>AdMint</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/stylish-portfolio.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">
<!-- Bootstrap Core CSS Isa-->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS Isa-->
<link href="css/logo-nav.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Navigation End Isa-->
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top " role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<a class="navbar-left" href="Website.html">
<img src="img/Logo.png" height="50px">
</a>
<a class="navbar-brand navbar-right">
<img src="img/Slogan.png" height='20px';>
</a>
</div>
<!-- /.container -->
</nav>
<header id="top" class="header">
<div class="text-vertical-center">
<h1>Publicidad en línea</h1>
<h3>Facebook Ads: Además de generar contenido promocionamos tu página de Facebook mediante promociones hechas a la medida o mediante publicaciones de interés para tu público. </h3>
<h3>Google Adwords: Alcanzamos a tu público objetivo lo que se traduce en clientes potenciales que están interesados en lo que ofreces. </h3>
<h3>Twitter Ads: Promocionamos el contenido que atrae a tus clientes potenciales. </h3>
</div>
</header>
</body>
<aside class="call-to-action bg-primary">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<a href="Website.html" class="btn btn-lg btn-light">Back</a>
</div>
</div>
</div>
</aside>
|
apache-2.0
|
wesleyan/chef-cookbooks
|
cookbooks/launch_association/metadata.rb
|
311
|
maintainer 'Wesleyan University'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Manages file type associations'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.2.0'
depends 'common'
depends 'homebrew'
|
apache-2.0
|
tsvetie/nativescript-cli
|
resources/vr/Assets/NVR/Interfaces/Elements/IElement.cs
|
278
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.NVR.Interfaces.Elements
{
public interface IElement : IUnit
{
void SetColor(string color);
void SetPosition(float pos);
}
}
|
apache-2.0
|
jmarkos/protostream
|
core/src/main/java/org/infinispan/protostream/UnknownFieldSetHandler.java
|
445
|
package org.infinispan.protostream;
/**
* An interface to be implemented by marshaller objects of type {@link MessageMarshaller}) that are able to handle
* unknown fields by storing them into an {@link UnknownFieldSet}.
*
* @author [email protected]
* @since 3.0
*/
public interface UnknownFieldSetHandler<T> {
UnknownFieldSet getUnknownFieldSet(T message);
void setUnknownFieldSet(T message, UnknownFieldSet unknownFieldSet);
}
|
apache-2.0
|
chicofilho/fst
|
events/mjun/2018/eleclerc-pont-labbe-junior-pro-.html
|
37196
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fantasy Surfing Tips - Stats from mjun E.Leclerc Pont-l&apos;Abbe Junior Pro La Torche 2018 </title>
<meta name="description" content="Statistics and analysis from all events of the 2018 year. From mjun of the E.Leclerc Pont-l&apos;Abbe Junior Pro La Torche event">
<meta name="author" content="">
<link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta property="og:title" content="Fantasy Surfing tips"/>
<meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/>
<!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ -->
<link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet">
<link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" />
<!-- Custom Fonts -->
<link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://code.jquery.com/jquery-2.x-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://www.w3schools.com/lib/w3data.js"></script>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-2675412311042802",
enable_page_level_ads: true
});
</script>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Navigation -->
<div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div>
<div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div>
<div class="row">
<div class="col-sm-12 text-center">
<h1> E.Leclerc Pont-l&apos;Abbe Junior Pro La Torche</h1>
<hr class="star-primary" />
<h4> La Torche, Finistere, Bretagne, France</h4>
<p> May 09, 2018</p>
<div class="row">
<div class="col-sm-2 text-center">
</div>
<div class="col-sm-4 text-center">
<span>Best AHS</span><br/>
<h5> Kauli Vaast</h5>
<p> 14.48</p>
</div>
<div class="col-sm-4 text-center">
<span>Best Winning Perc.</span><br/>
<h5> Justin Becret</h5>
<p> 100.0%</p>
</div>
<div class="col-sm-2 text-center">
</div>
</div>
<hr/>
</div>
</div>
<div class="container">
<div class="row">
<h3 class="text-center"> Stats from E.Leclerc Pont-l&apos;Abbe Junior Pro La Torche 2018</h3>
<div class="col-sm-12">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Average Heat Score</th>
<th>Heats</th>
<th>Victories</th>
<th>Winning Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/kvaa">Kauli Vaast</a> </td>
<td>14.48</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mmig">Marco Mignot</a> </td>
<td>12.97</td>
<td>5</td>
<td>4</td>
<td>80.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ljen">Lenni Jensen</a> </td>
<td>12.44</td>
<td>6</td>
<td>5</td>
<td>83.33%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/jbec">Justin Becret</a> </td>
<td>12.42</td>
<td>6</td>
<td>6</td>
<td>100.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/rbran">Ricardo Brandão</a> </td>
<td>12.1</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mcro">Mathis Crozon</a> </td>
<td>11.69</td>
<td>5</td>
<td>4</td>
<td>80.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/aant">Afonso Antunes</a> </td>
<td>11.6</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ypen">Yael Pena</a> </td>
<td>11.29</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tlac">Tomas Lacerda</a> </td>
<td>11.27</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tdeb">Thomas Debierre</a> </td>
<td>11.14</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/hnew">Huckleberry New</a> </td>
<td>10.82</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tcane">Titouan Canevet</a> </td>
<td>10.75</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/kama">Kayam Amar</a> </td>
<td>10.5</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tbouc">Teva Bouchgua</a> </td>
<td>10.49</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/gcar">Giulio Caruso</a> </td>
<td>10.47</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ngui">Nicolas Guimond</a> </td>
<td>10.45</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/cpor">Cristian Portelli</a> </td>
<td>10.34</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mlab">Mael Laborde</a> </td>
<td>10.31</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/rsilv">Rafael Silva</a> </td>
<td>10.26</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/sgun">Sean Gunning</a> </td>
<td>10.24</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/abuf">Aurelien Buffet</a> </td>
<td>10.19</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ocas">Olivier Cassaigne</a> </td>
<td>10.14</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tled">Thomas Ledee</a> </td>
<td>10.09</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/wmas">Willoughby Masterman</a> </td>
<td>10.09</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/jvid">Joao Vidal</a> </td>
<td>9.9</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ngerr">Noe Gerrits</a> </td>
<td>9.84</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/eblo">Erwan Blouin</a> </td>
<td>9.8</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/iaup">Issam Auptel</a> </td>
<td>9.66</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/asal">Antonin Salaverria</a> </td>
<td>9.66</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tgoa">Tom Goasguen</a> </td>
<td>9.61</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mcas">Miguel Castrillon</a> </td>
<td>9.49</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/blec">Brieuc Lecointre</a> </td>
<td>9.4</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mmato">Miguel Matos</a> </td>
<td>9.16</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ghou">Gaizka Housset Ezponda</a> </td>
<td>9.1</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/trun">Tréveur Runavot</a> </td>
<td>9.0</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/htos">Hugo Tosetti</a> </td>
<td>8.98</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/nled">Noe Ledee</a> </td>
<td>8.79</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mnune">Martim Nunes</a> </td>
<td>8.57</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/rcha">Rodrigo Chaves</a> </td>
<td>8.5</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/akad">Arthur Kadji</a> </td>
<td>8.5</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/apar">Antoine Parenteau</a> </td>
<td>8.44</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ycon">Youri Conradi</a> </td>
<td>8.27</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/sden">Seb Den Otter</a> </td>
<td>8.17</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mpau">Martim Paulino</a> </td>
<td>8.06</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/lnog">Luan Nogues</a> </td>
<td>8.02</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/maza">Mathis Azam</a> </td>
<td>7.77</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dvand">Dean Vandewalle</a> </td>
<td>7.76</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/lgen">Logan Gengembre</a> </td>
<td>7.4</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mdos">Maxime Dos Anjos</a> </td>
<td>7.35</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/iama">Iker Amatriain</a> </td>
<td>7.34</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/epap">Edoardo Papa</a> </td>
<td>7.26</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/test">Tom Esteva</a> </td>
<td>7.23</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/cguer">Clement Guertener</a> </td>
<td>7.14</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/scout">Salvador Couto</a> </td>
<td>7.1</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/szou">Selyann Zouhir</a> </td>
<td>7.08</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/spite">Sam Piter</a> </td>
<td>7.04</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/hcard">Hugo Cardoso</a> </td>
<td>6.94</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/alop">Axel Lopetegi</a> </td>
<td>6.89</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dgome">Dorian Gomez</a> </td>
<td>6.89</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/npau">Nicolas Paulet</a> </td>
<td>6.87</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dsua">Diego Suarez Diaz</a> </td>
<td>6.83</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/nena">Nicolas Enaux</a> </td>
<td>6.6</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/rgra">Renan Grainville</a> </td>
<td>6.6</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/snik">Siam Nikritin</a> </td>
<td>6.5</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/jmari">Jose Maria Bruschy</a> </td>
<td>6.47</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/kgue">Kyllian Guerin</a> </td>
<td>6.33</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ldesm">Lucas Desmoucelle</a> </td>
<td>6.3</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/sram">Sebastião Ramirez</a> </td>
<td>6.25</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tcon">Timothée Constant</a> </td>
<td>6.17</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mcal">Matteo Calatri</a> </td>
<td>6.16</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dmart">Diogo Martins</a> </td>
<td>6.13</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dgro">Dylan Groen</a> </td>
<td>5.97</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/telt">Tim Elter</a> </td>
<td>5.92</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/iark">Ido Arkin</a> </td>
<td>5.9</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mlec">Mathias Lecacheur</a> </td>
<td>5.83</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ltab">Louis Tabere Allamelou</a> </td>
<td>5.75</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/vcor">Vasco Cordeiro</a> </td>
<td>5.74</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/nhul">Nelson Hulot</a> </td>
<td>5.65</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/zs&#">Zouhir Sélyann</a> </td>
<td>5.57</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/gribe">Gabriel Ribeiro</a> </td>
<td>5.48</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ndup">Noa Dupouy</a> </td>
<td>5.44</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/wnew">Woody New</a> </td>
<td>5.4</td>
<td>4</td>
<td>3</td>
<td>75.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tgou">Teiva Goujon</a> </td>
<td>5.33</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mmic">Maksymilian Michalewski</a> </td>
<td>5.23</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/acan">Afonso Candeias</a> </td>
<td>5.1</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/jchav">Joaquim Chaves</a> </td>
<td>5.07</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tman">Thibault Manson</a> </td>
<td>5.03</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/crev">Cesar Reveillon</a> </td>
<td>4.67</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/lagur">Leon Agurruza</a> </td>
<td>4.67</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/snor">Stanley Norman</a> </td>
<td>4.63</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tcarr">Tiago Carrique</a> </td>
<td>4.43</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/mchou">Martin Chouraqui</a> </td>
<td>4.08</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dnob">Daniel Nobrega</a> </td>
<td>3.87</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/smor">Seth Morris</a> </td>
<td>3.74</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tkos">Tom Kostyra</a> </td>
<td>3.73</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/dcan">Dorian Can</a> </td>
<td>3.55</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/arier">Arnau Riera</a> </td>
<td>3.28</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/ksua">Kike Suarez</a> </td>
<td>3.0</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/hle">Hugo Le Foll</a> </td>
<td>3.0</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/kgod">Kilian God</a> </td>
<td>2.38</td>
<td>3</td>
<td>2</td>
<td>66.67%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/aleo">Agurruza Leon</a> </td>
<td>2.3</td>
<td>2</td>
<td>1</td>
<td>50.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/tves">Titouan Veschambre</a> </td>
<td>1.5</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
<tr>
<td><a href="http://fantasysurfingtips.com/surfers/mjun/gcarp">George Carpenter</a> </td>
<td>0.0</td>
<td>1</td>
<td>0</td>
<td>0.0%</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
$('.table').dataTable({bFilter: false, bInfo: false, paging: false});
});
</script>
</div>
</div>
</div>
<!-- Footer -->
<div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div>
<script type="text/javascript">
(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-74337819-1', 'auto'); // Replace with your property ID.
ga('send', 'pageview');
</script>
<script>
w3IncludeHTML();
</script>
<!-- jQuery -->
<script src="https://fantasysurfingtips.com/js/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="https://fantasysurfingtips.com/js/classie.js"></script>
<script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script>
<script src="https://fantasysurfingtips.com/js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="https://fantasysurfingtips.com/js/freelancer.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
</body>
</html>
|
apache-2.0
|
consulo/consulo-csharp
|
csharp-impl/src/test/resources/resolve/other/Issue424.cs
|
306
|
public struct SomeValue
{
public static SomeValue operator-(SomeValue someValue, SomeValue someValue2)
{
return new SomeValue();
}
}
public class Program
{
public static void Main()
{
SomeValue? nullable = new SomeValue();
SomeValue someValue = new SomeValue();
nullable -= someValue;
}
}
|
apache-2.0
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b_testAbaNumberCheck_28522_bad_8yp.html
|
10992
|
<!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_13b.html">Class Test_AbaRouteValidator_13b</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_28522_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b.html?line=31792#src-31792" >testAbaNumberCheck_28522_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:42:47
</td>
<td>
0.001 </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_28522_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=11617#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=11617#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=11617#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Cornales/Hydrangeaceae/Philadelphus/Philadelphus cinereus/README.md
|
183
|
# Philadelphus cinereus Hand.-Mazz. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
BenjaminRepingon/fractal
|
includes/mandelbrot.h
|
1505
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mandelbrot.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbenjami <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/02/23 10:53:23 by rbenjami #+# #+# */
/* Updated: 2015/02/27 17:47:57 by rbenjami ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MANDELBROT_H
# define MANDELBROT_H
# include "object.h"
# define MANDELBROT t_mandelbrot
typedef struct s_mandelbrot
{
OBJECT *object;
VERT vertex;
double min_x;
double max_x;
double min_y;
double max_y;
double rc;
double ic;
double rz;
double iz;
double zoom;
int mode;
int anti_alias;
VEC2 old_pos;
BOOL changed;
} t_mandelbrot;
MANDELBROT *new_mandelbrot(float minx, float maxx, float miny, float maxy);
MANDELBROT *new_julia(float min_x, float max_x, float min_y, float max_y);
MANDELBROT *new_burning_ship(float inx, float axx, float iny, float axy);
#endif
|
apache-2.0
|
FasterXML/jackson-annotations
|
src/main/java/com/fasterxml/jackson/annotation/JsonAlias.java
|
1130
|
package com.fasterxml.jackson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation that can be used to define one or more alternative names for
* a property, accepted during deserialization as alternative to the official
* name. Alias information is also exposed during POJO introspection, but has
* no effect during serialization where primary name is always used.
*<p>
* Examples:
*<pre>
*public class Info {
* @JsonAlias({ "n", "Name" })
* public String name;
*}
*</pre>
*
* @since 2.9
*/
@Target({ElementType.ANNOTATION_TYPE, // for combo-annotations
ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER// for properties (field, setter, ctor param)
})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonAlias
{
/**
* One or more secondary names to accept as aliases to the official name.
*
* @return Zero or more aliases to associate with property annotated
*/
public String[] value() default { };
}
|
apache-2.0
|
lab702-flyme/sweo_android
|
app/src/main/java/com/example/linxj/tool/RequestListener.java
|
787
|
package com.example.linxj.tool;
public interface RequestListener {
public static final int EVENT_BASE = 0x100;
/**
* 没有网络的信息提示
* */
public static final int EVENT_NOT_NETWORD = EVENT_BASE + 1;
/**
* 网络异常的信息提示
* */
public static final int EVENT_NETWORD_EEEOR = EVENT_BASE + 2;
/**
* 获取网络数据失败
* */
public static final int EVENT_GET_DATA_EEEOR = EVENT_BASE + 3;
/**
* 获取网络数据成功
* */
public static final int EVENT_GET_DATA_SUCCESS = EVENT_BASE + 4;
/**
* 获取网络数据成功
* */
public static final int EVENT_CLOSE_SOCKET = EVENT_BASE + 5;
public void action(int actionCode, Object object);
}
|
apache-2.0
|
jlinn/riot-api-java
|
src/main/java/net/joelinn/riot/staticdata/dto/RuneType.java
|
173
|
package net.joelinn.riot.staticdata.dto;
/**
* Joe Linn
* 2/1/14
*/
public class RuneType {
public boolean isrune;
public String tier;
public String type;
}
|
apache-2.0
|
grogdj/codename
|
codename-html5/app/views/messages.html
|
11362
|
<div class="user-section-title">
<div class="container">
<h2>My Messages</h2>
</div>
</div>
<div ng-if="chatStatus === 'loading'">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<div class="loader">
<i class="fa fa-spinner fa-spin"></i> Connecting to Chat Server ...
</div>
</div>
</div>
</div>
</div>
<div id="chatOffline" ng-if="chatStatus === 'offline'">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="content-block">
<div class="content-block-title">
Chat Offline
</div>
<div class="content-block-content">
<p>Sometimes the Chat Server goes down, we apologies for the inconvenience, please try reconnecting.</p>
</div>
<div class="content-block-actions">
<a href class="button block" ng-click="reConnectChat()"> Re-connect</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="messages" ng-if="chatStatus === 'online'">
<div class="container">
<div class="left-col">
<div class="content-block no-margin">
<div class="content-block-title">
Inbox
</div>
<div class="content-block-content">
<div id="user-messages-inbox">
<div ng-if="!conversationsLoaded">
<div class="loader text-center">
<i class="fa fa-spinner fa-spin"></i>
</div>
</div>
<div class="inbox-message" ng-repeat="conversation in inbox | orderBy:'last_message.sent_at':true" ng-click="selectConversation(conversation)" ng-class="{active: selectedConversation.url == conversation.url, blocked: conversation.blocked, new: conversation.last_message.is_unread == true}">
<div class="user-avatar">
<div class="message-user-avatar hexagon" ng-repeat="p in conversation.participants">
<div class="hexagon-inner-1" >
<div class="hexagon-inner-2 avatar" ng-if="p != me" style="background-image: url('{{serverUrlFull + 'rest/public/users/' + p + '/avatar?size=90'}}');">
</div>
</div>
</div>
<div class="message-user-avatar-bgr hexagon">
<div class="hexagon-inner-1">
<div class="hexagon-inner-2" >
</div>
</div>
</div>
<div class="online-status" ng-if="conversation.onlineStatus !== 'false'"></div>
<div class="unread-badge" ng-if="conversation.unread_message_count > 0">{{conversation.unread_message_count}}</div>
</div>
<div class="message-data">
<div ng-repeat="pFull in conversation.metadata.participantsName">
<div class="message-user-name" ng-if="pFull != meFull" ><span>{{pFull}}</span></div>
</div>
<div class="message-excerpt" >
<span class="reply" ng-if="conversation.last_message.sender.user_id == me"><i class="fa fa-reply"></i></span>
<span ng-bind-html="conversation.last_message.parts[0].body | colonToSmiley"></span>
<span ng-if="!conversation.last_message"> ... </span>
</div>
<div class="message-date">{{conversation.last_message.received_at| date:'EEE HH:mm'}}</div>
</div>
</div>
<a href class="button block" ng-if="inbox.length > 6">Load more</a>
<div class="no-message" ng-if="inbox.length === 0 && conversationsLoaded ">
No Messages
</div>
</div>
</div>
</div>
</div>
<div class="right-col">
<div class="content-block no-margin" ng-class="{blocked: selectedConversation.blocked == true}">
<div class="content-block-title">
<span ng-repeat="p in selectedConversation.metadata.participantsName">
<span ng-if="p != meFull">{{p}}</span>
</span>
<div class="no-message" ng-if="!selectedConversation">
Select a message to start chatting
</div>
<div class="content-block-title-options" ng-if="selectedConversation">
<ul class="option-button">
<li>
<div class="button-icon"><i class="fa fa-angle-down"></i></div>
<ul class="dropdown" >
<li class="dropdown-item">
<a href="#/report" class="dropdown-link" >Report abuse / spam</a>
</li>
<!--li ng-if="!selectedConversation.blocked" class="dropdown-item">
<a href class="dropdown-link" ng-click="deleteConversation(selectedConversation.url)">Remove Conversation</a>
</li-->
</ul>
</li>
</ul>
</div>
</div>
<div class="content-block-content">
<div id="user-messages-chat">
<div class="blocked-message" ng-if="selectedConversation.blocked">
This user is blocked.
</div>
<div class="messages-history" ng-if="!selectedConversation.blocked">
<div class="messages-history-day" >
<!--<div class="day-name" ng-if="selectedConversation">
<span>
<a href class="button inverted small">Load more</a>
</span>
</div>
-->
<div class="day-messages">
<div ng-if="!messagesLoaded && selectedConversation">
<div class="loader text-center">
<i class="fa fa-spinner fa-spin"></i> Loading messages...
</div>
</div>
<div class="history-message" ng-repeat="message in messageHistory | orderBy:'position':reverse">
<div class="user-avatar">
<div class="history-message-user-avatar hexagon">
<div class="hexagon-inner-1">
<div class="hexagon-inner-2 avatar" style="background-image: url('{{serverUrlFull + 'rest/public/users/' + message.sender.user_id + '/avatar?size=90'}}');">
</div>
</div>
</div>
</div>
<div class="message-body">
<div class="message-hour">
{{message.sent_at| date:'EEE HH:mm'}}
</div>
<div class="message-user" ng-if="message.sender.user_id == me">
{{meFull}}
</div>
<div class="message-user" ng-if="message.sender.user_id != me">
<span ng-repeat="p in selectedConversation.metadata.participantsName">
<span ng-if="p != meFull">{{p}}</span>
</span>
</div>
<div ng-bind-html="message.parts[0].body | colonToSmiley" class="message-text">
</div>
<div class="message-read-status" ng-if="$last && getLastSentMessageStatus(message.recipient_status) == 'read' && message.sender.user_id == me"> <i class="fa fa-check"></i> Read</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="user-messages-send">
<div class="send-input" emoji-form emoji-message="emojiMessage">
<textarea ng-model="emojiMessage.messagetext" id="sendMessageTextArea" ng-disabled="!selectedConversation" placeholder="Write your message here..." ng-class="{disabled: !selectedConversation}" ></textarea>
</div>
<!-- <button id="emojibtn">
<i class="icon icon-emoji"></i>
</button>-->
<div class="send-actions">
<button id="sendMessageButton" class="button primary" ng-disabled="!selectedConversation || !emojiMessage.messagetext"
ng-click="sendMessage(selectedConversation, emojiMessage.messagetext,'text/plain')" >{{sendText}}</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
apache-2.0
|
mkfeuhrer/TPO-MNNIT
|
app/src/main/java/com/example/mohit/tpomnnit/tpo/TpoHome.java
|
15187
|
package com.example.mohit.tpomnnit.tpo;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mohit.tpomnnit.Landing;
import com.example.mohit.tpomnnit.R;
import com.example.mohit.tpomnnit.contactUs;
import com.example.mohit.tpomnnit.login_signup.TpoLogin;
import com.example.mohit.tpomnnit.student.StudentProfile;
import com.example.mohit.tpomnnit.student.profile.UserData;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TpoHome extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private EditText name,regnum,branch,course,regno;
private String registrationnum,userId;
private DatabaseReference mDatabase;
private StorageReference storage,imageref;
private ImageView imageview,verified;
String nameuser;
Spinner spinnerbranch,spinnercourse;
String branchselected,courseselected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tpo_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(TpoHome.this,AddCompany.class);
startActivity(i);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mDatabase = FirebaseDatabase.getInstance().getReference("tpouserdata");
userId=mDatabase.push().getKey();
name=(EditText)findViewById(R.id.name);
regnum=(EditText)findViewById(R.id.regnum);
branch=(EditText)findViewById(R.id.branch);
course=(EditText)findViewById(R.id.course);
verified=(ImageView)findViewById(R.id.verified);
imageview = (ImageView)findViewById(R.id.imageView3);
registrationnum = getIntent().getStringExtra("reg");
// Log.e("reg",registrationnum);
storage = FirebaseStorage.getInstance().getReference("userimage/"+registrationnum+".jpg");
imageref = storage;
File localFile = null;
try {
localFile = File.createTempFile("images", "jpg");
} catch (IOException e) {
e.printStackTrace();
}
final File finalLocalFile = localFile;
imageref.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
Toast.makeText(getApplicationContext(),"File Download",Toast.LENGTH_LONG);
Bitmap bitmap = BitmapFactory.decodeFile(finalLocalFile.getAbsolutePath());
imageview.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
Toast.makeText(TpoHome.this,"Image not found",Toast.LENGTH_LONG).show();
}
});
ValueEventListener vel = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserData user= dataSnapshot.getValue(UserData.class);
for(DataSnapshot userDetails : dataSnapshot.getChildren()) {
if(registrationnum.equals(userDetails.child("regno").getValue().toString()))
{
name.setText(userDetails.child("name").getValue().toString());
View h1 = navigationView.getHeaderView(0);
TextView nav_user = h1.findViewById(R.id.name);
TextView nav_email = h1.findViewById(R.id.email);
nav_user.setText( "\t "+userDetails.child("name").getValue().toString());
nav_email.setText("\t "+userDetails.child("email").getValue().toString());
/*View h1 = navigationView.getHeaderView(0);
TextView nav_user = h1.findViewById(R.id.name);
TextView nav_email = h1.findViewById(R.id.email);
//Toast.makeText(StudentProfile.this,""+userDetails.child("name").getValue().toString(),Toast.LENGTH_LONG).show();
nav_user.setText( "\t "+userDetails.child("name").getValue().toString());
nav_email.setText("\t "+userDetails.child("email").getValue().toString());*/
course.setText(userDetails.child("course").getValue().toString());
branch.setText(userDetails.child("branch").getValue().toString());
regnum.setText(registrationnum);
/*int val=Integer.parseInt(userDetails.child("verified").getValue().toString());
if(val==1)
{
//Drawable d=R.drawable.tick;
verified.setImageResource(R.drawable.tick);
}*/
//Access all data
}
// Log.d("valueName:", userDetails.child("name").getValue().toString());
// Log.d("valueEmail:", userDetails.child("email").getValue().toString());
// Log.d("valueuserid:", userDetails.child("studentid").getValue().toString());
// Log.d("password:", userDetails.child("password").getValue().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addListenerForSingleValueEvent(vel);
}
@Override
public void onBackPressed()
{
Intent i=new Intent(TpoHome.this,Landing.class);
startActivity(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tpo_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.verifyuser) {
Intent i = new Intent(TpoHome.this,VerifyUser.class);
i.putExtra("flag",0);
startActivity(i);
// Handle the camera action
} else if (id == R.id.manage_student) {
final Dialog dialog = new Dialog(TpoHome.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.activity_student_filter);
dialog.setCanceledOnTouchOutside(true);
dialog.onBackPressed();
spinnerbranch=(Spinner)dialog.findViewById(R.id.spinnerbranch);
spinnercourse=(Spinner)dialog.findViewById(R.id.spinnercourse);
regno=(EditText) dialog.findViewById(R.id.regno);
Button find=(Button)dialog.findViewById(R.id.find);
branchspinner();
coursespinner();
find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
Intent intent=new Intent(TpoHome.this,ManageStudents.class);
intent.putExtra("flag",1);
intent.putExtra("course",courseselected);
intent.putExtra("branch",branchselected);
intent.putExtra("regno",regno.getText().toString().trim());
startActivity(intent);
}
});
dialog.show();
//Intent i = new Intent(TpoHome.this,StudentFilter.class);
//startActivity(i);
} else if (id == R.id.update_company) {
Intent intent=new Intent(TpoHome.this,UpdateCompany.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
Intent i = new Intent(TpoHome.this,contactUs.class);
startActivity(i);
} else if (id == R.id.nav_send) {
} else if (id == R.id.logout){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Logging Off")
.setMessage("Are you sure you want to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase data = openOrCreateDatabase("login", MODE_PRIVATE, null);
data.execSQL("drop table if exists tpo");
Intent i = new Intent(TpoHome.this, TpoLogin.class);
startActivity(i);
finish();
}
})
.setNegativeButton("No", null)
.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void branchspinner()
{
// Spinner click listener
List<String> branches = new ArrayList<String>();
branches.add("ALL");
branches.add("CSE");
branches.add("IT");
branches.add("ECE");
branches.add("EE");
branches.add("ME");
branches.add("PIE");
branches.add("CHE");
branches.add("BIO");
branches.add("CIVIL");
branches.add("MCA");
ArrayAdapter<String> dataAdapterbranch;
dataAdapterbranch = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,branches);
// Drop down layout style - list view with radio button
dataAdapterbranch.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerbranch.setAdapter(dataAdapterbranch);
spinnerbranch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
branchselected = parent.getItemAtPosition(position).toString();
if(branchselected.equals("ALL"))
branchselected="";
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void coursespinner()
{
// Spinner click listener
List<String> courses = new ArrayList<String>();
courses.add("ALL");
courses.add("BTech");
courses.add("MTech");
courses.add("MCA");
courses.add("PhD");
courses.add("MBA");
ArrayAdapter<String> dataAdapterbranch;
dataAdapterbranch = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,courses);
// Drop down layout style - list view with radio button
dataAdapterbranch.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnercourse.setAdapter(dataAdapterbranch);
spinnercourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
courseselected = parent.getItemAtPosition(position).toString();
if(courseselected.equals("ALL"))
courseselected="";
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
|
apache-2.0
|
ambasta/aws-sdk-cpp
|
aws-cpp-sdk-support/include/aws/support/model/AddCommunicationToCaseResult.h
|
1898
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/support/Support_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Support
{
namespace Model
{
/**
* <p>The result of the <a>AddCommunicationToCase</a> operation.</p>
*/
class AWS_SUPPORT_API AddCommunicationToCaseResult
{
public:
AddCommunicationToCaseResult();
AddCommunicationToCaseResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AddCommunicationToCaseResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>True if <a>AddCommunicationToCase</a> succeeds. Otherwise, returns an
* error.</p>
*/
inline bool GetResult() const{ return m_result; }
/**
* <p>True if <a>AddCommunicationToCase</a> succeeds. Otherwise, returns an
* error.</p>
*/
inline void SetResult(bool value) { m_result = value; }
/**
* <p>True if <a>AddCommunicationToCase</a> succeeds. Otherwise, returns an
* error.</p>
*/
inline AddCommunicationToCaseResult& WithResult(bool value) { SetResult(value); return *this;}
private:
bool m_result;
};
} // namespace Model
} // namespace Support
} // namespace Aws
|
apache-2.0
|
aayaam/website
|
contact.html
|
7041
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Contact - Business Casual - Start Bootstrap Theme</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/business-casual.css" rel="stylesheet">
<!-- Fonts -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="mybrand">
</div>
<div class="address-bar">
<img style="display:block;float:left;overflow:hidden; margin-left:40px"class"img-left" src="img/mylogo1.png" height="150" width="170">
<img style="margin-top:20px;float:centre;overflow:hidden;" class"img-left" src="img/logo1.png" height="100" width="300">
<img style="margin-top:10px;float:right;overflow:hidden;margin-right:40px" class"img-left" src="img/inst.png" height="130" width="120">
</div>
<!-- Navigation -->
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-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>
<!-- navbar-brand is hidden on larger screens, but visible when the menu is collapsed -->
<a class="navbar-brand" href="index.html">Business Casual</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="about.html">Blog</a>
</li>
<li>
<a href="events.html">Events</a>
</li>
<li>
<a href="contact.html">Parivar</a>
</li>
<li>
<a href="contact.html">Contact us</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact
<strong>
us</strong>
</h2>
<hr>
</div>
<div class="col-md-8">
<!-- Embedded Google Map using an iframe - to select your location find it on Google maps and paste the link as the iframe src. If you want to use the Google Maps API instead then have at it! -->
<iframe width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?hl=en&ie=UTF8&ll=10.7548818,78.8156087&spn=10.7548818,78.8156087&t=m&z=14&output=embed"></iframe>
</div>
<div class="col-md-4">
<p>Phone:
<strong>123 658 9874</strong>
</p>
<p>Email:
<strong><a href="mailto:[email protected]">[email protected]</a></strong>
</p>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">Contact
<strong>form</strong>
</h2>
<hr>
<p></p>
<form role="form">
<div class="row">
<div class="form-group col-lg-4">
<label>Name</label>
<input type="text" class="form-control">
</div>
<div class="form-group col-lg-4">
<label>Email Address</label>
<input type="email" class="form-control">
</div>
<div class="form-group col-lg-4">
<label>Phone Number</label>
<input type="tel" class="form-control">
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
<label>Message</label>
<textarea class="form-control" rows="6"></textarea>
</div>
<div class="form-group col-lg-12">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
apache-2.0
|
cwx521/Husky
|
src/Husky.Helpers/Enums/OnOff.cs
|
154
|
namespace Husky
{
public enum OnOff
{
[Label("关闭", CssClass = "text-danger")]
Off,
[Label("开启", CssClass = "text-success")]
On
}
}
|
apache-2.0
|
kumarsumit1/learning
|
src/main/java/com/packt/sfjd/ch11/AbsFunc2.java
|
283
|
package com.packt.sfjd.ch11;
import java.io.Serializable;
import scala.runtime.AbstractFunction2;
public class AbsFunc2 extends AbstractFunction2<Object, String, Object> implements Serializable{
@Override
public Object apply(Object arg0, String arg1) {
return true;
}
}
|
apache-2.0
|
jintou/jintou-backend
|
server/auth/index.js
|
664
|
'use strict';
import express from 'express';
import passport from 'passport';
import config from '../config/environment';
import {User} from '../sqldb';
// Passport Configuration
require('./local/passport').setup(User, config);
require('./facebook/passport').setup(User, config);
require('./google/passport').setup(User, config);
require('./twitter/passport').setup(User, config);
var router = express.Router();
router.use('/local', require('./local'));
router.use('/facebook', require('./facebook'));
router.use('/twitter', require('./twitter'));
router.use('/google', require('./google'));
router.use('/wechat', require('./wechat'));
export default router;
|
apache-2.0
|
stuffer2325/Makagiga
|
src/org/makagiga/commons/swing/MWindow.java
|
3865
|
// Copyright 2006 Konrad Twardowski
//
// 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.makagiga.commons.swing;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Insets;
import java.awt.Window;
import javax.swing.JComponent;
import javax.swing.JWindow;
import org.makagiga.commons.MApplication;
import org.makagiga.commons.UI;
/**
* @since 4.0 (org.makagiga.commons.swing package)
*/
public class MWindow extends JWindow implements MBorderLayout {
// private
private boolean respectScreenInsets = true;
private UI.HorizontalPosition horizontalPosition;
private UI.VerticalPosition verticalPosition;
// public
public MWindow() {
this(null);
}
public MWindow(final Window owner) {
super(owner);
}
public UI.HorizontalPosition getHorizontalPosition() { return horizontalPosition; }
public void setHorizontalPosition(final UI.HorizontalPosition value) {
horizontalPosition = value;
setLocation(getNewXPosition(), getLocation().y);
}
/**
* @since 4.8
*/
public boolean getRespectScreenInsets() { return respectScreenInsets; }
/**
* @since 4.8
*/
public void setRespectScreenInsets(final boolean value) { respectScreenInsets = value; }
public UI.VerticalPosition getVerticalPosition() { return verticalPosition; }
public void setVerticalPosition(final UI.VerticalPosition value) {
verticalPosition = value;
setLocation(getLocation().x, getNewYPosition());
}
@Override
public void setVisible(final boolean value) {
if (value && MApplication.getForceRTL() && !isVisible())
applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
super.setVisible(value);
}
public void showAtPosition(final UI.VerticalPosition v, final UI.HorizontalPosition h) {
showAtPosition(v, h, true);
}
/**
* @since 4.8
*/
public void showAtPosition(final UI.VerticalPosition v, final UI.HorizontalPosition h, final boolean pack) {
horizontalPosition = h;
verticalPosition = v;
if (pack)
pack();
setLocation(getNewXPosition(), getNewYPosition());
setVisible(true);
}
// MBorderLayout
/**
* @since 1.2
*/
@Override
public void addCenter(final JComponent component) {
UI.addCenter(this, component);
}
/**
* @since 1.2
*/
@Override
public void addEast(final JComponent component) {
add(component, BorderLayout.LINE_END);
}
/**
* @since 1.2
*/
@Override
public void addNorth(final JComponent component) {
add(component, BorderLayout.PAGE_START);
}
/**
* @since 1.2
*/
@Override
public void addSouth(final JComponent component) {
add(component, BorderLayout.PAGE_END);
}
/**
* @since 1.2
*/
@Override
public void addWest(final JComponent component) {
add(component, BorderLayout.LINE_START);
}
// private
private int getNewXPosition() {
Insets i = getScreenInsets();
return
(horizontalPosition == UI.HorizontalPosition.LEFT)
? i.left // left
: UI.getScreenSize().width - getWidth() - i.right; // right
}
private int getNewYPosition() {
Insets i = getScreenInsets();
return
(verticalPosition == UI.VerticalPosition.BOTTOM)
? UI.getScreenSize().height - getHeight() - i.bottom // bottom
: i.top; // top
}
private Insets getScreenInsets() {
if (respectScreenInsets)
return UI.getScreenInsets();
return new Insets(0, 0, 0, 0);
}
}
|
apache-2.0
|
bcgov/MyGovBC-MSP
|
src/app/modules/assistance/pages/review/review.component.spec.ts
|
1356
|
import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { AssistanceReviewComponent } from './review.component';
import { MspDataService } from '../../../../services/msp-data.service';
import { LocalStorageModule } from 'angular-2-local-storage';
import {RouterTestingModule} from '@angular/router/testing';
import {MspLogService} from '../../../../services/log.service';
import { ModalModule } from 'ngx-bootstrap/modal';
import {HttpClientModule} from '@angular/common/http';
import { MspCoreModule } from '../../../msp-core/msp-core.module';
describe('AssistanceReviewComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AssistanceReviewComponent],
imports: [
FormsModule,
RouterTestingModule,
HttpClientModule,
LocalStorageModule.withConfig({
prefix: 'ca.bc.gov.msp',
storageType: 'sessionStorage'
}),
ModalModule.forRoot(),
MspCoreModule
],
providers: [
MspDataService,
MspLogService
]
});
});
it ('should work', () => {
const fixture = TestBed.createComponent(AssistanceReviewComponent);
expect(fixture.componentInstance instanceof AssistanceReviewComponent).toBe(true, 'should create AssistanceReviewComponent');
});
});
|
apache-2.0
|
beckettkev/react-chat-back
|
src/utils/shared.js
|
867
|
export default class Shared {
getPrettyDate(time) {
const date = new Date((time || '').replace(/-/g,'/').replace(/[TZ]/g,' '));
const diff = (((new Date()).getTime() - date.getTime()) / 1000);
const day_diff = Math.floor(diff / 86400);
// return date for anything greater than a day
if (isNaN(day_diff) || day_diff < 0 || day_diff > 0) {
return date.getDate() + ' ' + date.toDateString().split(' ')[1];
}
return (day_diff === 0 && ((diff < 60 && 'just now') || (diff < 120 && '1 minute ago') || (diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago') || (diff < 7200 && '1 hour ago') || (diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago')))
|| (day_diff === 1 && 'Yesterday') || (day_diff < 7 && day_diff + ' days ago') || (day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago');
}
}
|
apache-2.0
|
DomDerrien/amazon-fps-gaej
|
src/com/amazonaws/fps/model/WriteOffDebtResult.java
|
7331
|
package com.amazonaws.fps.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TransactionId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="TransactionStatus" type="{http://fps.amazonaws.com/doc/2008-09-17/}TransactionStatus"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
* Generated by AWS Code Generator
* <p/>
* Tue Sep 29 03:25:23 PDT 2009
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"transactionId",
"transactionStatus"
})
@XmlRootElement(name = "WriteOffDebtResult")
public class WriteOffDebtResult {
@XmlElement(name = "TransactionId", required = true)
protected String transactionId;
@XmlElement(name = "TransactionStatus", required = true)
protected TransactionStatus transactionStatus;
/**
* Default constructor
*
*/
public WriteOffDebtResult() {
super();
}
/**
* Value constructor
*
*/
public WriteOffDebtResult(final String transactionId, final TransactionStatus transactionStatus) {
this.transactionId = transactionId;
this.transactionStatus = transactionStatus;
}
/**
* Gets the value of the transactionId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransactionId() {
return transactionId;
}
/**
* Sets the value of the transactionId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransactionId(String value) {
this.transactionId = value;
}
public boolean isSetTransactionId() {
return (this.transactionId!= null);
}
/**
* Gets the value of the transactionStatus property.
*
* @return
* possible object is
* {@link TransactionStatus }
*
*/
public TransactionStatus getTransactionStatus() {
return transactionStatus;
}
/**
* Sets the value of the transactionStatus property.
*
* @param value
* allowed object is
* {@link TransactionStatus }
*
*/
public void setTransactionStatus(TransactionStatus value) {
this.transactionStatus = value;
}
public boolean isSetTransactionStatus() {
return (this.transactionStatus!= null);
}
/**
* Sets the value of the TransactionId property.
*
* @param value
* @return
* this instance
*/
public WriteOffDebtResult withTransactionId(String value) {
setTransactionId(value);
return this;
}
/**
* Sets the value of the TransactionStatus property.
*
* @param value
* @return
* this instance
*/
public WriteOffDebtResult withTransactionStatus(TransactionStatus value) {
setTransactionStatus(value);
return this;
}
/**
*
* XML fragment representation of this object
*
* @return XML fragment for this object. Name for outer
* tag expected to be set by calling method. This fragment
* returns inner properties representation only
*/
protected String toXMLFragment() {
StringBuffer xml = new StringBuffer();
if (isSetTransactionId()) {
xml.append("<TransactionId>");
xml.append(escapeXML(getTransactionId()));
xml.append("</TransactionId>");
}
if (isSetTransactionStatus()) {
xml.append("<TransactionStatus>");
xml.append(getTransactionStatus().value());
xml.append("</TransactionStatus>");
}
return xml.toString();
}
/**
*
* Escape XML special characters
*/
private String escapeXML(String string) {
StringBuffer sb = new StringBuffer();
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
*
* JSON fragment representation of this object
*
* @return JSON fragment for this object. Name for outer
* object expected to be set by calling method. This fragment
* returns inner properties representation only
*
*/
protected String toJSONFragment() {
StringBuffer json = new StringBuffer();
boolean first = true;
if (isSetTransactionId()) {
if (!first) json.append(", ");
json.append(quoteJSON("TransactionId"));
json.append(" : ");
json.append(quoteJSON(getTransactionId()));
first = false;
}
if (isSetTransactionStatus()) {
if (!first) json.append(", ");
json.append(quoteJSON("TransactionStatus"));
json.append(" : ");
json.append(quoteJSON(getTransactionStatus().value()));
first = false;
}
return json.toString();
}
/**
*
* Quote JSON string
*/
private String quoteJSON(String string) {
StringBuffer sb = new StringBuffer();
sb.append("\"");
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < ' ') {
sb.append("\\u" + String.format("%03x", Integer.valueOf(c)));
} else {
sb.append(c);
}
}
}
sb.append("\"");
return sb.toString();
}
}
|
apache-2.0
|
brain-research/data-linter
|
README.md
|
2772
|
# Data Linter
## Summary
This code accompanies the
[NIPS 2017 ML Systems Workshop](http://learningsys.org/nips17/) paper/poster,
"The Data Linter: Lightweight, Automated Sanity Checking for ML Data Sets."
The Data Linter identifies potential issues (lints) in your ML training data.
# Using the Data Linter
## Prerequisites
You'll need the following installed to use the Data Linter:
1. Python
2. [Apache Beam](https://beam.apache.org/)
3. [TensorFlow](https://www.tensorflow.org/)
4. [Facets](https://github.com/PAIR-code/facets)
## Data Linter Demo
The easiest way to see how to use the Data Linter is to follow the demo
instructions found in `demo/README.md`.
## Running the Data Linter
Running the Data Linter requires the following steps:
1. Encoding your data in TFRecord format.
2. Generating summary statistics for those data, using Facets.
3. Running the Data Linter.
4. Using the Lint Explorer to produce the lint results.
### Creating Data in the TFRecord Format
To see how to convert CSV files to the TFRecord format, look at the example code
in `demo/convert_to_tfrecord.py`.
### Summarizing Your Data Using Facets
To see how to generate summary statistics for your data, see the example code in
`demo/summarize_data.py`.
### Executing the Data Linter
Once you have both the data and summary statistics, you can run the Data Linter
as such:
```shell
python data_linter_main.py --dataset_path PATH_TO_TFRECORDS \
--stats_path PATH_TO_FACETS_SUMMARIES --results_path PATH_FOR_SAVING_RESULTS
```
For example, if you follow the instructions in the demo folder, you'll invoke
the Data Linter like this:
```shell
python data_linter_main.py --dataset_path /tmp/adult.tfrecords \
--stats_path /tmp/adult_summary.bin \
--results_path /tmp/datalinter/results/lint_results.bin
```
### Viewing Results with the Lint Explorer
After the Data Linter is done examining your data, you can view the results
using this command:
```shell
python lint_explorer_main.py --results_path PATH_TO_RESULTS
```
For example:
```shell
python lint_explorer_main.py --results_path \
/tmp/datalinter/results/lint_results.bin
```
# Notes
The code makes use of
[Google's protobuf format](https://developers.google.com/protocol-buffers/).
The protos are defined in `protos/`.
To make it easier to run the code, we include protobuf definitions from
[TensorFlow](https://www.tensorflow.org/) and
[Facets](https://github.com/PAIR-code/facets) in this distribution.
# Support
This is not an official Google project. This project will not be supported or
maintained, and we will not accept any pull requests.
# Authors
The Data Linter was created by Nick Hynes ([email protected]) during an
internship at Google with Michael Terry ([email protected]).
|
apache-2.0
|
james-hu/jabb-core
|
src/main/java/net/sf/jabb/util/db/impl/TryDataSourceProvider.java
|
1868
|
/*
Copyright 2010 Zhengmao HU (James)
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 net.sf.jabb.util.db.impl;
import java.util.Properties;
import javax.sql.DataSource;
import net.sf.jabb.util.db.ConnectionUtility;
import net.sf.jabb.util.db.DataSourceProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 一个一个尝试。
* @author Zhengmao HU (James)
*
*/
public class TryDataSourceProvider implements DataSourceProvider {
private static final Log log = LogFactory.getLog(TryDataSourceProvider.class);
@Override
public DataSource createDataSource(String source, Properties configurationProperties, String config) {
log.warn("Properties argument ignored for: " + source);
return createDataSource(source, config);
}
@Override
public DataSource createDataSource(String source, String config) {
for (String subSource: config.split(ConnectionUtility.DELIMITORS)){
DataSource ds = ConnectionUtility.getDataSource(subSource);
if (ds != null){
log.debug("Data source '" + subSource + "' will be used for data source '" + source + "'.");
return ds;
}
}
log.error("No usable data source found for '" + source + "'.");
return null;
}
@Override
public boolean destroyDataSource(DataSource dataSource) {
return false;
}
}
|
apache-2.0
|
BeoBuzzDev/artryvis.com
|
_includes/contact_static.html
|
1952
|
<!-- Contact Section -->
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Us</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<form action="//formspree.io/[email protected]" method="POST" name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" name="_replyto" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div>
<input type="hidden" name="_subject" value="New submission!">
<input type="text" name="_gotcha" style="display:none" />
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" name="message" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
|
apache-2.0
|
fperignon/siconos
|
externals/sort/sort.h
|
57106
|
/* Copyright (c) 2010-2017 Christopher Swenson. */
/* Copyright (c) 2012 Vojtech Fried. */
/* Copyright (c) 2012 Google Inc. All Rights Reserved. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#ifndef SORT_NAME
#error "Must declare SORT_NAME"
#endif
#ifndef SORT_TYPE
#error "Must declare SORT_TYPE"
#endif
#ifndef SORT_CMP
#define SORT_CMP(x, y) ((x) < (y) ? -1 : ((x) == (y) ? 0 : 1))
#endif
#ifndef TIM_SORT_STACK_SIZE
#define TIM_SORT_STACK_SIZE 128
#endif
#ifndef SORT_SWAP
#define SORT_SWAP(x,y) {SORT_TYPE _sort_swap_temp = (x); (x) = (y); (y) = _sort_swap_temp;}
#endif
/* Common, type-agnostic functions and constants that we don't want to declare twice. */
#ifndef SORT_COMMON_H
#define SORT_COMMON_H
#ifndef MAX
#define MAX(x,y) (((x) > (y) ? (x) : (y)))
#endif
#ifndef MIN
#define MIN(x,y) (((x) < (y) ? (x) : (y)))
#endif
static int compute_minrun(const uint64_t);
/* From http://oeis.org/classic/A102549 */
static const uint64_t shell_gaps[48] = {1, 4, 10, 23, 57, 132, 301, 701, 1750, 4376, 10941, 27353, 68383, 170958, 427396, 1068491, 2671228, 6678071, 16695178, 41737946, 104344866, 260862166, 652155416, 1630388541, 4075971353LL, 10189928383LL, 25474820958LL, 63687052396LL, 159217630991LL, 398044077478LL, 995110193696LL, 2487775484241LL, 6219438710603LL, 15548596776508LL, 38871491941271LL, 97178729853178LL, 242946824632946LL, 607367061582366LL, 1518417653955916LL, 3796044134889791LL, 9490110337224478LL, 23725275843061196LL, 59313189607652991LL, 148282974019132478LL, 370707435047831196LL, 926768587619577991LL, 2316921469048944978LL, 5792303672622362446LL};
#ifndef CLZ
#ifdef __GNUC__
#define CLZ __builtin_clzll
#else
static int clzll(uint64_t);
/* adapted from Hacker's Delight */
static int clzll(uint64_t x) {
int n;
if (x == 0) {
return 64;
}
n = 0;
if (x <= 0x00000000FFFFFFFFL) {
n = n + 32;
x = x << 32;
}
if (x <= 0x0000FFFFFFFFFFFFL) {
n = n + 16;
x = x << 16;
}
if (x <= 0x00FFFFFFFFFFFFFFL) {
n = n + 8;
x = x << 8;
}
if (x <= 0x0FFFFFFFFFFFFFFFL) {
n = n + 4;
x = x << 4;
}
if (x <= 0x3FFFFFFFFFFFFFFFL) {
n = n + 2;
x = x << 2;
}
if (x <= 0x7FFFFFFFFFFFFFFFL) {
n = n + 1;
}
return n;
}
#define CLZ clzll
#endif
#endif
static __inline int compute_minrun(const uint64_t size) {
const int top_bit = 64 - CLZ(size);
const int shift = MAX(top_bit, 6) - 6;
const int minrun = size >> shift;
const uint64_t mask = (1ULL << shift) - 1;
if (mask & size) {
return minrun + 1;
}
return minrun;
}
static __inline size_t rbnd(size_t len) {
int k;
if (len < 16) {
return 2;
}
k = 62 - CLZ(len);
return 1ULL << ((2 * k) / 3);
}
#endif /* SORT_COMMON_H */
#define SORT_CONCAT(x, y) x ## _ ## y
#define SORT_MAKE_STR1(x, y) SORT_CONCAT(x,y)
#define SORT_MAKE_STR(x) SORT_MAKE_STR1(SORT_NAME,x)
#define BINARY_INSERTION_FIND SORT_MAKE_STR(binary_insertion_find)
#define BINARY_INSERTION_SORT_START SORT_MAKE_STR(binary_insertion_sort_start)
#define BINARY_INSERTION_SORT SORT_MAKE_STR(binary_insertion_sort)
#define REVERSE_ELEMENTS SORT_MAKE_STR(reverse_elements)
#define COUNT_RUN SORT_MAKE_STR(count_run)
#define CHECK_INVARIANT SORT_MAKE_STR(check_invariant)
#define TIM_SORT SORT_MAKE_STR(tim_sort)
#define TIM_SORT_RESIZE SORT_MAKE_STR(tim_sort_resize)
#define TIM_SORT_MERGE SORT_MAKE_STR(tim_sort_merge)
#define TIM_SORT_COLLAPSE SORT_MAKE_STR(tim_sort_collapse)
#define HEAP_SORT SORT_MAKE_STR(heap_sort)
#define MEDIAN SORT_MAKE_STR(median)
#define QUICK_SORT SORT_MAKE_STR(quick_sort)
#define MERGE_SORT SORT_MAKE_STR(merge_sort)
#define MERGE_SORT_IN_PLACE SORT_MAKE_STR(merge_sort_in_place)
#define MERGE_SORT_IN_PLACE_RMERGE SORT_MAKE_STR(merge_sort_in_place_rmerge)
#define MERGE_SORT_IN_PLACE_BACKMERGE SORT_MAKE_STR(merge_sort_in_place_backmerge)
#define MERGE_SORT_IN_PLACE_FRONTMERGE SORT_MAKE_STR(merge_sort_in_place_frontmerge)
#define MERGE_SORT_IN_PLACE_ASWAP SORT_MAKE_STR(merge_sort_in_place_aswap)
#define SELECTION_SORT SORT_MAKE_STR(selection_sort)
#define SHELL_SORT SORT_MAKE_STR(shell_sort)
#define QUICK_SORT_PARTITION SORT_MAKE_STR(quick_sort_partition)
#define QUICK_SORT_RECURSIVE SORT_MAKE_STR(quick_sort_recursive)
#define HEAP_SIFT_DOWN SORT_MAKE_STR(heap_sift_down)
#define HEAPIFY SORT_MAKE_STR(heapify)
#define TIM_SORT_RUN_T SORT_MAKE_STR(tim_sort_run_t)
#define TEMP_STORAGE_T SORT_MAKE_STR(temp_storage_t)
#define PUSH_NEXT SORT_MAKE_STR(push_next)
#define GRAIL_SWAP1 SORT_MAKE_STR(grail_swap1)
#define REC_STABLE_SORT SORT_MAKE_STR(rec_stable_sort)
#define GRAIL_REC_MERGE SORT_MAKE_STR(grail_rec_merge)
#define GRAIL_SORT_DYN_BUFFER SORT_MAKE_STR(grail_sort_dyn_buffer)
#define GRAIL_SORT_FIXED_BUFFER SORT_MAKE_STR(grail_sort_fixed_buffer)
#define GRAIL_COMMON_SORT SORT_MAKE_STR(grail_common_sort)
#define GRAIL_SORT SORT_MAKE_STR(grail_sort)
#define GRAIL_COMBINE_BLOCKS SORT_MAKE_STR(grail_combine_blocks)
#define GRAIL_LAZY_STABLE_SORT SORT_MAKE_STR(grail_lazy_stable_sort)
#define GRAIL_MERGE_WITHOUT_BUFFER SORT_MAKE_STR(grail_merge_without_buffer)
#define GRAIL_ROTATE SORT_MAKE_STR(grail_rotate)
#define GRAIL_BIN_SEARCH_LEFT SORT_MAKE_STR(grail_bin_search_left)
#define GRAIL_BUILD_BLOCKS SORT_MAKE_STR(grail_build_blocks)
#define GRAIL_FIND_KEYS SORT_MAKE_STR(grail_find_keys)
#define GRAIL_MERGE_BUFFERS_LEFT_WITH_X_BUF SORT_MAKE_STR(grail_merge_buffers_left_with_x_buf)
#define GRAIL_BIN_SEARCH_RIGHT SORT_MAKE_STR(grail_bin_search_right)
#define GRAIL_MERGE_BUFFERS_LEFT SORT_MAKE_STR(grail_merge_buffers_left)
#define GRAIL_SMART_MERGE_WITH_X_BUF SORT_MAKE_STR(grail_smart_merge_with_x_buf)
#define GRAIL_MERGE_LEFT_WITH_X_BUF SORT_MAKE_STR(grail_merge_left_with_x_buf)
#define GRAIL_SMART_MERGE_WITHOUT_BUFFER SORT_MAKE_STR(grail_smart_merge_without_buffer)
#define GRAIL_SMART_MERGE_WITH_BUFFER SORT_MAKE_STR(grail_smart_merge_with_buffer)
#define GRAIL_MERGE_RIGHT SORT_MAKE_STR(grail_merge_right)
#define GRAIL_MERGE_LEFT SORT_MAKE_STR(grail_merge_left)
#define GRAIL_SWAP_N SORT_MAKE_STR(grail_swap_n)
#define SQRT_SORT SORT_MAKE_STR(sqrt_sort)
#define SQRT_SORT_BUILD_BLOCKS SORT_MAKE_STR(sqrt_sort_build_blocks)
#define SQRT_SORT_MERGE_BUFFERS_LEFT_WITH_X_BUF SORT_MAKE_STR(sqrt_sort_merge_buffers_left_with_x_buf)
#define SQRT_SORT_MERGE_DOWN SORT_MAKE_STR(sqrt_sort_merge_down)
#define SQRT_SORT_MERGE_LEFT_WITH_X_BUF SORT_MAKE_STR(sqrt_sort_merge_left_with_x_buf)
#define SQRT_SORT_MERGE_RIGHT SORT_MAKE_STR(sqrt_sort_merge_right)
#define SQRT_SORT_SWAP_N SORT_MAKE_STR(sqrt_sort_swap_n)
#define SQRT_SORT_SWAP_1 SORT_MAKE_STR(sqrt_sort_swap_1)
#define SQRT_SORT_SMART_MERGE_WITH_X_BUF SORT_MAKE_STR(sqrt_sort_smart_merge_with_x_buf)
#define SQRT_SORT_SORT_INS SORT_MAKE_STR(sqrt_sort_sort_ins)
#define SQRT_SORT_COMBINE_BLOCKS SORT_MAKE_STR(sqrt_sort_combine_blocks)
#define SQRT_SORT_COMMON_SORT SORT_MAKE_STR(sqrt_sort_common_sort)
#define BUBBLE_SORT SORT_MAKE_STR(bubble_sort)
#ifndef MAX
#define MAX(x,y) (((x) > (y) ? (x) : (y)))
#endif
#ifndef MIN
#define MIN(x,y) (((x) < (y) ? (x) : (y)))
#endif
typedef struct {
size_t start;
size_t length;
} TIM_SORT_RUN_T;
void SHELL_SORT(SORT_TYPE *dst, const size_t size);
void BINARY_INSERTION_SORT(SORT_TYPE *dst, const size_t size);
void HEAP_SORT(SORT_TYPE *dst, const size_t size);
void QUICK_SORT(SORT_TYPE *dst, const size_t size);
void MERGE_SORT(SORT_TYPE *dst, const size_t size);
void MERGE_SORT_IN_PLACE(SORT_TYPE *dst, const size_t size);
void SELECTION_SORT(SORT_TYPE *dst, const size_t size);
void TIM_SORT(SORT_TYPE *dst, const size_t size);
void BUBBLE_SORT(SORT_TYPE *dst, const size_t size);
void MERGE_SORT_IN_PLACE_ASWAP(SORT_TYPE * dst1, SORT_TYPE * dst2, size_t len) ;
void MERGE_SORT_IN_PLACE_FRONTMERGE(SORT_TYPE *dst1, size_t l1, SORT_TYPE *dst2, size_t l2);
size_t MERGE_SORT_IN_PLACE_BACKMERGE(SORT_TYPE * dst1, size_t l1, SORT_TYPE * dst2, size_t l2);
void MERGE_SORT_IN_PLACE_RMERGE(SORT_TYPE *dst, size_t len, size_t lp, size_t r);
/* Shell sort implementation based on Wikipedia article
http://en.wikipedia.org/wiki/Shell_sort
*/
void SHELL_SORT(SORT_TYPE *dst, const size_t size) {
/* don't bother sorting an array of size 0 or 1 */
if (size <= 1) {
return;
}
/* TODO: binary search to find first gap? */
int inci = 47;
size_t inc = shell_gaps[inci];
size_t i;
while (inc > (size >> 1)) {
inc = shell_gaps[--inci];
}
while (1) {
for (i = inc; i < size; i++) {
SORT_TYPE temp = dst[i];
size_t j = i;
while ((j >= inc) && (SORT_CMP(dst[j - inc], temp) > 0)) {
dst[j] = dst[j - inc];
j -= inc;
}
dst[j] = temp;
}
if (inc == 1) {
break;
}
inc = shell_gaps[--inci];
}
}
/* Function used to do a binary search for binary insertion sort */
static __inline size_t BINARY_INSERTION_FIND(SORT_TYPE *dst, const SORT_TYPE x,
const size_t size) {
size_t l, c, r;
SORT_TYPE cx;
l = 0;
r = size - 1;
c = r >> 1;
/* check for out of bounds at the beginning. */
if (SORT_CMP(x, dst[0]) < 0) {
return 0;
} else if (SORT_CMP(x, dst[r]) > 0) {
return r;
}
cx = dst[c];
while (1) {
const int val = SORT_CMP(x, cx);
if (val < 0) {
if (c - l <= 1) {
return c;
}
r = c;
} else { /* allow = for stability. The binary search favors the right. */
if (r - c <= 1) {
return c + 1;
}
l = c;
}
c = l + ((r - l) >> 1);
cx = dst[c];
}
}
/* Binary insertion sort, but knowing that the first "start" entries are sorted. Used in timsort. */
static void BINARY_INSERTION_SORT_START(SORT_TYPE *dst, const size_t start, const size_t size) {
size_t i;
for (i = start; i < size; i++) {
size_t j;
SORT_TYPE x;
size_t location;
/* If this entry is already correct, just move along */
if (SORT_CMP(dst[i - 1], dst[i]) <= 0) {
continue;
}
/* Else we need to find the right place, shift everything over, and squeeze in */
x = dst[i];
location = BINARY_INSERTION_FIND(dst, x, i);
for (j = i - 1; j >= location; j--) {
dst[j + 1] = dst[j];
if (j == 0) { /* check edge case because j is unsigned */
break;
}
}
dst[location] = x;
}
}
/* Binary insertion sort */
void BINARY_INSERTION_SORT(SORT_TYPE *dst, const size_t size) {
/* don't bother sorting an array of size <= 1 */
if (size <= 1) {
return;
}
BINARY_INSERTION_SORT_START(dst, 1, size);
}
/* Selection sort */
void SELECTION_SORT(SORT_TYPE *dst, const size_t size) {
/* don't bother sorting an array of size <= 1 */
if (size <= 1) {
return;
}
size_t i;
size_t j;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (SORT_CMP(dst[j], dst[i]) < 0) {
SORT_SWAP(dst[i], dst[j]);
}
}
}
}
/* In-place mergesort */
void MERGE_SORT_IN_PLACE_ASWAP(SORT_TYPE * dst1, SORT_TYPE * dst2, size_t len) {
do {
SORT_SWAP(*dst1, *dst2);
dst1++;
dst2++;
} while (--len);
}
void MERGE_SORT_IN_PLACE_FRONTMERGE(SORT_TYPE *dst1, size_t l1, SORT_TYPE *dst2, size_t l2) {
SORT_TYPE *dst0 = dst2 - l1;
if (SORT_CMP(dst1[l1 - 1], dst2[0]) <= 0) {
MERGE_SORT_IN_PLACE_ASWAP(dst1, dst0, l1);
return;
}
do {
while (SORT_CMP(*dst2, *dst1) > 0) {
SORT_SWAP(*dst1, *dst0);
dst1++;
dst0++;
if (--l1 == 0) {
return;
}
}
SORT_SWAP(*dst2, *dst0);
dst2++;
dst0++;
} while (--l2);
do {
SORT_SWAP(*dst1, *dst0);
dst1++;
dst0++;
} while (--l1);
}
size_t MERGE_SORT_IN_PLACE_BACKMERGE(SORT_TYPE * dst1, size_t l1, SORT_TYPE * dst2, size_t l2) {
size_t res;
SORT_TYPE *dst0 = dst2 + l1;
if (SORT_CMP(dst1[1 - l1], dst2[0]) >= 0) {
MERGE_SORT_IN_PLACE_ASWAP(dst1 - l1 + 1, dst0 - l1 + 1, l1);
return l1;
}
do {
while (SORT_CMP(*dst2, *dst1) < 0) {
SORT_SWAP(*dst1, *dst0);
dst1--;
dst0--;
if (--l1 == 0) {
return 0;
}
}
SORT_SWAP(*dst2, *dst0);
dst2--;
dst0--;
} while (--l2);
res = l1;
do {
SORT_SWAP(*dst1, *dst0);
dst1--;
dst0--;
} while (--l1);
return res;
}
/* merge dst[p0..p1) by buffer dst[p1..p1+r) */
void MERGE_SORT_IN_PLACE_RMERGE(SORT_TYPE *dst, size_t len, size_t lp, size_t r) {
size_t i, lq;
int cv;
if (SORT_CMP(dst[lp], dst[lp - 1]) >= 0) {
return;
}
lq = lp;
for (i = 0; i < len; i += r) {
/* select smallest dst[p0+n*r] */
size_t q = i, j;
for (j = lp; j <= lq; j += r) {
cv = SORT_CMP(dst[j], dst[q]);
if (cv == 0) {
cv = SORT_CMP(dst[j + r - 1], dst[q + r - 1]);
}
if (cv < 0) {
q = j;
}
}
if (q != i) {
MERGE_SORT_IN_PLACE_ASWAP(dst + i, dst + q, r); /* swap it with current position */
if (q == lq && q < (len - r)) {
lq += r;
}
}
if (i != 0 && SORT_CMP(dst[i], dst[i - 1]) < 0) {
MERGE_SORT_IN_PLACE_ASWAP(dst + len, dst + i, r); /* swap current position with buffer */
MERGE_SORT_IN_PLACE_BACKMERGE(dst + (len + r - 1), r, dst + (i - 1),
r); /* buffer :merge: dst[i-r..i) -> dst[i-r..i+r) */
}
if (lp == i) {
lp += r;
}
}
}
/* In-place Merge Sort implementation. (c)2012, Andrey Astrelin, [email protected] */
void MERGE_SORT_IN_PLACE(SORT_TYPE *dst, const size_t len) {
/* don't bother sorting an array of size <= 1 */
if (len <= 1) {
return;
}
size_t r = rbnd(len);
size_t lr = (len / r - 1) * r, p, m, q, q1, p0;
SORT_TYPE *dst1 = dst - 1;
if (len < 16) {
BINARY_INSERTION_SORT(dst, len);
return;
}
for (p = 2; p <= lr; p += 2) {
dst1 += 2;
if (SORT_CMP(dst1[0], dst1[-1]) < 0) {
SORT_SWAP(dst1[0], dst1[-1]);
}
if (p & 2) {
continue;
}
m = len - p;
q = 2;
while ((p & q) == 0) {
if (SORT_CMP(dst1[1 - q], dst1[-q]) < 0) {
break;
}
q *= 2;
}
if (p & q) {
continue;
}
if (q < m) {
p0 = len - q;
MERGE_SORT_IN_PLACE_ASWAP(dst + p - q, dst + p0, q);
for (;;) {
q1 = 2 * q;
if ((q1 > m) || (p & q1)) {
break;
}
p0 = len - q1;
MERGE_SORT_IN_PLACE_FRONTMERGE(dst + (p - q1), q, dst + p0 + q, q);
q = q1;
}
MERGE_SORT_IN_PLACE_BACKMERGE(dst + (len - 1), q, dst1 - q, q);
q *= 2;
}
q1 = q;
while (q1 > m) {
q1 /= 2;
}
while ((q & p) == 0) {
q *= 2;
MERGE_SORT_IN_PLACE_RMERGE(dst + (p - q), q, q / 2, q1);
}
}
q1 = 0;
for (q = r; q < lr; q *= 2) {
if ((lr & q) != 0) {
q1 += q;
if (q1 != q) {
MERGE_SORT_IN_PLACE_RMERGE(dst + (lr - q1), q1, q, r);
}
}
}
m = len - lr;
MERGE_SORT_IN_PLACE(dst + lr, m);
MERGE_SORT_IN_PLACE_ASWAP(dst, dst + lr, m);
m += MERGE_SORT_IN_PLACE_BACKMERGE(dst + (m - 1), m, dst + (lr - 1), lr - m);
MERGE_SORT_IN_PLACE(dst, m);
}
/* Standard merge sort */
void MERGE_SORT(SORT_TYPE *dst, const size_t size) {
SORT_TYPE *newdst;
const size_t middle = size / 2;
size_t out = 0;
size_t i = 0;
size_t j = middle;
/* don't bother sorting an array of size <= 1 */
if (size <= 1) {
return;
}
if (size < 16) {
BINARY_INSERTION_SORT(dst, size);
return;
}
MERGE_SORT(dst, middle);
MERGE_SORT(&dst[middle], size - middle);
newdst = (SORT_TYPE *) malloc(size * sizeof(SORT_TYPE));
while (out != size) {
if (i < middle) {
if (j < size) {
if (SORT_CMP(dst[i], dst[j]) <= 0) {
newdst[out] = dst[i++];
} else {
newdst[out] = dst[j++];
}
} else {
newdst[out] = dst[i++];
}
} else {
newdst[out] = dst[j++];
}
out++;
}
memcpy(dst, newdst, size * sizeof(SORT_TYPE));
free(newdst);
}
/* Quick sort: based on wikipedia */
static __inline size_t QUICK_SORT_PARTITION(SORT_TYPE *dst, const size_t left,
const size_t right, const size_t pivot) {
SORT_TYPE value = dst[pivot];
size_t index = left;
size_t i;
int not_all_same = 0;
/* move the pivot to the right */
SORT_SWAP(dst[pivot], dst[right]);
for (i = left; i < right; i++) {
int cmp = SORT_CMP(dst[i], value);
/* check if everything is all the same */
not_all_same |= cmp;
if (cmp < 0) {
SORT_SWAP(dst[i], dst[index]);
index++;
}
}
SORT_SWAP(dst[right], dst[index]);
/* avoid degenerate case */
if (not_all_same == 0) {
return SIZE_MAX;
}
return index;
}
/* Return the median index of the objects at the three indices. */
static __inline size_t MEDIAN(const SORT_TYPE *dst, const size_t a, const size_t b,
const size_t c) {
const int AB = SORT_CMP(dst[a], dst[b]) < 0;
if (AB) {
/* a < b */
const int BC = SORT_CMP(dst[b], dst[c]) < 0;
if (BC) {
/* a < b < c */
return b;
} else {
/* a < b, c < b */
const int AC = SORT_CMP(dst[a], dst[c]) < 0;
if (AC) {
/* a < c < b */
return c;
} else {
/* c < a < b */
return a;
}
}
} else {
/* b < a */
const int AC = SORT_CMP(dst[a], dst[b]) < 0;
if (AC) {
/* b < a < c */
return a;
} else {
/* b < a, c < a */
const int BC = SORT_CMP(dst[b], dst[c]) < 0;
if (BC) {
/* b < c < a */
return c;
} else {
/* c < b < a */
return b;
}
}
}
}
static void QUICK_SORT_RECURSIVE(SORT_TYPE *dst, const size_t left, const size_t right) {
size_t pivot;
size_t new_pivot;
if (right <= left) {
return;
}
if ((right - left + 1U) < 16U) {
BINARY_INSERTION_SORT(&dst[left], right - left + 1U);
return;
}
pivot = left + ((right - left) >> 1);
/* this seems to perform worse by a small amount... ? */
/* pivot = MEDIAN(dst, left, pivot, right); */
new_pivot = QUICK_SORT_PARTITION(dst, left, right, pivot);
/* check for partition all equal */
if (new_pivot == SIZE_MAX) {
return;
}
QUICK_SORT_RECURSIVE(dst, left, new_pivot - 1U);
QUICK_SORT_RECURSIVE(dst, new_pivot + 1U, right);
}
void QUICK_SORT(SORT_TYPE *dst, const size_t size) {
/* don't bother sorting an array of size 1 */
if (size <= 1) {
return;
}
QUICK_SORT_RECURSIVE(dst, 0U, size - 1U);
}
/* timsort implementation, based on timsort.txt */
static __inline void REVERSE_ELEMENTS(SORT_TYPE *dst, size_t start, size_t end) {
while (1) {
if (start >= end) {
return;
}
SORT_SWAP(dst[start], dst[end]);
start++;
end--;
}
}
static size_t COUNT_RUN(SORT_TYPE *dst, const size_t start, const size_t size) {
size_t curr;
if (size - start == 1) {
return 1;
}
if (start >= size - 2) {
if (SORT_CMP(dst[size - 2], dst[size - 1]) > 0) {
SORT_SWAP(dst[size - 2], dst[size - 1]);
}
return 2;
}
curr = start + 2;
if (SORT_CMP(dst[start], dst[start + 1]) <= 0) {
/* increasing run */
while (1) {
if (curr == size - 1) {
break;
}
if (SORT_CMP(dst[curr - 1], dst[curr]) > 0) {
break;
}
curr++;
}
return curr - start;
} else {
/* decreasing run */
while (1) {
if (curr == size - 1) {
break;
}
if (SORT_CMP(dst[curr - 1], dst[curr]) <= 0) {
break;
}
curr++;
}
/* reverse in-place */
REVERSE_ELEMENTS(dst, start, curr - 1);
return curr - start;
}
}
static int CHECK_INVARIANT(TIM_SORT_RUN_T *stack, const int stack_curr) {
size_t A, B, C;
if (stack_curr < 2) {
return 1;
}
if (stack_curr == 2) {
const size_t A1 = stack[stack_curr - 2].length;
const size_t B1 = stack[stack_curr - 1].length;
if (A1 <= B1) {
return 0;
}
return 1;
}
A = stack[stack_curr - 3].length;
B = stack[stack_curr - 2].length;
C = stack[stack_curr - 1].length;
if ((A <= B + C) || (B <= C)) {
return 0;
}
return 1;
}
typedef struct {
size_t alloc;
SORT_TYPE *storage;
} TEMP_STORAGE_T;
static void TIM_SORT_RESIZE(TEMP_STORAGE_T *store, const size_t new_size) {
if (store->alloc < new_size) {
SORT_TYPE *tempstore = (SORT_TYPE *)realloc(store->storage, new_size * sizeof(SORT_TYPE));
if (tempstore == NULL) {
fprintf(stderr, "Error allocating temporary storage for tim sort: need %lu bytes",
(unsigned long)(sizeof(SORT_TYPE) * new_size));
exit(1);
}
store->storage = tempstore;
store->alloc = new_size;
}
}
static void TIM_SORT_MERGE(SORT_TYPE *dst, const TIM_SORT_RUN_T *stack, const int stack_curr,
TEMP_STORAGE_T *store) {
const size_t A = stack[stack_curr - 2].length;
const size_t B = stack[stack_curr - 1].length;
const size_t curr = stack[stack_curr - 2].start;
SORT_TYPE *storage;
size_t i, j, k;
TIM_SORT_RESIZE(store, MIN(A, B));
storage = store->storage;
/* left merge */
if (A < B) {
memcpy(storage, &dst[curr], A * sizeof(SORT_TYPE));
i = 0;
j = curr + A;
for (k = curr; k < curr + A + B; k++) {
if ((i < A) && (j < curr + A + B)) {
if (SORT_CMP(storage[i], dst[j]) <= 0) {
dst[k] = storage[i++];
} else {
dst[k] = dst[j++];
}
} else if (i < A) {
dst[k] = storage[i++];
} else {
break;
}
}
} else {
/* right merge */
memcpy(storage, &dst[curr + A], B * sizeof(SORT_TYPE));
i = B;
j = curr + A;
k = curr + A + B;
while (k-- > curr) {
if ((i > 0) && (j > curr)) {
if (SORT_CMP(dst[j - 1], storage[i - 1]) > 0) {
dst[k] = dst[--j];
} else {
dst[k] = storage[--i];
}
} else if (i > 0) {
dst[k] = storage[--i];
} else {
break;
}
}
}
}
static int TIM_SORT_COLLAPSE(SORT_TYPE *dst, TIM_SORT_RUN_T *stack, int stack_curr,
TEMP_STORAGE_T *store, const size_t size) {
while (1) {
size_t A, B, C, D;
int ABC, BCD, CD;
/* if the stack only has one thing on it, we are done with the collapse */
if (stack_curr <= 1) {
break;
}
/* if this is the last merge, just do it */
if ((stack_curr == 2) && (stack[0].length + stack[1].length == size)) {
TIM_SORT_MERGE(dst, stack, stack_curr, store);
stack[0].length += stack[1].length;
stack_curr--;
break;
}
/* check if the invariant is off for a stack of 2 elements */
else if ((stack_curr == 2) && (stack[0].length <= stack[1].length)) {
TIM_SORT_MERGE(dst, stack, stack_curr, store);
stack[0].length += stack[1].length;
stack_curr--;
break;
} else if (stack_curr == 2) {
break;
}
B = stack[stack_curr - 3].length;
C = stack[stack_curr - 2].length;
D = stack[stack_curr - 1].length;
if (stack_curr >= 4) {
A = stack[stack_curr - 4].length;
ABC = (A <= B + C);
} else {
ABC = 0;
}
BCD = (B <= C + D) || ABC;
CD = (C <= D);
/* Both invariants are good */
if (!BCD && !CD) {
break;
}
/* left merge */
if (BCD && !CD) {
TIM_SORT_MERGE(dst, stack, stack_curr - 1, store);
stack[stack_curr - 3].length += stack[stack_curr - 2].length;
stack[stack_curr - 2] = stack[stack_curr - 1];
stack_curr--;
} else {
/* right merge */
TIM_SORT_MERGE(dst, stack, stack_curr, store);
stack[stack_curr - 2].length += stack[stack_curr - 1].length;
stack_curr--;
}
}
return stack_curr;
}
static __inline int PUSH_NEXT(SORT_TYPE *dst,
const size_t size,
TEMP_STORAGE_T *store,
const size_t minrun,
TIM_SORT_RUN_T *run_stack,
size_t *stack_curr,
size_t *curr) {
size_t len = COUNT_RUN(dst, *curr, size);
size_t run = minrun;
if (run > size - *curr) {
run = size - *curr;
}
if (run > len) {
BINARY_INSERTION_SORT_START(&dst[*curr], len, run);
len = run;
}
run_stack[*stack_curr].start = *curr;
run_stack[*stack_curr].length = len;
(*stack_curr)++;
*curr += len;
if (*curr == size) {
/* finish up */
while (*stack_curr > 1) {
TIM_SORT_MERGE(dst, run_stack, *stack_curr, store);
run_stack[*stack_curr - 2].length += run_stack[*stack_curr - 1].length;
(*stack_curr)--;
}
if (store->storage != NULL) {
free(store->storage);
store->storage = NULL;
}
return 0;
}
return 1;
}
void TIM_SORT(SORT_TYPE *dst, const size_t size) {
size_t minrun;
TEMP_STORAGE_T _store, *store;
TIM_SORT_RUN_T run_stack[TIM_SORT_STACK_SIZE];
size_t stack_curr = 0;
size_t curr = 0;
/* don't bother sorting an array of size 1 */
if (size <= 1) {
return;
}
if (size < 64) {
BINARY_INSERTION_SORT(dst, size);
return;
}
/* compute the minimum run length */
minrun = compute_minrun(size);
/* temporary storage for merges */
store = &_store;
store->alloc = 0;
store->storage = NULL;
if (!PUSH_NEXT(dst, size, store, minrun, run_stack, &stack_curr, &curr)) {
return;
}
if (!PUSH_NEXT(dst, size, store, minrun, run_stack, &stack_curr, &curr)) {
return;
}
if (!PUSH_NEXT(dst, size, store, minrun, run_stack, &stack_curr, &curr)) {
return;
}
while (1) {
if (!CHECK_INVARIANT(run_stack, stack_curr)) {
stack_curr = TIM_SORT_COLLAPSE(dst, run_stack, stack_curr, store, size);
continue;
}
if (!PUSH_NEXT(dst, size, store, minrun, run_stack, &stack_curr, &curr)) {
return;
}
}
}
/* heap sort: based on wikipedia */
static __inline void HEAP_SIFT_DOWN(SORT_TYPE *dst, const size_t start, const size_t end) {
size_t root = start;
while ((root << 1) <= end) {
size_t child = root << 1;
if ((child < end) && (SORT_CMP(dst[child], dst[child + 1]) < 0)) {
child++;
}
if (SORT_CMP(dst[root], dst[child]) < 0) {
SORT_SWAP(dst[root], dst[child]);
root = child;
} else {
return;
}
}
}
static __inline void HEAPIFY(SORT_TYPE *dst, const size_t size) {
size_t start = size >> 1;
while (1) {
HEAP_SIFT_DOWN(dst, start, size - 1);
if (start == 0) {
break;
}
start--;
}
}
void HEAP_SORT(SORT_TYPE *dst, const size_t size) {
/* don't bother sorting an array of size <= 1 */
if (size <= 1) {
return;
}
size_t end = size - 1;
HEAPIFY(dst, size);
while (end > 0) {
SORT_SWAP(dst[end], dst[0]);
HEAP_SIFT_DOWN(dst, 0, end - 1);
end--;
}
}
/********* Sqrt sorting *********************************/
/* */
/* (c) 2014 by Andrey Astrelin */
/* */
/* */
/* Stable sorting that works in O(N*log(N)) worst time */
/* and uses O(sqrt(N)) extra memory */
/* */
/* Define SORT_TYPE and SORT_CMP */
/* and then call SqrtSort() function */
/* */
/*********************************************************/
#define SORT_CMP_A(a,b) SORT_CMP(*(a),*(b))
static __inline void SQRT_SORT_SWAP_1(SORT_TYPE *a, SORT_TYPE *b) {
SORT_TYPE c = *a;
*a++ = *b;
*b++ = c;
}
static __inline void SQRT_SORT_SWAP_N(SORT_TYPE *a, SORT_TYPE *b, int n) {
while (n--) {
SQRT_SORT_SWAP_1(a++, b++);
}
}
static void SQRT_SORT_MERGE_RIGHT(SORT_TYPE *arr, int L1, int L2, int M) {
int p0 = L1 + L2 + M - 1, p2 = L1 + L2 - 1, p1 = L1 - 1;
while (p1 >= 0) {
if (p2 < L1 || SORT_CMP_A(arr + p1, arr + p2) > 0) {
arr[p0--] = arr[p1--];
} else {
arr[p0--] = arr[p2--];
}
}
if (p2 != p0) while (p2 >= L1) {
arr[p0--] = arr[p2--];
}
}
/* arr[M..-1] - free, arr[0,L1-1]++arr[L1,L1+L2-1] -> arr[M,M+L1+L2-1] */
static void SQRT_SORT_MERGE_LEFT_WITH_X_BUF(SORT_TYPE *arr, int L1, int L2, int M) {
int p0 = 0, p1 = L1;
L2 += L1;
while (p1 < L2) {
if (p0 == L1 || SORT_CMP_A(arr + p0, arr + p1) > 0) {
arr[M++] = arr[p1++];
} else {
arr[M++] = arr[p0++];
}
}
if (M != p0) while (p0 < L1) {
arr[M++] = arr[p0++];
}
}
/* arr[0,L1-1] ++ arr2[0,L2-1] -> arr[-L1,L2-1], arr2 is "before" arr1 */
static void SQRT_SORT_MERGE_DOWN(SORT_TYPE *arr, SORT_TYPE *arr2, int L1, int L2) {
int p0 = 0, p1 = 0, M = -L2;
while (p1 < L2) {
if (p0 == L1 || SORT_CMP_A(arr + p0, arr2 + p1) >= 0) {
arr[M++] = arr2[p1++];
} else {
arr[M++] = arr[p0++];
}
}
if (M != p0) while (p0 < L1) {
arr[M++] = arr[p0++];
}
}
static void SQRT_SORT_SMART_MERGE_WITH_X_BUF(SORT_TYPE *arr, int *alen1, int *atype, int len2,
int lkeys) {
int p0 = -lkeys, p1 = 0, p2 = *alen1, q1 = p2, q2 = p2 + len2;
int ftype = 1 - *atype; /* 1 if inverted */
while (p1 < q1 && p2 < q2) {
if (SORT_CMP_A(arr + p1, arr + p2) - ftype < 0) {
arr[p0++] = arr[p1++];
} else {
arr[p0++] = arr[p2++];
}
}
if (p1 < q1) {
*alen1 = q1 - p1;
while (p1 < q1) {
arr[--q2] = arr[--q1];
}
} else {
*alen1 = q2 - p2;
*atype = ftype;
}
}
/*
arr - starting array. arr[-lblock..-1] - buffer (if havebuf).
lblock - length of regular blocks. First nblocks are stable sorted by 1st elements and key-coded
keys - arrays of keys, in same order as blocks. key<midkey means stream A
nblock2 are regular blocks from stream A. llast is length of last (irregular) block from stream B, that should go before nblock2 blocks.
llast=0 requires nblock2=0 (no irregular blocks). llast>0, nblock2=0 is possible.
*/
static void SQRT_SORT_MERGE_BUFFERS_LEFT_WITH_X_BUF(int *keys, int midkey, SORT_TYPE *arr,
int nblock, int lblock, int nblock2, int llast) {
int l, prest, lrest, frest, pidx, cidx, fnext;
if (nblock == 0) {
l = nblock2 * lblock;
SQRT_SORT_MERGE_LEFT_WITH_X_BUF(arr, l, llast, -lblock);
return;
}
lrest = lblock;
frest = keys[0] < midkey ? 0 : 1;
pidx = lblock;
for (cidx = 1; cidx < nblock; cidx++, pidx += lblock) {
prest = pidx - lrest;
fnext = keys[cidx] < midkey ? 0 : 1;
if (fnext == frest) {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
prest = pidx;
lrest = lblock;
} else {
SQRT_SORT_SMART_MERGE_WITH_X_BUF(arr + prest, &lrest, &frest, lblock, lblock);
}
}
prest = pidx - lrest;
if (llast) {
if (frest) {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
prest = pidx;
lrest = lblock * nblock2;
frest = 0;
} else {
lrest += lblock * nblock2;
}
SQRT_SORT_MERGE_LEFT_WITH_X_BUF(arr + prest, lrest, llast, -lblock);
} else {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
}
}
/*
build blocks of length K
input: [-K,-1] elements are buffer
output: first K elements are buffer, blocks 2*K and last subblock sorted
*/
static void SQRT_SORT_BUILD_BLOCKS(SORT_TYPE *arr, int L, int K) {
int m, u, h, p0, p1, rest, restk, p;
for (m = 1; m < L; m += 2) {
u = 0;
if (SORT_CMP_A(arr + (m - 1), arr + m) > 0) {
u = 1;
}
arr[m - 3] = arr[m - 1 + u];
arr[m - 2] = arr[m - u];
}
if (L % 2) {
arr[L - 3] = arr[L - 1];
}
arr -= 2;
for (h = 2; h < K; h *= 2) {
p0 = 0;
p1 = L - 2 * h;
while (p0 <= p1) {
SQRT_SORT_MERGE_LEFT_WITH_X_BUF(arr + p0, h, h, -h);
p0 += 2 * h;
}
rest = L - p0;
if (rest > h) {
SQRT_SORT_MERGE_LEFT_WITH_X_BUF(arr + p0, h, rest - h, -h);
} else {
for (; p0 < L; p0++) {
arr[p0 - h] = arr[p0];
}
}
arr -= h;
}
restk = L % (2 * K);
p = L - restk;
if (restk <= K) {
memcpy(arr + p + K, arr + p, restk * sizeof(SORT_TYPE));
} else {
SQRT_SORT_MERGE_RIGHT(arr + p, K, restk - K, K);
}
while (p > 0) {
p -= 2 * K;
SQRT_SORT_MERGE_RIGHT(arr + p, K, K, K);
}
}
static void SQRT_SORT_SORT_INS(SORT_TYPE *arr, int len) {
int i, j;
for (i = 1; i < len; i++) {
for (j = i - 1; j >= 0 && SORT_CMP_A(arr + (j + 1), arr + j) < 0; j--) {
SQRT_SORT_SWAP_1(arr + j, arr + (j + 1));
}
}
}
/*
keys are on the left of arr. Blocks of length LL combined. We'll combine them in pairs
LL and nkeys are powers of 2. (2*LL/lblock) keys are guarantied
*/
static void SQRT_SORT_COMBINE_BLOCKS(SORT_TYPE *arr, int len, int LL, int lblock, int *tags) {
int M, b, NBlk, midkey, lrest, u, i, p, v, kc, nbl2, llast;
SORT_TYPE *arr1;
M = len / (2 * LL);
lrest = len % (2 * LL);
if (lrest <= LL) {
len -= lrest;
lrest = 0;
}
for (b = 0; b <= M; b++) {
if (b == M && lrest == 0) {
break;
}
arr1 = arr + b * 2 * LL;
NBlk = (b == M ? lrest : 2 * LL) / lblock;
u = NBlk + (b == M ? 1 : 0);
for (i = 0; i <= u; i++) {
tags[i] = i;
}
midkey = LL / lblock;
for (u = 1; u < NBlk; u++) {
p = u - 1;
for (v = u; v < NBlk; v++) {
kc = SORT_CMP_A(arr1 + p * lblock, arr1 + v * lblock);
if (kc > 0 || (kc == 0 && tags[p] > tags[v])) {
p = v;
}
}
if (p != u - 1) {
SQRT_SORT_SWAP_N(arr1 + (u - 1)*lblock, arr1 + p * lblock, lblock);
i = tags[u - 1];
tags[u - 1] = tags[p];
tags[p] = i;
}
}
nbl2 = llast = 0;
if (b == M) {
llast = lrest % lblock;
}
if (llast != 0) {
while (nbl2 < NBlk && SORT_CMP_A(arr1 + NBlk * lblock, arr1 + (NBlk - nbl2 - 1)*lblock) < 0) {
nbl2++;
}
}
SQRT_SORT_MERGE_BUFFERS_LEFT_WITH_X_BUF(tags, midkey, arr1, NBlk - nbl2, lblock, nbl2, llast);
}
for (p = len; --p >= 0;) {
arr[p] = arr[p - lblock];
}
}
static void SQRT_SORT_COMMON_SORT(SORT_TYPE *arr, int Len, SORT_TYPE *extbuf, int *Tags) {
int lblock, cbuf;
if (Len < 16) {
SQRT_SORT_SORT_INS(arr, Len);
return;
}
lblock = 1;
while (lblock * lblock < Len) {
lblock *= 2;
}
memcpy(extbuf, arr, lblock * sizeof(SORT_TYPE));
SQRT_SORT_COMMON_SORT(extbuf, lblock, arr, Tags);
SQRT_SORT_BUILD_BLOCKS(arr + lblock, Len - lblock, lblock);
cbuf = lblock;
while (Len > (cbuf *= 2)) {
SQRT_SORT_COMBINE_BLOCKS(arr + lblock, Len - lblock, cbuf, lblock, Tags);
}
SQRT_SORT_MERGE_DOWN(arr + lblock, extbuf, Len - lblock, lblock);
}
static void SQRT_SORT(SORT_TYPE *arr, size_t Len) {
size_t L = 1;
SORT_TYPE *ExtBuf;
int *Tags;
while (L * L < Len) {
L *= 2;
}
int NK = (Len - 1) / L + 2;
ExtBuf = (SORT_TYPE*)malloc(L * sizeof(SORT_TYPE));
if (ExtBuf == NULL) {
return; /* fail */
}
Tags = (int*)malloc(NK * sizeof(int));
if (Tags == NULL) {
return;
}
SQRT_SORT_COMMON_SORT(arr, Len, ExtBuf, Tags);
free(Tags);
free(ExtBuf);
}
/********* Grail sorting *********************************/
/* */
/* (c) 2013 by Andrey Astrelin */
/* */
/* */
/* Stable sorting that works in O(N*log(N)) worst time */
/* and uses O(1) extra memory */
/* */
/* Define SORT_TYPE and SORT_CMP */
/* and then call GrailSort() function */
/* */
/* For sorting with fixed external buffer (512 items) */
/* use GrailSortWithBuffer() */
/* */
/* For sorting with dynamic external buffer (O(sqrt(N)) items) */
/* use GrailSortWithDynBuffer() */
/* */
/* Also classic in-place merge sort is implemented */
/* under the name of RecStableSort() */
/* */
/*********************************************************/
#define GRAIL_EXT_BUFFER_LENGTH 512
static __inline void GRAIL_SWAP1(SORT_TYPE *a, SORT_TYPE *b) {
SORT_TYPE c = *a;
*a = *b;
*b = c;
}
static __inline void GRAIL_SWAP_N(SORT_TYPE *a, SORT_TYPE *b, int n) {
while (n--) {
GRAIL_SWAP1(a++, b++);
}
}
static void GRAIL_ROTATE(SORT_TYPE *a, int l1, int l2) {
while (l1 && l2) {
if (l1 <= l2) {
GRAIL_SWAP_N(a, a + l1, l1);
a += l1;
l2 -= l1;
} else {
GRAIL_SWAP_N(a + (l1 - l2), a + l1, l2);
l1 -= l2;
}
}
}
static int GRAIL_BIN_SEARCH_LEFT(SORT_TYPE *arr, int len, SORT_TYPE *key) {
int a = -1, b = len, c;
while (a < b - 1) {
c = a + ((b - a) >> 1);
if (SORT_CMP_A(arr + c, key) >= 0) {
b = c;
} else {
a = c;
}
}
return b;
}
static int GRAIL_BIN_SEARCH_RIGHT(SORT_TYPE *arr, int len, SORT_TYPE *key) {
int a = -1, b = len, c;
while (a < b - 1) {
c = a + ((b - a) >> 1);
if (SORT_CMP_A(arr + c, key) > 0) {
b = c;
} else {
a = c;
}
}
return b;
}
/* cost: 2*len+nk^2/2 */
static int GRAIL_FIND_KEYS(SORT_TYPE *arr, int len, int nkeys) {
int h = 1, h0 = 0; /* first key is always here */
int u = 1, r;
while (u < len && h < nkeys) {
r = GRAIL_BIN_SEARCH_LEFT(arr + h0, h, arr + u);
if (r == h || SORT_CMP_A(arr + u, arr + (h0 + r)) != 0) {
GRAIL_ROTATE(arr + h0, h, u - (h0 + h));
h0 = u - h;
GRAIL_ROTATE(arr + (h0 + r), h - r, 1);
h++;
}
u++;
}
GRAIL_ROTATE(arr, h0, h);
return h;
}
/* cost: min(L1,L2)^2+max(L1,L2) */
static void GRAIL_MERGE_WITHOUT_BUFFER(SORT_TYPE *arr, int len1, int len2) {
int h;
if (len1 < len2) {
while (len1) {
h = GRAIL_BIN_SEARCH_LEFT(arr + len1, len2, arr);
if (h != 0) {
GRAIL_ROTATE(arr, len1, h);
arr += h;
len2 -= h;
}
if (len2 == 0) {
break;
}
do {
arr++;
len1--;
} while (len1 && SORT_CMP_A(arr, arr + len1) <= 0);
}
} else {
while (len2) {
h = GRAIL_BIN_SEARCH_RIGHT(arr, len1, arr + (len1 + len2 - 1));
if (h != len1) {
GRAIL_ROTATE(arr + h, len1 - h, len2);
len1 = h;
}
if (len1 == 0) {
break;
}
do {
len2--;
} while (len2 && SORT_CMP_A(arr + len1 - 1, arr + len1 + len2 - 1) <= 0);
}
}
}
/* arr[M..-1] - buffer, arr[0,L1-1]++arr[L1,L1+L2-1] -> arr[M,M+L1+L2-1] */
static void GRAIL_MERGE_LEFT(SORT_TYPE *arr, int L1, int L2, int M) {
int p0 = 0, p1 = L1;
L2 += L1;
while (p1 < L2) {
if (p0 == L1 || SORT_CMP_A(arr + p0, arr + p1) > 0) {
GRAIL_SWAP1(arr + (M++), arr + (p1++));
} else {
GRAIL_SWAP1(arr + (M++), arr + (p0++));
}
}
if (M != p0) {
GRAIL_SWAP_N(arr + M, arr + p0, L1 - p0);
}
}
static void GRAIL_MERGE_RIGHT(SORT_TYPE *arr, int L1, int L2, int M) {
int p0 = L1 + L2 + M - 1, p2 = L1 + L2 - 1, p1 = L1 - 1;
while (p1 >= 0) {
if (p2 < L1 || SORT_CMP_A(arr + p1, arr + p2) > 0) {
GRAIL_SWAP1(arr + (p0--), arr + (p1--));
} else {
GRAIL_SWAP1(arr + (p0--), arr + (p2--));
}
}
if (p2 != p0) while (p2 >= L1) {
GRAIL_SWAP1(arr + (p0--), arr + (p2--));
}
}
static void GRAIL_SMART_MERGE_WITH_BUFFER(SORT_TYPE *arr, int *alen1, int *atype, int len2,
int lkeys) {
int p0 = -lkeys, p1 = 0, p2 = *alen1, q1 = p2, q2 = p2 + len2;
int ftype = 1 - *atype; /* 1 if inverted */
while (p1 < q1 && p2 < q2) {
if (SORT_CMP_A(arr + p1, arr + p2) - ftype < 0) {
GRAIL_SWAP1(arr + (p0++), arr + (p1++));
} else {
GRAIL_SWAP1(arr + (p0++), arr + (p2++));
}
}
if (p1 < q1) {
*alen1 = q1 - p1;
while (p1 < q1) {
GRAIL_SWAP1(arr + (--q1), arr + (--q2));
}
} else {
*alen1 = q2 - p2;
*atype = ftype;
}
}
static void GRAIL_SMART_MERGE_WITHOUT_BUFFER(SORT_TYPE *arr, int *alen1, int *atype, int _len2) {
int len1, len2, ftype, h;
if (!_len2) {
return;
}
len1 = *alen1;
len2 = _len2;
ftype = 1 - *atype;
if (len1 && SORT_CMP_A(arr + (len1 - 1), arr + len1) - ftype >= 0) {
while (len1) {
h = ftype ? GRAIL_BIN_SEARCH_LEFT(arr + len1, len2, arr) : GRAIL_BIN_SEARCH_RIGHT(arr + len1, len2,
arr);
if (h != 0) {
GRAIL_ROTATE(arr, len1, h);
arr += h;
len2 -= h;
}
if (len2 == 0) {
*alen1 = len1;
return;
}
do {
arr++;
len1--;
} while (len1 && SORT_CMP_A(arr, arr + len1) - ftype < 0);
}
}
*alen1 = len2;
*atype = ftype;
}
/***** Sort With Extra Buffer *****/
/* arr[M..-1] - free, arr[0,L1-1]++arr[L1,L1+L2-1] -> arr[M,M+L1+L2-1] */
static void GRAIL_MERGE_LEFT_WITH_X_BUF(SORT_TYPE *arr, int L1, int L2, int M) {
int p0 = 0, p1 = L1;
L2 += L1;
while (p1 < L2) {
if (p0 == L1 || SORT_CMP_A(arr + p0, arr + p1) > 0) {
arr[M++] = arr[p1++];
} else {
arr[M++] = arr[p0++];
}
}
if (M != p0) while (p0 < L1) {
arr[M++] = arr[p0++];
}
}
static void GRAIL_SMART_MERGE_WITH_X_BUF(SORT_TYPE *arr, int *alen1, int *atype, int len2,
int lkeys) {
int p0 = -lkeys, p1 = 0, p2 = *alen1, q1 = p2, q2 = p2 + len2;
int ftype = 1 - *atype; /* 1 if inverted */
while (p1 < q1 && p2 < q2) {
if (SORT_CMP_A(arr + p1, arr + p2) - ftype < 0) {
arr[p0++] = arr[p1++];
} else {
arr[p0++] = arr[p2++];
}
}
if (p1 < q1) {
*alen1 = q1 - p1;
while (p1 < q1) {
arr[--q2] = arr[--q1];
}
} else {
*alen1 = q2 - p2;
*atype = ftype;
}
}
/*
arr - starting array. arr[-lblock..-1] - buffer (if havebuf).
lblock - length of regular blocks. First nblocks are stable sorted by 1st elements and key-coded
keys - arrays of keys, in same order as blocks. key<midkey means stream A
nblock2 are regular blocks from stream A. llast is length of last (irregular) block from stream B, that should go before nblock2 blocks.
llast=0 requires nblock2=0 (no irregular blocks). llast>0, nblock2=0 is possible.
*/
static void GRAIL_MERGE_BUFFERS_LEFT_WITH_X_BUF(SORT_TYPE *keys, SORT_TYPE *midkey, SORT_TYPE *arr,
int nblock, int lblock, int nblock2, int llast) {
int l, prest, lrest, frest, pidx, cidx, fnext;
if (nblock == 0) {
l = nblock2 * lblock;
GRAIL_MERGE_LEFT_WITH_X_BUF(arr, l, llast, -lblock);
return;
}
lrest = lblock;
frest = SORT_CMP_A(keys, midkey) < 0 ? 0 : 1;
pidx = lblock;
for (cidx = 1; cidx < nblock; cidx++, pidx += lblock) {
prest = pidx - lrest;
fnext = SORT_CMP_A(keys + cidx, midkey) < 0 ? 0 : 1;
if (fnext == frest) {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
prest = pidx;
lrest = lblock;
} else {
GRAIL_SMART_MERGE_WITH_X_BUF(arr + prest, &lrest, &frest, lblock, lblock);
}
}
prest = pidx - lrest;
if (llast) {
if (frest) {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
prest = pidx;
lrest = lblock * nblock2;
frest = 0;
} else {
lrest += lblock * nblock2;
}
GRAIL_MERGE_LEFT_WITH_X_BUF(arr + prest, lrest, llast, -lblock);
} else {
memcpy(arr + prest - lblock, arr + prest, lrest * sizeof(SORT_TYPE));
}
}
/***** End Sort With Extra Buffer *****/
/*
build blocks of length K
input: [-K,-1] elements are buffer
output: first K elements are buffer, blocks 2*K and last subblock sorted
*/
static void GRAIL_BUILD_BLOCKS(SORT_TYPE *arr, int L, int K, SORT_TYPE *extbuf, int LExtBuf) {
int m, u, h, p0, p1, rest, restk, p, kbuf;
kbuf = K < LExtBuf ? K : LExtBuf;
while (kbuf & (kbuf - 1)) {
kbuf &= kbuf - 1; /* max power or 2 - just in case */
}
if (kbuf) {
memcpy(extbuf, arr - kbuf, kbuf * sizeof(SORT_TYPE));
for (m = 1; m < L; m += 2) {
u = 0;
if (SORT_CMP_A(arr + (m - 1), arr + m) > 0) {
u = 1;
}
arr[m - 3] = arr[m - 1 + u];
arr[m - 2] = arr[m - u];
}
if (L % 2) {
arr[L - 3] = arr[L - 1];
}
arr -= 2;
for (h = 2; h < kbuf; h *= 2) {
p0 = 0;
p1 = L - 2 * h;
while (p0 <= p1) {
GRAIL_MERGE_LEFT_WITH_X_BUF(arr + p0, h, h, -h);
p0 += 2 * h;
}
rest = L - p0;
if (rest > h) {
GRAIL_MERGE_LEFT_WITH_X_BUF(arr + p0, h, rest - h, -h);
} else {
for (; p0 < L; p0++) {
arr[p0 - h] = arr[p0];
}
}
arr -= h;
}
memcpy(arr + L, extbuf, kbuf * sizeof(SORT_TYPE));
} else {
for (m = 1; m < L; m += 2) {
u = 0;
if (SORT_CMP_A(arr + (m - 1), arr + m) > 0) {
u = 1;
}
GRAIL_SWAP1(arr + (m - 3), arr + (m - 1 + u));
GRAIL_SWAP1(arr + (m - 2), arr + (m - u));
}
if (L % 2) {
GRAIL_SWAP1(arr + (L - 1), arr + (L - 3));
}
arr -= 2;
h = 2;
}
for (; h < K; h *= 2) {
p0 = 0;
p1 = L - 2 * h;
while (p0 <= p1) {
GRAIL_MERGE_LEFT(arr + p0, h, h, -h);
p0 += 2 * h;
}
rest = L - p0;
if (rest > h) {
GRAIL_MERGE_LEFT(arr + p0, h, rest - h, -h);
} else {
GRAIL_ROTATE(arr + p0 - h, h, rest);
}
arr -= h;
}
restk = L % (2 * K);
p = L - restk;
if (restk <= K) {
GRAIL_ROTATE(arr + p, restk, K);
} else {
GRAIL_MERGE_RIGHT(arr + p, K, restk - K, K);
}
while (p > 0) {
p -= 2 * K;
GRAIL_MERGE_RIGHT(arr + p, K, K, K);
}
}
/*
arr - starting array. arr[-lblock..-1] - buffer (if havebuf).
lblock - length of regular blocks. First nblocks are stable sorted by 1st elements and key-coded
keys - arrays of keys, in same order as blocks. key<midkey means stream A
nblock2 are regular blocks from stream A. llast is length of last (irregular) block from stream B, that should go before nblock2 blocks.
llast=0 requires nblock2=0 (no irregular blocks). llast>0, nblock2=0 is possible.
*/
static void GRAIL_MERGE_BUFFERS_LEFT(SORT_TYPE *keys, SORT_TYPE *midkey, SORT_TYPE *arr, int nblock,
int lblock, int havebuf, int nblock2, int llast) {
int l, prest, lrest, frest, pidx, cidx, fnext;
if (nblock == 0) {
l = nblock2 * lblock;
if (havebuf) {
GRAIL_MERGE_LEFT(arr, l, llast, -lblock);
} else {
GRAIL_MERGE_WITHOUT_BUFFER(arr, l, llast);
}
return;
}
lrest = lblock;
frest = SORT_CMP_A(keys, midkey) < 0 ? 0 : 1;
pidx = lblock;
for (cidx = 1; cidx < nblock; cidx++, pidx += lblock) {
prest = pidx - lrest;
fnext = SORT_CMP_A(keys + cidx, midkey) < 0 ? 0 : 1;
if (fnext == frest) {
if (havebuf) {
GRAIL_SWAP_N(arr + prest - lblock, arr + prest, lrest);
}
prest = pidx;
lrest = lblock;
} else {
if (havebuf) {
GRAIL_SMART_MERGE_WITH_BUFFER(arr + prest, &lrest, &frest, lblock, lblock);
} else {
GRAIL_SMART_MERGE_WITHOUT_BUFFER(arr + prest, &lrest, &frest, lblock);
}
}
}
prest = pidx - lrest;
if (llast) {
if (frest) {
if (havebuf) {
GRAIL_SWAP_N(arr + prest - lblock, arr + prest, lrest);
}
prest = pidx;
lrest = lblock * nblock2;
frest = 0;
} else {
lrest += lblock * nblock2;
}
if (havebuf) {
GRAIL_MERGE_LEFT(arr + prest, lrest, llast, -lblock);
} else {
GRAIL_MERGE_WITHOUT_BUFFER(arr + prest, lrest, llast);
}
} else {
if (havebuf) {
GRAIL_SWAP_N(arr + prest, arr + (prest - lblock), lrest);
}
}
}
static void GRAIL_LAZY_STABLE_SORT(SORT_TYPE *arr, int L) {
int m, h, p0, p1, rest;
for (m = 1; m < L; m += 2) {
if (SORT_CMP_A(arr + m - 1, arr + m) > 0) {
GRAIL_SWAP1(arr + (m - 1), arr + m);
}
}
for (h = 2; h < L; h *= 2) {
p0 = 0;
p1 = L - 2 * h;
while (p0 <= p1) {
GRAIL_MERGE_WITHOUT_BUFFER(arr + p0, h, h);
p0 += 2 * h;
}
rest = L - p0;
if (rest > h) {
GRAIL_MERGE_WITHOUT_BUFFER(arr + p0, h, rest - h);
}
}
}
/*
keys are on the left of arr. Blocks of length LL combined. We'll combine them in pairs
LL and nkeys are powers of 2. (2*LL/lblock) keys are guarantied
*/
static void GRAIL_COMBINE_BLOCKS(SORT_TYPE *keys, SORT_TYPE *arr, int len, int LL, int lblock,
int havebuf, SORT_TYPE *xbuf) {
int M, b, NBlk, midkey, lrest, u, p, v, kc, nbl2, llast;
SORT_TYPE *arr1;
M = len / (2 * LL);
lrest = len % (2 * LL);
if (lrest <= LL) {
len -= lrest;
lrest = 0;
}
if (xbuf) {
memcpy(xbuf, arr - lblock, lblock * sizeof(SORT_TYPE));
}
for (b = 0; b <= M; b++) {
if (b == M && lrest == 0) {
break;
}
arr1 = arr + b * 2 * LL;
NBlk = (b == M ? lrest : 2 * LL) / lblock;
BINARY_INSERTION_SORT(keys, NBlk + (b == M ? 1 : 0));
midkey = LL / lblock;
for (u = 1; u < NBlk; u++) {
p = u - 1;
for (v = u; v < NBlk; v++) {
kc = SORT_CMP_A(arr1 + p * lblock, arr1 + v * lblock);
if (kc > 0 || (kc == 0 && SORT_CMP_A(keys + p, keys + v) > 0)) {
p = v;
}
}
if (p != u - 1) {
GRAIL_SWAP_N(arr1 + (u - 1)*lblock, arr1 + p * lblock, lblock);
GRAIL_SWAP1(keys + (u - 1), keys + p);
if (midkey == u - 1 || midkey == p) {
midkey ^= (u - 1)^p;
}
}
}
nbl2 = llast = 0;
if (b == M) {
llast = lrest % lblock;
}
if (llast != 0) {
while (nbl2 < NBlk && SORT_CMP_A(arr1 + NBlk * lblock, arr1 + (NBlk - nbl2 - 1)*lblock) < 0) {
nbl2++;
}
}
if (xbuf) {
GRAIL_MERGE_BUFFERS_LEFT_WITH_X_BUF(keys, keys + midkey, arr1, NBlk - nbl2, lblock, nbl2, llast);
} else {
GRAIL_MERGE_BUFFERS_LEFT(keys, keys + midkey, arr1, NBlk - nbl2, lblock, havebuf, nbl2, llast);
}
}
if (xbuf) {
for (p = len; --p >= 0;) {
arr[p] = arr[p - lblock];
}
memcpy(arr - lblock, xbuf, lblock * sizeof(SORT_TYPE));
} else if (havebuf) while (--len >= 0) {
GRAIL_SWAP1(arr + len, arr + len - lblock);
}
}
static void GRAIL_COMMON_SORT(SORT_TYPE *arr, int Len, SORT_TYPE *extbuf, int LExtBuf) {
int lblock, nkeys, findkeys, ptr, cbuf, lb, nk;
int havebuf, chavebuf;
long long s;
if (Len < 16) {
BINARY_INSERTION_SORT(arr, Len);
return;
}
lblock = 1;
while (lblock * lblock < Len) {
lblock *= 2;
}
nkeys = (Len - 1) / lblock + 1;
findkeys = GRAIL_FIND_KEYS(arr, Len, nkeys + lblock);
havebuf = 1;
if (findkeys < nkeys + lblock) {
if (findkeys < 4) {
GRAIL_LAZY_STABLE_SORT(arr, Len);
return;
}
nkeys = lblock;
while (nkeys > findkeys) {
nkeys /= 2;
}
havebuf = 0;
lblock = 0;
}
ptr = lblock + nkeys;
cbuf = havebuf ? lblock : nkeys;
if (havebuf) {
GRAIL_BUILD_BLOCKS(arr + ptr, Len - ptr, cbuf, extbuf, LExtBuf);
} else {
GRAIL_BUILD_BLOCKS(arr + ptr, Len - ptr, cbuf, NULL, 0);
}
/* 2*cbuf are built */
while (Len - ptr > (cbuf *= 2)) {
lb = lblock;
chavebuf = havebuf;
if (!havebuf) {
if (nkeys > 4 && nkeys / 8 * nkeys >= cbuf) {
lb = nkeys / 2;
chavebuf = 1;
} else {
nk = 1;
s = (long long)cbuf * findkeys / 2;
while (nk < nkeys && s != 0) {
nk *= 2;
s /= 8;
}
lb = (2 * cbuf) / nk;
}
}
GRAIL_COMBINE_BLOCKS(arr, arr + ptr, Len - ptr, cbuf, lb, chavebuf, chavebuf
&& lb <= LExtBuf ? extbuf : NULL);
}
BINARY_INSERTION_SORT(arr, ptr);
GRAIL_MERGE_WITHOUT_BUFFER(arr, ptr, Len - ptr);
}
static void GRAIL_SORT(SORT_TYPE *arr, size_t Len) {
GRAIL_COMMON_SORT(arr, Len, NULL, 0);
}
static void GRAIL_SORT_FIXED_BUFFER(SORT_TYPE *arr, size_t Len) {
SORT_TYPE ExtBuf[GRAIL_EXT_BUFFER_LENGTH];
GRAIL_COMMON_SORT(arr, Len, ExtBuf, GRAIL_EXT_BUFFER_LENGTH);
}
static void GRAIL_SORT_DYN_BUFFER(SORT_TYPE *arr, size_t Len) {
size_t L = 1;
SORT_TYPE *ExtBuf;
while (L * L < Len) {
L *= 2;
}
ExtBuf = (SORT_TYPE*)malloc(L * sizeof(SORT_TYPE));
if (ExtBuf == NULL) {
GRAIL_SORT_FIXED_BUFFER(arr, Len);
} else {
GRAIL_COMMON_SORT(arr, Len, ExtBuf, L);
free(ExtBuf);
}
}
/****** classic MergeInPlace *************/
static void GRAIL_REC_MERGE(SORT_TYPE *A, int L1, int L2) {
int K, k1, k2, m1, m2;
if (L1 < 3 || L2 < 3) {
GRAIL_MERGE_WITHOUT_BUFFER(A, L1, L2);
return;
}
if (L1 < L2) {
K = L1 + L2 / 2;
} else {
K = L1 / 2;
}
k1 = k2 = GRAIL_BIN_SEARCH_LEFT(A, L1, A + K);
if (k2 < L1 && SORT_CMP_A(A + k2, A + K) == 0) {
k2 = GRAIL_BIN_SEARCH_RIGHT(A + k1, L1 - k1, A + K) + k1;
}
m1 = GRAIL_BIN_SEARCH_LEFT(A + L1, L2, A + K);
m2 = m1;
if (m2 < L2 && SORT_CMP_A(A + L1 + m2, A + K) == 0) {
m2 = GRAIL_BIN_SEARCH_RIGHT(A + L1 + m1, L2 - m1, A + K) + m1;
}
if (k1 == k2) {
GRAIL_ROTATE(A + k2, L1 - k2, m2);
} else {
GRAIL_ROTATE(A + k1, L1 - k1, m1);
if (m2 != m1) {
GRAIL_ROTATE(A + (k2 + m1), L1 - k2, m2 - m1);
}
}
GRAIL_REC_MERGE(A + (k2 + m2), L1 - k2, L2 - m2);
GRAIL_REC_MERGE(A, k1, m1);
}
static void REC_STABLE_SORT(SORT_TYPE *arr, size_t L) {
size_t m, h, p0, p1, rest;
for (m = 1; m < L; m += 2) {
if (SORT_CMP_A(arr + m - 1, arr + m) > 0) {
GRAIL_SWAP1(arr + (m - 1), arr + m);
}
}
for (h = 2; h < L; h *= 2) {
p0 = 0;
p1 = L - 2 * h;
while (p0 <= p1) {
GRAIL_REC_MERGE(arr + p0, h, h);
p0 += 2 * h;
}
rest = L - p0;
if (rest > h) {
GRAIL_REC_MERGE(arr + p0, h, rest - h);
}
}
}
/* Bubble sort implementation based on Wikipedia article
https://en.wikipedia.org/wiki/Bubble_sort
*/
void BUBBLE_SORT(SORT_TYPE *dst, const size_t size) {
size_t n = size;
while (n) {
size_t i, newn = 0U;
for (i = 1U; i < n; ++i) {
if (SORT_CMP(dst[i - 1U], dst[i]) > 0) {
SORT_SWAP(dst[i - 1U], dst[i]);
newn = i;
}
}
n = newn;
}
}
#undef QUICK_SORT
#undef MEDIAN
#undef SORT_CONCAT
#undef SORT_MAKE_STR1
#undef SORT_MAKE_STR
#undef SORT_NAME
#undef SORT_TYPE
#undef SORT_CMP
#undef TEMP_STORAGE_T
#undef TIM_SORT_RUN_T
#undef PUSH_NEXT
#undef SORT_SWAP
#undef SORT_CONCAT
#undef SORT_MAKE_STR1
#undef SORT_MAKE_STR
#undef BINARY_INSERTION_FIND
#undef BINARY_INSERTION_SORT_START
#undef BINARY_INSERTION_SORT
#undef REVERSE_ELEMENTS
#undef COUNT_RUN
#undef TIM_SORT
#undef TIM_SORT_RESIZE
#undef TIM_SORT_COLLAPSE
#undef TIM_SORT_RUN_T
#undef TEMP_STORAGE_T
#undef MERGE_SORT
#undef MERGE_SORT_IN_PLACE
#undef MERGE_SORT_IN_PLACE_RMERGE
#undef MERGE_SORT_IN_PLACE_BACKMERGE
#undef MERGE_SORT_IN_PLACE_FRONTMERGE
#undef MERGE_SORT_IN_PLACE_ASWAP
#undef GRAIL_SWAP1
#undef REC_STABLE_SORT
#undef GRAIL_REC_MERGE
#undef GRAIL_SORT_DYN_BUFFER
#undef GRAIL_SORT_FIXED_BUFFER
#undef GRAIL_COMMON_SORT
#undef GRAIL_SORT
#undef GRAIL_COMBINE_BLOCKS
#undef GRAIL_LAZY_STABLE_SORT
#undef GRAIL_MERGE_WITHOUT_BUFFER
#undef GRAIL_ROTATE
#undef GRAIL_BIN_SEARCH_LEFT
#undef GRAIL_BUILD_BLOCKS
#undef GRAIL_FIND_KEYS
#undef GRAIL_MERGE_BUFFERS_LEFT_WITH_X_BUF
#undef GRAIL_BIN_SEARCH_RIGHT
#undef GRAIL_MERGE_BUFFERS_LEFT
#undef GRAIL_SMART_MERGE_WITH_X_BUF
#undef GRAIL_MERGE_LEFT_WITH_X_BUF
#undef GRAIL_SMART_MERGE_WITHOUT_BUFFER
#undef GRAIL_SMART_MERGE_WITH_BUFFER
#undef GRAIL_MERGE_RIGHT
#undef GRAIL_MERGE_LEFT
#undef GRAIL_SWAP_N
#undef SQRT_SORT
#undef SQRT_SORT_BUILD_BLOCKS
#undef SQRT_SORT_MERGE_BUFFERS_LEFT_WITH_X_BUF
#undef SQRT_SORT_MERGE_DOWN
#undef SQRT_SORT_MERGE_LEFT_WITH_X_BUF
#undef SQRT_SORT_MERGE_RIGHT
#undef SQRT_SORT_SWAP_N
#undef SQRT_SORT_SWAP_1
#undef SQRT_SORT_SMART_MERGE_WITH_X_BUF
#undef SQRT_SORT_SORT_INS
#undef SQRT_SORT_COMBINE_BLOCKS
#undef SQRT_SORT_COMMON_SORT
#undef SORT_CMP_A
#undef BUBBLE_SORT
|
apache-2.0
|
quarkusio/quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/customproviders/UniExceptionMapper.java
|
409
|
package org.jboss.resteasy.reactive.server.vertx.test.customproviders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class UniExceptionMapper implements ExceptionMapper<UniException> {
@Override
public Response toResponse(UniException exception) {
return Response.accepted(exception.getInput()).build();
}
}
|
apache-2.0
|
tensorflow/recommenders-addons
|
demo/dynamic_embedding/movielens-100k-estimator-with-warmup/warmup_train.sh
|
692
|
#!/usr/bin/env bash
sh stop.sh
sleep 1
export TF_CONFIG='{"cluster": {"worker": ["localhost:2222"], "ps": ["localhost:2223"], "chief": ["localhost:2224"]}, "task": {"type": "chief", "index": 0}}'
python movielens-100k-estimator.py --mode warmup &
sleep 1
export TF_CONFIG='{"cluster": {"worker": ["localhost:2222"], "ps": ["localhost:2223"], "chief": ["localhost:2224"]}, "task": {"type": "worker", "index": 0}}'
python movielens-100k-estimator.py --mode warmup &
sleep 1
export TF_CONFIG='{"cluster": {"worker": ["localhost:2222"], "ps": ["localhost:2223"], "chief": ["localhost:2224"]}, "task": {"type": "ps", "index": 0}}'
python movielens-100k-estimator.py --mode warmup &
echo "ok"
|
apache-2.0
|
fiatjaf/summadb
|
utils/random.go
|
964
|
package utils
import (
"math/rand"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
func RandomString(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func LetterByIndex(idx int) string {
idx = idx % len(letterBytes)
return letterBytes[idx : idx+1]
}
|
apache-2.0
|
redhat-cip/openstack-logcollector
|
openstack-logcollector/openstack/common/rpc/impl_qpid.py
|
29688
|
# Copyright 2011 OpenStack Foundation
# Copyright 2011 - 2012, 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.
import functools
import itertools
import time
import eventlet
import greenlet
from oslo.config import cfg
import six
from logcollector.openstack.common import excutils
from logcollector.openstack.common.gettextutils import _
from logcollector.openstack.common import importutils
from logcollector.openstack.common import jsonutils
from logcollector.openstack.common import log as logging
from logcollector.openstack.common.rpc import amqp as rpc_amqp
from logcollector.openstack.common.rpc import common as rpc_common
qpid_codec = importutils.try_import("qpid.codec010")
qpid_messaging = importutils.try_import("qpid.messaging")
qpid_exceptions = importutils.try_import("qpid.messaging.exceptions")
LOG = logging.getLogger(__name__)
qpid_opts = [
cfg.StrOpt('qpid_hostname',
default='localhost',
help='Qpid broker hostname'),
cfg.IntOpt('qpid_port',
default=5672,
help='Qpid broker port'),
cfg.ListOpt('qpid_hosts',
default=['$qpid_hostname:$qpid_port'],
help='Qpid HA cluster host:port pairs'),
cfg.StrOpt('qpid_username',
default='',
help='Username for qpid connection'),
cfg.StrOpt('qpid_password',
default='',
help='Password for qpid connection',
secret=True),
cfg.StrOpt('qpid_sasl_mechanisms',
default='',
help='Space separated list of SASL mechanisms to use for auth'),
cfg.IntOpt('qpid_heartbeat',
default=60,
help='Seconds between connection keepalive heartbeats'),
cfg.StrOpt('qpid_protocol',
default='tcp',
help="Transport to use, either 'tcp' or 'ssl'"),
cfg.BoolOpt('qpid_tcp_nodelay',
default=True,
help='Disable Nagle algorithm'),
# NOTE(russellb) If any additional versions are added (beyond 1 and 2),
# this file could probably use some additional refactoring so that the
# differences between each version are split into different classes.
cfg.IntOpt('qpid_topology_version',
default=1,
help="The qpid topology version to use. Version 1 is what "
"was originally used by impl_qpid. Version 2 includes "
"some backwards-incompatible changes that allow broker "
"federation to work. Users should update to version 2 "
"when they are able to take everything down, as it "
"requires a clean break."),
]
cfg.CONF.register_opts(qpid_opts)
JSON_CONTENT_TYPE = 'application/json; charset=utf8'
def raise_invalid_topology_version(conf):
msg = (_("Invalid value for qpid_topology_version: %d") %
conf.qpid_topology_version)
LOG.error(msg)
raise Exception(msg)
class ConsumerBase(object):
"""Consumer base class."""
def __init__(self, conf, session, callback, node_name, node_opts,
link_name, link_opts):
"""Declare a queue on an amqp session.
'session' is the amqp session to use
'callback' is the callback to call when messages are received
'node_name' is the first part of the Qpid address string, before ';'
'node_opts' will be applied to the "x-declare" section of "node"
in the address string.
'link_name' goes into the "name" field of the "link" in the address
string
'link_opts' will be applied to the "x-declare" section of "link"
in the address string.
"""
self.callback = callback
self.receiver = None
self.session = None
if conf.qpid_topology_version == 1:
addr_opts = {
"create": "always",
"node": {
"type": "topic",
"x-declare": {
"durable": True,
"auto-delete": True,
},
},
"link": {
"durable": True,
"x-declare": {
"durable": False,
"auto-delete": True,
"exclusive": False,
},
},
}
addr_opts["node"]["x-declare"].update(node_opts)
elif conf.qpid_topology_version == 2:
addr_opts = {
"link": {
"x-declare": {
"auto-delete": True,
"exclusive": False,
},
},
}
else:
raise_invalid_topology_version()
addr_opts["link"]["x-declare"].update(link_opts)
if link_name:
addr_opts["link"]["name"] = link_name
self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts))
self.connect(session)
def connect(self, session):
"""Declare the receiver on connect."""
self._declare_receiver(session)
def reconnect(self, session):
"""Re-declare the receiver after a qpid reconnect."""
self._declare_receiver(session)
def _declare_receiver(self, session):
self.session = session
self.receiver = session.receiver(self.address)
self.receiver.capacity = 1
def _unpack_json_msg(self, msg):
"""Load the JSON data in msg if msg.content_type indicates that it
is necessary. Put the loaded data back into msg.content and
update msg.content_type appropriately.
A Qpid Message containing a dict will have a content_type of
'amqp/map', whereas one containing a string that needs to be converted
back from JSON will have a content_type of JSON_CONTENT_TYPE.
:param msg: a Qpid Message object
:returns: None
"""
if msg.content_type == JSON_CONTENT_TYPE:
msg.content = jsonutils.loads(msg.content)
msg.content_type = 'amqp/map'
def consume(self):
"""Fetch the message and pass it to the callback object."""
message = self.receiver.fetch()
try:
self._unpack_json_msg(message)
msg = rpc_common.deserialize_msg(message.content)
self.callback(msg)
except Exception:
LOG.exception(_("Failed to process message... skipping it."))
finally:
# TODO(sandy): Need support for optional ack_on_error.
self.session.acknowledge(message)
def get_receiver(self):
return self.receiver
def get_node_name(self):
return self.address.split(';')[0]
class DirectConsumer(ConsumerBase):
"""Queue/consumer class for 'direct'."""
def __init__(self, conf, session, msg_id, callback):
"""Init a 'direct' queue.
'session' is the amqp session to use
'msg_id' is the msg_id to listen on
'callback' is the callback to call when messages are received
"""
link_opts = {
"auto-delete": conf.amqp_auto_delete,
"exclusive": True,
"durable": conf.amqp_durable_queues,
}
if conf.qpid_topology_version == 1:
node_name = "%s/%s" % (msg_id, msg_id)
node_opts = {"type": "direct"}
link_name = msg_id
elif conf.qpid_topology_version == 2:
node_name = "amq.direct/%s" % msg_id
node_opts = {}
link_name = None
else:
raise_invalid_topology_version()
super(DirectConsumer, self).__init__(conf, session, callback,
node_name, node_opts, link_name,
link_opts)
class TopicConsumer(ConsumerBase):
"""Consumer class for 'topic'."""
def __init__(self, conf, session, topic, callback, name=None,
exchange_name=None):
"""Init a 'topic' queue.
:param session: the amqp session to use
:param topic: is the topic to listen on
:paramtype topic: str
:param callback: the callback to call when messages are received
:param name: optional queue name, defaults to topic
"""
exchange_name = exchange_name or rpc_amqp.get_control_exchange(conf)
link_opts = {
"auto-delete": conf.amqp_auto_delete,
"durable": conf.amqp_durable_queues,
}
if conf.qpid_topology_version == 1:
node_name = "%s/%s" % (exchange_name, topic)
elif conf.qpid_topology_version == 2:
node_name = "amq.topic/topic/%s/%s" % (exchange_name, topic)
else:
raise_invalid_topology_version()
super(TopicConsumer, self).__init__(conf, session, callback, node_name,
{}, name or topic, link_opts)
class FanoutConsumer(ConsumerBase):
"""Consumer class for 'fanout'."""
def __init__(self, conf, session, topic, callback):
"""Init a 'fanout' queue.
'session' is the amqp session to use
'topic' is the topic to listen on
'callback' is the callback to call when messages are received
"""
self.conf = conf
link_opts = {"exclusive": True}
if conf.qpid_topology_version == 1:
node_name = "%s_fanout" % topic
node_opts = {"durable": False, "type": "fanout"}
elif conf.qpid_topology_version == 2:
node_name = "amq.topic/fanout/%s" % topic
node_opts = {}
else:
raise_invalid_topology_version()
super(FanoutConsumer, self).__init__(conf, session, callback,
node_name, node_opts, None,
link_opts)
class Publisher(object):
"""Base Publisher class."""
def __init__(self, conf, session, node_name, node_opts=None):
"""Init the Publisher class with the exchange_name, routing_key,
and other options
"""
self.sender = None
self.session = session
if conf.qpid_topology_version == 1:
addr_opts = {
"create": "always",
"node": {
"type": "topic",
"x-declare": {
"durable": False,
# auto-delete isn't implemented for exchanges in qpid,
# but put in here anyway
"auto-delete": True,
},
},
}
if node_opts:
addr_opts["node"]["x-declare"].update(node_opts)
self.address = "%s ; %s" % (node_name, jsonutils.dumps(addr_opts))
elif conf.qpid_topology_version == 2:
self.address = node_name
else:
raise_invalid_topology_version()
self.reconnect(session)
def reconnect(self, session):
"""Re-establish the Sender after a reconnection."""
self.sender = session.sender(self.address)
def _pack_json_msg(self, msg):
"""Qpid cannot serialize dicts containing strings longer than 65535
characters. This function dumps the message content to a JSON
string, which Qpid is able to handle.
:param msg: May be either a Qpid Message object or a bare dict.
:returns: A Qpid Message with its content field JSON encoded.
"""
try:
msg.content = jsonutils.dumps(msg.content)
except AttributeError:
# Need to have a Qpid message so we can set the content_type.
msg = qpid_messaging.Message(jsonutils.dumps(msg))
msg.content_type = JSON_CONTENT_TYPE
return msg
def send(self, msg):
"""Send a message."""
try:
# Check if Qpid can encode the message
check_msg = msg
if not hasattr(check_msg, 'content_type'):
check_msg = qpid_messaging.Message(msg)
content_type = check_msg.content_type
enc, dec = qpid_messaging.message.get_codec(content_type)
enc(check_msg.content)
except qpid_codec.CodecException:
# This means the message couldn't be serialized as a dict.
msg = self._pack_json_msg(msg)
self.sender.send(msg)
class DirectPublisher(Publisher):
"""Publisher class for 'direct'."""
def __init__(self, conf, session, msg_id):
"""Init a 'direct' publisher."""
if conf.qpid_topology_version == 1:
node_name = msg_id
node_opts = {"type": "direct"}
elif conf.qpid_topology_version == 2:
node_name = "amq.direct/%s" % msg_id
node_opts = {}
else:
raise_invalid_topology_version()
super(DirectPublisher, self).__init__(conf, session, node_name,
node_opts)
class TopicPublisher(Publisher):
"""Publisher class for 'topic'."""
def __init__(self, conf, session, topic):
"""Init a 'topic' publisher.
"""
exchange_name = rpc_amqp.get_control_exchange(conf)
if conf.qpid_topology_version == 1:
node_name = "%s/%s" % (exchange_name, topic)
elif conf.qpid_topology_version == 2:
node_name = "amq.topic/topic/%s/%s" % (exchange_name, topic)
else:
raise_invalid_topology_version()
super(TopicPublisher, self).__init__(conf, session, node_name)
class FanoutPublisher(Publisher):
"""Publisher class for 'fanout'."""
def __init__(self, conf, session, topic):
"""Init a 'fanout' publisher.
"""
if conf.qpid_topology_version == 1:
node_name = "%s_fanout" % topic
node_opts = {"type": "fanout"}
elif conf.qpid_topology_version == 2:
node_name = "amq.topic/fanout/%s" % topic
node_opts = {}
else:
raise_invalid_topology_version()
super(FanoutPublisher, self).__init__(conf, session, node_name,
node_opts)
class NotifyPublisher(Publisher):
"""Publisher class for notifications."""
def __init__(self, conf, session, topic):
"""Init a 'topic' publisher.
"""
exchange_name = rpc_amqp.get_control_exchange(conf)
node_opts = {"durable": True}
if conf.qpid_topology_version == 1:
node_name = "%s/%s" % (exchange_name, topic)
elif conf.qpid_topology_version == 2:
node_name = "amq.topic/topic/%s/%s" % (exchange_name, topic)
else:
raise_invalid_topology_version()
super(NotifyPublisher, self).__init__(conf, session, node_name,
node_opts)
class Connection(object):
"""Connection object."""
pool = None
def __init__(self, conf, server_params=None):
if not qpid_messaging:
raise ImportError("Failed to import qpid.messaging")
self.session = None
self.consumers = {}
self.consumer_thread = None
self.proxy_callbacks = []
self.conf = conf
if server_params and 'hostname' in server_params:
# NOTE(russellb) This enables support for cast_to_server.
server_params['qpid_hosts'] = [
'%s:%d' % (server_params['hostname'],
server_params.get('port', 5672))
]
params = {
'qpid_hosts': self.conf.qpid_hosts,
'username': self.conf.qpid_username,
'password': self.conf.qpid_password,
}
params.update(server_params or {})
self.brokers = params['qpid_hosts']
self.username = params['username']
self.password = params['password']
self.connection_create(self.brokers[0])
self.reconnect()
def connection_create(self, broker):
# Create the connection - this does not open the connection
self.connection = qpid_messaging.Connection(broker)
# Check if flags are set and if so set them for the connection
# before we call open
self.connection.username = self.username
self.connection.password = self.password
self.connection.sasl_mechanisms = self.conf.qpid_sasl_mechanisms
# Reconnection is done by self.reconnect()
self.connection.reconnect = False
self.connection.heartbeat = self.conf.qpid_heartbeat
self.connection.transport = self.conf.qpid_protocol
self.connection.tcp_nodelay = self.conf.qpid_tcp_nodelay
def _register_consumer(self, consumer):
self.consumers[str(consumer.get_receiver())] = consumer
def _lookup_consumer(self, receiver):
return self.consumers[str(receiver)]
def reconnect(self):
"""Handles reconnecting and re-establishing sessions and queues."""
attempt = 0
delay = 1
while True:
# Close the session if necessary
if self.connection.opened():
try:
self.connection.close()
except qpid_exceptions.ConnectionError:
pass
broker = self.brokers[attempt % len(self.brokers)]
attempt += 1
try:
self.connection_create(broker)
self.connection.open()
except qpid_exceptions.ConnectionError as e:
msg_dict = dict(e=e, delay=delay)
msg = _("Unable to connect to AMQP server: %(e)s. "
"Sleeping %(delay)s seconds") % msg_dict
LOG.error(msg)
time.sleep(delay)
delay = min(2 * delay, 60)
else:
LOG.info(_('Connected to AMQP server on %s'), broker)
break
self.session = self.connection.session()
if self.consumers:
consumers = self.consumers
self.consumers = {}
for consumer in six.itervalues(consumers):
consumer.reconnect(self.session)
self._register_consumer(consumer)
LOG.debug(_("Re-established AMQP queues"))
def ensure(self, error_callback, method, *args, **kwargs):
while True:
try:
return method(*args, **kwargs)
except (qpid_exceptions.Empty,
qpid_exceptions.ConnectionError) as e:
if error_callback:
error_callback(e)
self.reconnect()
def close(self):
"""Close/release this connection."""
self.cancel_consumer_thread()
self.wait_on_proxy_callbacks()
try:
self.connection.close()
except Exception:
# NOTE(dripton) Logging exceptions that happen during cleanup just
# causes confusion; there's really nothing useful we can do with
# them.
pass
self.connection = None
def reset(self):
"""Reset a connection so it can be used again."""
self.cancel_consumer_thread()
self.wait_on_proxy_callbacks()
self.session.close()
self.session = self.connection.session()
self.consumers = {}
def declare_consumer(self, consumer_cls, topic, callback):
"""Create a Consumer using the class that was passed in and
add it to our list of consumers
"""
def _connect_error(exc):
log_info = {'topic': topic, 'err_str': str(exc)}
LOG.error(_("Failed to declare consumer for topic '%(topic)s': "
"%(err_str)s") % log_info)
def _declare_consumer():
consumer = consumer_cls(self.conf, self.session, topic, callback)
self._register_consumer(consumer)
return consumer
return self.ensure(_connect_error, _declare_consumer)
def iterconsume(self, limit=None, timeout=None):
"""Return an iterator that will consume from all queues/consumers."""
def _error_callback(exc):
if isinstance(exc, qpid_exceptions.Empty):
LOG.debug(_('Timed out waiting for RPC response: %s') %
str(exc))
raise rpc_common.Timeout()
else:
LOG.exception(_('Failed to consume message from queue: %s') %
str(exc))
def _consume():
nxt_receiver = self.session.next_receiver(timeout=timeout)
try:
self._lookup_consumer(nxt_receiver).consume()
except Exception:
LOG.exception(_("Error processing message. Skipping it."))
for iteration in itertools.count(0):
if limit and iteration >= limit:
raise StopIteration
yield self.ensure(_error_callback, _consume)
def cancel_consumer_thread(self):
"""Cancel a consumer thread."""
if self.consumer_thread is not None:
self.consumer_thread.kill()
try:
self.consumer_thread.wait()
except greenlet.GreenletExit:
pass
self.consumer_thread = None
def wait_on_proxy_callbacks(self):
"""Wait for all proxy callback threads to exit."""
for proxy_cb in self.proxy_callbacks:
proxy_cb.wait()
def publisher_send(self, cls, topic, msg):
"""Send to a publisher based on the publisher class."""
def _connect_error(exc):
log_info = {'topic': topic, 'err_str': str(exc)}
LOG.exception(_("Failed to publish message to topic "
"'%(topic)s': %(err_str)s") % log_info)
def _publisher_send():
publisher = cls(self.conf, self.session, topic)
publisher.send(msg)
return self.ensure(_connect_error, _publisher_send)
def declare_direct_consumer(self, topic, callback):
"""Create a 'direct' queue.
In nova's use, this is generally a msg_id queue used for
responses for call/multicall
"""
self.declare_consumer(DirectConsumer, topic, callback)
def declare_topic_consumer(self, topic, callback=None, queue_name=None,
exchange_name=None):
"""Create a 'topic' consumer."""
self.declare_consumer(functools.partial(TopicConsumer,
name=queue_name,
exchange_name=exchange_name,
),
topic, callback)
def declare_fanout_consumer(self, topic, callback):
"""Create a 'fanout' consumer."""
self.declare_consumer(FanoutConsumer, topic, callback)
def direct_send(self, msg_id, msg):
"""Send a 'direct' message."""
self.publisher_send(DirectPublisher, msg_id, msg)
def topic_send(self, topic, msg, timeout=None):
"""Send a 'topic' message."""
#
# We want to create a message with attributes, e.g. a TTL. We
# don't really need to keep 'msg' in its JSON format any longer
# so let's create an actual qpid message here and get some
# value-add on the go.
#
# WARNING: Request timeout happens to be in the same units as
# qpid's TTL (seconds). If this changes in the future, then this
# will need to be altered accordingly.
#
qpid_message = qpid_messaging.Message(content=msg, ttl=timeout)
self.publisher_send(TopicPublisher, topic, qpid_message)
def fanout_send(self, topic, msg):
"""Send a 'fanout' message."""
self.publisher_send(FanoutPublisher, topic, msg)
def notify_send(self, topic, msg, **kwargs):
"""Send a notify message on a topic."""
self.publisher_send(NotifyPublisher, topic, msg)
def consume(self, limit=None):
"""Consume from all queues/consumers."""
it = self.iterconsume(limit=limit)
while True:
try:
six.next(it)
except StopIteration:
return
def consume_in_thread(self):
"""Consumer from all queues/consumers in a greenthread."""
@excutils.forever_retry_uncaught_exceptions
def _consumer_thread():
try:
self.consume()
except greenlet.GreenletExit:
return
if self.consumer_thread is None:
self.consumer_thread = eventlet.spawn(_consumer_thread)
return self.consumer_thread
def create_consumer(self, topic, proxy, fanout=False):
"""Create a consumer that calls a method in a proxy object."""
proxy_cb = rpc_amqp.ProxyCallback(
self.conf, proxy,
rpc_amqp.get_connection_pool(self.conf, Connection))
self.proxy_callbacks.append(proxy_cb)
if fanout:
consumer = FanoutConsumer(self.conf, self.session, topic, proxy_cb)
else:
consumer = TopicConsumer(self.conf, self.session, topic, proxy_cb)
self._register_consumer(consumer)
return consumer
def create_worker(self, topic, proxy, pool_name):
"""Create a worker that calls a method in a proxy object."""
proxy_cb = rpc_amqp.ProxyCallback(
self.conf, proxy,
rpc_amqp.get_connection_pool(self.conf, Connection))
self.proxy_callbacks.append(proxy_cb)
consumer = TopicConsumer(self.conf, self.session, topic, proxy_cb,
name=pool_name)
self._register_consumer(consumer)
return consumer
def join_consumer_pool(self, callback, pool_name, topic,
exchange_name=None, ack_on_error=True):
"""Register as a member of a group of consumers for a given topic from
the specified exchange.
Exactly one member of a given pool will receive each message.
A message will be delivered to multiple pools, if more than
one is created.
"""
callback_wrapper = rpc_amqp.CallbackWrapper(
conf=self.conf,
callback=callback,
connection_pool=rpc_amqp.get_connection_pool(self.conf,
Connection),
wait_for_consumers=not ack_on_error
)
self.proxy_callbacks.append(callback_wrapper)
consumer = TopicConsumer(conf=self.conf,
session=self.session,
topic=topic,
callback=callback_wrapper,
name=pool_name,
exchange_name=exchange_name)
self._register_consumer(consumer)
return consumer
def create_connection(conf, new=True):
"""Create a connection."""
return rpc_amqp.create_connection(
conf, new,
rpc_amqp.get_connection_pool(conf, Connection))
def multicall(conf, context, topic, msg, timeout=None):
"""Make a call that returns multiple times."""
return rpc_amqp.multicall(
conf, context, topic, msg, timeout,
rpc_amqp.get_connection_pool(conf, Connection))
def call(conf, context, topic, msg, timeout=None):
"""Sends a message on a topic and wait for a response."""
return rpc_amqp.call(
conf, context, topic, msg, timeout,
rpc_amqp.get_connection_pool(conf, Connection))
def cast(conf, context, topic, msg):
"""Sends a message on a topic without waiting for a response."""
return rpc_amqp.cast(
conf, context, topic, msg,
rpc_amqp.get_connection_pool(conf, Connection))
def fanout_cast(conf, context, topic, msg):
"""Sends a message on a fanout exchange without waiting for a response."""
return rpc_amqp.fanout_cast(
conf, context, topic, msg,
rpc_amqp.get_connection_pool(conf, Connection))
def cast_to_server(conf, context, server_params, topic, msg):
"""Sends a message on a topic to a specific server."""
return rpc_amqp.cast_to_server(
conf, context, server_params, topic, msg,
rpc_amqp.get_connection_pool(conf, Connection))
def fanout_cast_to_server(conf, context, server_params, topic, msg):
"""Sends a message on a fanout exchange to a specific server."""
return rpc_amqp.fanout_cast_to_server(
conf, context, server_params, topic, msg,
rpc_amqp.get_connection_pool(conf, Connection))
def notify(conf, context, topic, msg, envelope):
"""Sends a notification event on a topic."""
return rpc_amqp.notify(conf, context, topic, msg,
rpc_amqp.get_connection_pool(conf, Connection),
envelope)
def cleanup():
return rpc_amqp.cleanup(Connection.pool)
|
apache-2.0
|
snowplow/snowplow-unity-tracker
|
SnowplowTracker.Tests/Assets/Tests/TestTracker.cs
|
5574
|
/*
* TestTracker.cs
* SnowplowTrackerTests
*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*
* Authors: Joshua Beemster
* Copyright: Copyright (c) 2015 Snowplow Analytics Ltd
* License: Apache License Version 2.0
*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using SnowplowTrackerTests.TestHelpers;
using SnowplowTracker;
using SnowplowTracker.Emitters;
using SnowplowTracker.Enums;
using SnowplowTracker.Events;
using SnowplowTracker.Payloads;
namespace SnowplowTrackerTests
{
[TestFixture()]
public class TestTracker
{
[Test()]
public void TestTrackerInitMinimal()
{
Tracker t = new Tracker(new AsyncEmitter("acme.com", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L), "aNamespace", "aAppId");
Assert.NotNull(t);
Assert.NotNull(t.GetEmitter());
Assert.Null(t.GetSubject());
Assert.Null(t.GetSession());
Assert.AreEqual("aNamespace", t.GetTrackerNamespace());
Assert.AreEqual("aAppId", t.GetAppId());
Assert.AreEqual(true, t.GetBase64Encoded());
Assert.AreEqual(DevicePlatforms.Mobile.Value, t.GetPlatform().Value);
}
[Test()]
public void TestTrackerInitException()
{
Tracker t = null;
try
{
t = new Tracker(null, "aNamespace", "aAppId");
}
catch (Exception e)
{
Assert.AreEqual("Emitter cannot be null.", e.Message);
}
Assert.Null(t);
}
[Test()]
public void TestTrackerSetterFunctions()
{
Subject s1 = new Subject();
Session sess1 = new Session(null);
IEmitter e1 = new AsyncEmitter("acme.com", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L);
Tracker t = new Tracker(e1, "aNamespace", "aAppId", s1, sess1);
Assert.NotNull(t.GetEmitter());
Assert.AreEqual("http://acme.com/com.snowplowanalytics.snowplow/tp2", t.GetEmitter().GetCollectorUri().ToString());
Assert.NotNull(t.GetSubject());
Assert.NotNull(t.GetSession());
Assert.AreEqual("aNamespace", t.GetTrackerNamespace());
Assert.AreEqual("aAppId", t.GetAppId());
Assert.AreEqual(true, t.GetBase64Encoded());
Assert.AreEqual(DevicePlatforms.Mobile.Value, t.GetPlatform().Value);
IEmitter e2 = new AsyncEmitter("acme.com.au", HttpProtocol.HTTP, HttpMethod.POST, 500, 52000L, 52000L);
t.SetEmitter(e2);
Assert.AreEqual("http://acme.com.au/com.snowplowanalytics.snowplow/tp2", t.GetEmitter().GetCollectorUri().ToString());
t.SetSession(null);
Assert.Null(t.GetSession());
t.SetSubject(null);
Assert.Null(t.GetSubject());
t.SetTrackerNamespace("newNamespace");
Assert.AreEqual("newNamespace", t.GetTrackerNamespace());
t.SetAppId("newAppId");
Assert.AreEqual("newAppId", t.GetAppId());
t.SetBase64Encoded(false);
Assert.AreEqual(false, t.GetBase64Encoded());
t.SetPlatform(DevicePlatforms.Desktop);
Assert.AreEqual(DevicePlatforms.Desktop.Value, t.GetPlatform().Value);
}
[Test()]
public void TestTrackerSendEvent()
{
IEmitter e1 = new BaseEmitter();
Tracker t = new Tracker(e1, "aNamespace", "aAppId");
t.StartEventTracking();
t.Track(new PageView().SetPageTitle("title").SetPageUrl("url").SetReferrer("ref").SetTimestamp(1234567890).SetEventId("event-id-custom").Build());
t.Track(new PageView().SetPageTitle("title").SetPageUrl("url").SetReferrer("ref").SetTimestamp(1234567890).SetEventId("event-id-custom").Build());
BaseEmitter te1 = (BaseEmitter)t.GetEmitter();
Assert.AreEqual(2, te1.payloads.Count);
foreach (TrackerPayload payload in te1.payloads)
{
Dictionary<string, object> dict = payload.GetDictionary();
Assert.AreEqual(SnowplowTracker.Version.VERSION, dict[Constants.TRACKER_VERSION]);
Assert.AreEqual("1234567890", dict[Constants.TIMESTAMP]);
Assert.AreEqual("event-id-custom", dict[Constants.EID]);
Assert.AreEqual("aNamespace", dict[Constants.NAMESPACE]);
Assert.AreEqual("aAppId", dict[Constants.APP_ID]);
Assert.AreEqual("mob", dict[Constants.PLATFORM]);
Assert.AreEqual(Constants.EVENT_PAGE_VIEW, dict[Constants.EVENT]);
Assert.AreEqual("title", dict[Constants.PAGE_TITLE]);
Assert.AreEqual("url", dict[Constants.PAGE_URL]);
Assert.AreEqual("ref", dict[Constants.PAGE_REFR]);
}
}
}
}
|
apache-2.0
|
William-Yeh/build-docker-with-ansible
|
lab-nginx/step-2/Dockerfile
|
406
|
# Dockerfile for building image that contains software stack provisioned by Ansible.
#
# pull base image
FROM williamyeh/ansible:debian8-onbuild
MAINTAINER William Yeh <[email protected]>
#
# build phase
#
#ENV PLAYBOOK playbook.yml
RUN ansible-playbook-wrapper
#
# runtime spec
#
EXPOSE 80
#
# fix for Docker process execution model
#
ENTRYPOINT [ "nginx" ]
CMD [ "-g", "daemon off;" ]
|
apache-2.0
|
SkyRocketGWT/skyrocketgwt
|
skyrocket-core/src/main/java/com/skyrocketgwt/core/client/layouts/layoutpanel/appearance/SkySplitterAppearance.java
|
237
|
package com.skyrocketgwt.core.client.layouts.layoutpanel.appearance;
import com.google.gwt.dom.client.Element;
/**
* Created by v on 2/22/2015.
*/
public interface SkySplitterAppearance {
Element render(double splitterSize);
}
|
apache-2.0
|
firstbytegithub/MyCodeRepo
|
app/src/main/java/com/example/chengqi/mycoderepo/layouts/RelativeLayoutActivity.java
|
415
|
package com.example.chengqi.mycoderepo.layouts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.chengqi.mycoderepo.R;
public class RelativeLayoutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relative_layout);
}
}
|
apache-2.0
|
trevor/calendarserver
|
twistedcaldav/test/test_memcacheprops.py
|
14385
|
##
# Copyright (c) 2009-2014 Apple Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##
"""
Test memcacheprops.
"""
import os
from txweb2.http import HTTPError
from txdav.xml.base import encodeXMLName
from twistedcaldav.memcacheprops import MemcachePropertyCollection
from twistedcaldav.test.util import InMemoryPropertyStore
from twistedcaldav.test.util import TestCase
class StubCollection(object):
def __init__(self, path, childNames):
self.path = path
self.fp = StubFP(path)
self.children = {}
for childName in childNames:
self.children[childName] = StubResource(self, path, childName)
def listChildren(self):
return self.children.iterkeys()
def getChild(self, childName):
return self.children[childName]
def propertyCollection(self):
if not hasattr(self, "_propertyCollection"):
self._propertyCollection = MemcachePropertyCollection(self)
return self._propertyCollection
class StubResource(object):
def __init__(self, parent, path, name):
self.parent = parent
self.fp = StubFP(os.path.join(path, name))
def deadProperties(self):
if not hasattr(self, "_dead_properties"):
self._dead_properties = self.parent.propertyCollection().propertyStoreForChild(self, InMemoryPropertyStore())
return self._dead_properties
class StubFP(object):
def __init__(self, path):
self.path = path
def child(self, childName):
class _Child(object):
def __init__(self, path):
self.path = path
return _Child(os.path.join(self.path, childName))
def basename(self):
return os.path.basename(self.path)
class StubProperty(object):
def __init__(self, ns, name, value=None):
self.ns = ns
self.name = name
self.value = value
def qname(self):
return self.ns, self.name
def __repr__(self):
return "%s = %s" % (encodeXMLName(self.ns, self.name), self.value)
class MemcachePropertyCollectionTestCase(TestCase):
"""
Test MemcacheProprtyCollection
"""
def getColl(self):
return StubCollection("calendars", ["a", "b", "c"])
def test_setget(self):
child1 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child2 = self.getColl().getChild("a")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val1")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val2"))
# force memcache to be consulted (once per collection per request)
child1 = self.getColl().getChild("a")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1")).value,
"val2")
def test_merge(self):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0"))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val3"))
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val1")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3")).value,
"val3")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1")).value,
"val1")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val3")
def test_delete(self):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0"))
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0"))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1"))
child1.deadProperties().delete(("ns1:", "prop1"))
self.assertRaises(HTTPError, child1.deadProperties().get, ("ns1:", "prop1"))
self.assertFalse(child1.deadProperties().contains(("ns1:", "prop1")))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3")).value,
"val0")
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertFalse(child2.deadProperties().contains(("ns1:", "prop1")))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2")).value,
"val0")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3")).value,
"val0")
def test_setget_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child2 = self.getColl().getChild("a")
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val2%s" % (uid if uid else "",)), uid=uid)
# force memcache to be consulted (once per collection per request)
child1 = self.getColl().getChild("a")
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val2%s" % (uid if uid else "",))
def test_merge_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0%s" % (uid if uid else "",)), uid=uid)
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val3%s" % (uid if uid else "",)), uid=uid)
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val3%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val1%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val3%s" % (uid if uid else "",))
def test_delete_uids(self):
for uid in (None, "123", "456"):
child1 = self.getColl().getChild("a")
child2 = self.getColl().getChild("a")
child1.deadProperties().set(StubProperty("ns1:", "prop1", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop2", value="val0%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().set(StubProperty("ns1:", "prop3", value="val0%s" % (uid if uid else "",)), uid=uid)
self.assertEquals(child2.deadProperties().get(("ns1:", "prop1"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
child2.deadProperties().set(StubProperty("ns1:", "prop1", value="val1%s" % (uid if uid else "",)), uid=uid)
child1.deadProperties().delete(("ns1:", "prop1"), uid=uid)
self.assertRaises(HTTPError, child1.deadProperties().get, ("ns1:", "prop1"), uid=uid)
self.assertFalse(child1.deadProperties().contains(("ns1:", "prop1"), uid=uid))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child1.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
# force memcache to be consulted (once per collection per request)
child2 = self.getColl().getChild("a")
# verify properties
self.assertFalse(child2.deadProperties().contains(("ns1:", "prop1"), uid=uid))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop2"), uid=uid).value,
"val0%s" % (uid if uid else "",))
self.assertEquals(child2.deadProperties().get(("ns1:", "prop3"), uid=uid).value,
"val0%s" % (uid if uid else "",))
def _stub_set_multi(self, values, time=None):
self.callCount += 1
for key, value in values.iteritems():
self.results[key] = value
def test_splitSetMulti(self):
self.callCount = 0
self.results = {}
mpc = MemcachePropertyCollection(None)
values = {}
for i in xrange(600):
values["key%d" % (i,)] = "value%d" % (i,)
mpc._split_set_multi(values, self._stub_set_multi)
self.assertEquals(self.callCount, 3)
self.assertEquals(self.results, values)
def test_splitSetMultiWithChunksize(self):
self.callCount = 0
self.results = {}
mpc = MemcachePropertyCollection(None)
values = {}
for i in xrange(13):
values["key%d" % (i,)] = "value%d" % (i,)
mpc._split_set_multi(values, self._stub_set_multi, chunksize=3)
self.assertEquals(self.callCount, 5)
self.assertEquals(self.results, values)
def _stub_gets_multi(self, keys):
self.callCount += 1
result = {}
for key in keys:
result[key] = self.expected[key]
return result
def test_splitGetsMulti(self):
self.callCount = 0
self.expected = {}
keys = []
for i in xrange(600):
keys.append("key%d" % (i,))
self.expected["key%d" % (i,)] = "value%d" % (i,)
mpc = MemcachePropertyCollection(None)
result = mpc._split_gets_multi(keys, self._stub_gets_multi)
self.assertEquals(self.callCount, 3)
self.assertEquals(self.expected, result)
def test_splitGetsMultiWithChunksize(self):
self.callCount = 0
self.expected = {}
keys = []
for i in xrange(600):
keys.append("key%d" % (i,))
self.expected["key%d" % (i,)] = "value%d" % (i,)
mpc = MemcachePropertyCollection(None)
result = mpc._split_gets_multi(keys, self._stub_gets_multi, chunksize=12)
self.assertEquals(self.callCount, 50)
self.assertEquals(self.expected, result)
|
apache-2.0
|
yvasilevskaya/java_pft
|
sandbox/src/main/java/ru/stqa/pft/sandbox/Equality.java
|
279
|
package ru.stqa.pft.sandbox;
/**
* Created by Yulia on 3/1/2017.
*/
public class Equality {
public static void main(String [] args){
String s1 = "firefox";
String s2 = new String(s1);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
|
apache-2.0
|
zy4kamu/Coda
|
src/nlp-stack/Disambiguator/Core/Settings/IDisambiguatorSettings.h
|
2747
|
/**
*
* .. invisible:
* _ _ _____ _ _____ _____
*
* | | | | ___| | | ___/ ___|
*
* | | | | |__ | | | |__ \ `--.
*
* | | | | __|| | | __| `--. \
*
* \ \_/ / |___| |___| |___/\__/ /
*
* \___/\____/\_____|____/\____/
*
* 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
*
*/
#ifndef DISAMBIGUATOR_SETTINGS_INTERFACE
#define DISAMBIGUATOR_SETTINGS_INTERFACE
#include "MorphologicalDictionary.h"
#include "ICRFSettings.h"
#include "IDisambiguator.h"
#include "IFeatureCalculator.h"
namespace Disambiguation
{
using Tools::Language;
class IDisambiguatorSettings : public virtual LinearCRF::ICRFSettings
{
public:
virtual shared_ptr<IChainTransformer> GetChainTransformer() = 0;
virtual shared_ptr<IPossibleStateFinder> GetPossibleStateFinder() = 0;
virtual shared_ptr<IRegularization> GetRegularizator() = 0;
virtual shared_ptr<RelearnRegularization> GetRelearnRegularizator() = 0;
virtual shared_ptr<MorphologicalDictionary> GetDictionary() = 0;
virtual shared_ptr<IFeatureCalculator> GetFeatureCalculator() = 0;
virtual shared_ptr<DataFunctor> GetTrainingFunctor() = 0;
virtual shared_ptr<DataFunctor> GetTestFunctor() = 0;
virtual const string& GetIntermidiateOutputFile() const = 0;
virtual size_t GetMaxNumberOfIterations() const = 0;
virtual const string& GetModelFile() const = 0;
virtual size_t GetPeriodOfTesting() const = 0;
virtual const string& GetTrainingSetFile() const = 0;
virtual const string& GetTestSetFile() const = 0;
virtual const string& GetTokenLabelSetFile() const = 0;
virtual const string& GetRelearnSetFile() const = 0;
virtual const string& GetRelearnInputSetFile() const = 0;
virtual bool IsModelFileBinary() const = 0;
virtual Language GetLanguage() const = 0;
virtual shared_ptr<IDisambiguator> GetDisambiguator() = 0;
virtual shared_ptr<IDisambiguator> ReloadDisambiguator() = 0;
};
}
#endif // DISAMBIGUATOR_SETTINGS_INTERFACE
|
apache-2.0
|
vpalex999/python_training
|
fixture/application.py
|
1165
|
# -*- coding: utf-8 -*-
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.address import AddressHelper
class Application(object):
def __init__(self, browser, base_url):
if browser == "firefox":
self.wd = webdriver.Firefox()
elif browser == 'chrome':
self.wd = webdriver.Chrome()
elif browser == "ie":
self.wd = webdriver.Ie()
else:
raise ValueError(f"Unrecognized browser {browser}")
self.wd.implicitly_wait(3)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.address = AddressHelper(self)
self.base_url = base_url
self.open_home_page()
def open_home_page(self):
# open homepage
wd = self.wd
if not (wd.current_url.endswith("/addressbook/") and wd.find_element_by_name("searchstring")):
wd.get(self.base_url)
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False
def destroy(self):
self.wd.quit()
|
apache-2.0
|
shwinpiocess/fire
|
job/static/job/css/newTask.css
|
1790
|
@CHARSET "UTF-8";
ul.group-ul,ul.group-node-ul{
margin:0;
padding:0;
}
ul.group-ul>li,ul.group-node-ul>li{
margin:0;
padding:0;
}
li.group-li{
padding:5px 0!important;
}
.group-node-table{
margin-bottom: 0;
}
.group-node-header .group-node-table{
background-color:#f0f0f0;
}
.group-node-top{
height: 45px;
color: #676a6c;
position: relative;
}
.group-node-top1{background:#69BD69;}
.group-node-top2{background:#6A97D0;}
.group-name-input{
width: 200px;
display: inline-block;
}
.step-down,.step-up,.step-cut,.step-close{
position: absolute; top: 2px;color:#676a6c;
}
.step-down,.step-up{
right: 50px;
}
.step-close{
right:8px;
}
.step-cut{
right:96px;
}
.step-down-right,.step-up-right{position: absolute; right:8px;color:#676a6c;top:2px;}
.group-node-footer{
border: 1px solid #ccc;
height: 45px;
background: #f6f8f8;
position: relative;
}
tr.name-tr td,tr.name-tr th{
width:20%;
}
td.td_step_oper i{
margin-left: 0!important;
margin-right: 0!important;
}
.step_oper_div{width:auto;min-width:220px;}
.step_oper_div_min{width:auto;min-width:180px;}
.show-step{cursor:pointer;}
.ijobs-required:before{
content:"* ";
color:red;
}
/* 服务器集结果显示 */
.serverIp-result-table.h300 td,.serverIp-result-table.h300 th,.serverIpResultTable td,.serverIpResultTable th{
text-align:center;
}
.file-table td,.file-table th{text-align:center;}
.serverIp-result-table.h300 table.dataTable thead > tr > th{padding-right:8px;}
/* 新建步骤 */
.add-node{font-size:15px;margin-top:15px;display:inline-block;margin-left:10px;color:#2985c2;}
/* 添加步骤 */
.add-step{display:inline-block;position:relative;}
.add-step ul{display:none;position:absolute;margin:0;padding:0;}
.add-step ul a,.add-step button{width:120px;}
.add-step:hover ul{display:block;}
|
apache-2.0
|
Luehrsen/good_morning_news
|
www/wp-content/plugins/goodmorning_plugin/js/admin.js
|
787
|
jQuery(document).ready(function($){
$("a[data-upvote-id]").click(function(){
var id = $(this).attr('data-upvote-id');
$.ajax( {
url: WP_API_Settings.root + 'goodmorning-news/1.0/upvote/' + id,
method: 'GET',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
}
} ).done( function ( response ) {
console.log( response );
} );
});
$("a[data-downvote-id]").click(function(){
var id = $(this).attr('data-downvote-id');
$.ajax( {
url: WP_API_Settings.root + 'goodmorning-news/1.0/downvote/' + id,
method: 'GET',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WP_API_Settings.nonce );
}
} ).done( function ( response ) {
console.log( response );
} );
});
});
|
apache-2.0
|
blackcathacker/kc.preclean
|
coeus-db/coeus-db-sql/src/main/resources/org/kuali/coeus/coeus-sql/log/Release_2_0_logs/KCIRB-195a.sql
|
104
|
alter table protocol_actions drop column action_date;
alter table protocol_actions add action_date date;
|
apache-2.0
|
hkbhkb7/online_complaitbox
|
login.php
|
672
|
<?php include 'db.php';?>
<?php
if(isset($_POST["login-submit"]))
{
$sql="SELECT
`email`,
`passwd`
FROM
`register`
WHERE
email ='".$_POST['email']."';";
if($res = $mysqli->query($sql))
{
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
if($row['email'] == $_POST['email'] && $row['passwd'] == $_POST['passwd'])
{
echo '<script> window.location.href = "type.html";';
echo '</script>';
}
else
{
echo "<script> alert('invalid username or password');";
echo 'window.location.href = "login.html";';
echo '</script>';
}
}
}
}
}
?>
|
apache-2.0
|
githubdiarra/playground-repo
|
playground/src/main/java/edu/mycourses/adt/st/BasicST.java
|
407
|
/**
*
*/
package edu.mycourses.adt.st;
/**
* @author Ibrahima Diarra
*
*/
public class BasicST<Key, Value> extends AbstractST<Key, Value> {
@Override
public void put(Key key, Value value) {
}
@Override
public Value get(Key key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterable<Key> keys() {
return null;
}
}
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.4.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/undertow/configuration/class-use/RewriteConsumer.html
|
12361
|
<!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_151) on Wed Jul 17 09:40:07 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.undertow.configuration.RewriteConsumer (BOM: * : All 2.4.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-07-17">
<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 Interface org.wildfly.swarm.config.undertow.configuration.RewriteConsumer (BOM: * : All 2.4.1.Final-SNAPSHOT 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="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-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">Thorntail API, 2.4.1.Final-SNAPSHOT</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/undertow/configuration/class-use/RewriteConsumer.html" target="_top">Frames</a></li>
<li><a href="RewriteConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.undertow.configuration.RewriteConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.undertow.configuration.RewriteConsumer</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="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</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.undertow">org.wildfly.swarm.config.undertow</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.undertow.configuration">org.wildfly.swarm.config.undertow.configuration</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.undertow">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/undertow/FilterConfiguration.html" title="type parameter in FilterConfiguration">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">FilterConfiguration.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/undertow/FilterConfiguration.html#rewrite-java.lang.String-org.wildfly.swarm.config.undertow.configuration.RewriteConsumer-">rewrite</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> childKey,
<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a> consumer)</code>
<div class="block">Create and configure a Rewrite object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.undertow.configuration">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/package-summary.html">org.wildfly.swarm.config.undertow.configuration</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/package-summary.html">org.wildfly.swarm.config.undertow.configuration</a> that return <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="type parameter in RewriteConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">RewriteConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html#andThen-org.wildfly.swarm.config.undertow.configuration.RewriteConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="type parameter in RewriteConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/package-summary.html">org.wildfly.swarm.config.undertow.configuration</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="type parameter in RewriteConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">RewriteConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html#andThen-org.wildfly.swarm.config.undertow.configuration.RewriteConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">RewriteConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="type parameter in RewriteConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="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="../../../../../../../org/wildfly/swarm/config/undertow/configuration/RewriteConsumer.html" title="interface in org.wildfly.swarm.config.undertow.configuration">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-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">Thorntail API, 2.4.1.Final-SNAPSHOT</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/undertow/configuration/class-use/RewriteConsumer.html" target="_top">Frames</a></li>
<li><a href="RewriteConsumer.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 © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
nmcspadden/PrinterGenerator
|
print_generator.py
|
10809
|
#!/usr/bin/python
from __future__ import absolute_import, print_function
import argparse
import csv
import os
import re
import sys
try:
from plistlib import load as load_plist # Python 3
from plistlib import dump as dump_plist
except ImportError:
from plistlib import readPlist as load_plist # Python 2
from plistlib import writePlist as dump_plist
def getOptionsString(optionList):
# optionList should be a list item
optionsString = ''
for option in optionList:
if option == optionList[-1]:
optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1]))
else:
optionsString += "\"%s\":\"%s\"" % (str(option.split('=')[0]), str(option.split('=')[1])) + ', '
return optionsString
parser = argparse.ArgumentParser(description='Generate a Munki nopkg-style pkginfo for printer installation.')
parser.add_argument('--printername', help='Name of printer queue. May not contain spaces, tabs, # or /. Required.')
parser.add_argument('--driver', help='Name of driver file in /Library/Printers/PPDs/Contents/Resources/. Can be relative or full path. Required.')
parser.add_argument('--address', help='IP or DNS address of printer. If no protocol is specified, defaults to lpd://. Required.')
parser.add_argument('--location', help='Location name for printer. Optional. Defaults to printername.')
parser.add_argument('--displayname', help='Display name for printer (and Munki pkginfo). Optional. Defaults to printername.')
parser.add_argument('--desc', help='Description for Munki pkginfo only. Optional.')
parser.add_argument('--requires', help='Required packages in form of space-delimited \'CanonDriver1 CanonDriver2\'. Optional.')
parser.add_argument('--options', nargs='*', dest='options', help='Printer options in form of space-delimited \'Option1=Key Option2=Key Option3=Key\', etc. Optional.')
parser.add_argument('--version', help='Version number of Munki pkginfo. Optional. Defaults to 1.0.', default='1.0')
parser.add_argument('--icon', help='Specifies an existing icon in the Munki repo to display for the printer in Managed Software Center. Optional.')
parser.add_argument('--csv', help='Path to CSV file containing printer info. If CSV is provided, all other options are ignored.')
args = parser.parse_args()
pwd = os.path.dirname(os.path.realpath(__file__))
f = open(os.path.join(pwd, 'AddPrinter-Template.plist'), 'rb')
templatePlist = load_plist(f)
f.close()
if args.csv:
# A CSV was found, use that for all data.
with open(args.csv, mode='r') as infile:
reader = csv.reader(infile)
next(reader, None) # skip the header row
for row in reader:
newPlist = dict(templatePlist)
# each row contains 10 elements:
# Printer name, location, display name, address, driver, description, options, version, requires, icon
# options in the form of "Option=Value Option2=Value Option3=Value"
# requires in the form of "package1 package2" Note: the space seperator
theOptionString = ''
if row[6] != "":
theOptionString = getOptionsString(row[6].split(" "))
# First, change the plist keys in the pkginfo itself
newPlist['display_name'] = row[2]
newPlist['description'] = row[5]
newPlist['name'] = "AddPrinter_" + str(row[0]) # set to printer name
# Check for an icon
if row[9] != "":
newPlist['icon_name'] = row[9]
# Check for a version number
if row[7] != "":
# Assume the user specified a version number
version = row[7]
else:
# Use the default version of 1.0
version = "1.0"
newPlist['version'] = version
# Check for a protocol listed in the address
if '://' in row[3]:
# Assume the user passed in a full address and protocol
address = row[3]
else:
# Assume the user wants to use the default, lpd://
address = 'lpd://' + row[3]
# Append the driver path to the driver file specified in the csv
driver = '/Library/Printers/PPDs/Contents/Resources/%s' % row[4]
base_driver = row[4]
if row[4].endswith('.gz'):
base_driver = row[4].replace('.gz', '')
if base_driver.endswith('.ppd'):
base_driver = base_driver.replace('.ppd', '')
# Now change the variables in the installcheck_script
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("PRINTERNAME", row[0])
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", theOptionString)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", row[1].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DRIVER", base_driver)
# Now change the variables in the postinstall_script
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("PRINTERNAME", row[0])
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", row[1].replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", row[2].replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", theOptionString)
# Now change the one variable in the uninstall_script
newPlist['uninstall_script'] = newPlist['uninstall_script'].replace("PRINTERNAME", row[0])
# Add required packages if passed in the csv
if row[8] != "":
newPlist['requires'] = row[8].split(' ')
# Write out the file
newFileName = "AddPrinter-" + row[0] + "-" + version + ".pkginfo"
f = open(newFileName, 'wb')
dump_plist(newPlist, f)
f.close()
else:
if not args.printername:
print(os.path.basename(sys.argv[0]) + ': error: argument --printername is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if not args.driver:
print(os.path.basename(sys.argv[0]) + ': error: argument --driver is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if not args.address:
print(os.path.basename(sys.argv[0]) + ': error: argument --address is required', file=sys.stderr)
parser.print_usage()
sys.exit(1)
if re.search(r"[\s#/]", args.printername):
# printernames can't contain spaces, tabs, # or /. See lpadmin manpage for details.
print("ERROR: Printernames can't contain spaces, tabs, # or /.", file=sys.stderr)
sys.exit(1)
if args.desc:
description = args.desc
else:
description = ""
if args.displayname:
displayName = args.displayname
else:
displayName = str(args.printername)
if args.location:
location = args.location
else:
location = args.printername
if args.version:
version = str(args.version)
else:
version = "1.0"
if args.requires:
requires = args.requires
else:
requires = ""
if args.icon:
icon = args.icon
else:
icon = ""
if args.options:
optionsString = str(args.options[0]).split(' ')
optionsString = getOptionsString(optionsString)
else:
optionsString = ''
if args.driver.startswith('/Library'):
# Assume the user passed in a full path rather than a relative filename
driver = args.driver
else:
# Assume only a relative filename
driver = os.path.join('/Library/Printers/PPDs/Contents/Resources', args.driver)
if '://' in args.address:
# Assume the user passed in a full address and protocol
address = args.address
else:
# Assume the user wants to use the default, lpd://
address = 'lpd://' + args.address
newPlist = dict(templatePlist)
# root pkginfo variable replacement
newPlist['description'] = description
newPlist['display_name'] = displayName
newPlist['name'] = "AddPrinter_" + displayName.replace(" ", "")
newPlist['version'] = version
newPlist['icon_name'] = icon
# installcheck_script variable replacement
newPlist['installcheck_script'] = templatePlist['installcheck_script'].replace("PRINTERNAME", args.printername)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("ADDRESS", address)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DISPLAY_NAME", displayName)
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("LOCATION", location.replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("DRIVER", os.path.splitext(os.path.basename(driver))[0].replace('"', ''))
newPlist['installcheck_script'] = newPlist['installcheck_script'].replace("OPTIONS", optionsString)
# postinstall_script variable replacement
newPlist['postinstall_script'] = templatePlist['postinstall_script'].replace("PRINTERNAME", args.printername)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("ADDRESS", address)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DISPLAY_NAME", displayName)
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("LOCATION", location.replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("DRIVER", driver.replace('"', ''))
newPlist['postinstall_script'] = newPlist['postinstall_script'].replace("OPTIONS", optionsString)
# uninstall_script variable replacement
newPlist['uninstall_script'] = templatePlist['uninstall_script'].replace("PRINTERNAME", args.printername)
# required packages
if requires != "":
newPlist['requires'] = [r.replace('\\', '') for r in re.split(r"(?<!\\)\s", requires)]
newFileName = "AddPrinter-" + str(args.printername) + "-%s.pkginfo" % str(version)
f = open(newFileName, 'wb')
dump_plist(newPlist, f)
f.close()
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Bryophyta/Bryopsida/Funariales/Funariaceae/Funaria/Funaria beyrichii/README.md
|
187
|
# Funaria beyrichii Hampe, 1879 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
bruiserventures/bruiserventures.github.io
|
legal/terms_of_use.html
|
38130
|
<!DOCTYPE html>
<!--[if lt IE 7 ]><html lang="en-US" class="no-js ie ie6 lte7 lte8 lte9"><![endif]-->
<!--[if IE 7 ]><html lang="en-US" class="no-js ie ie7 lte7 lte8 lte9"><![endif]-->
<!--[if IE 8 ]><html lang="en-US" class="no-js ie ie8 lte8 lte9"><![endif]-->
<!--[if IE 9 ]><html lang="en-US" class="no-js ie ie9 lte9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en-US" class="no-js"><!--<![endif]-->
<head>
<!-- metadata -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Bruiser Ventures</title>
<!-- Bootstrap Core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/bv.css" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<meta name="theme-color" content="#ffffff">
<!-- javascripts -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script>
$('.carousel').carousel({
interval: 5000 //changes the speed
})
</script>
</head>
<body>
<div class="brand">Bruiser Ventures</div>
<div class="address-bar">
<strong>Data Science & Analytics Startup Incubator & VC Partner</strong><br><br>
Atlanta | Knoxville | Austin
</div>
<!-- Navigation -->
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-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>
<!-- navbar-brand is hidden on larger screens, but visible when the menu is collapsed -->
<a class="navbar-brand" href="/index.html">Bruiser Ventures</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="/index.html">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
<strong>Terms of Service</strong>
</h2>
<hr>
<p>Last Updated: April 24, 2015</p>
<p>Welcome, and thank you for your interest in Bruiser Ventures,
LLC. (“BV”, “we,” or “us”) and our Web site at www.bruiser-ventures.com (the
“Site”), as well as all related mobile applications (including tablet
applications), and other services provided by us and on which a link
to these Terms of Service is displayed (collectively, together with
the Site, our “Service”). These Terms of Service are a legally binding
contract between you and BV regarding your use of the Service.</p>
<p>PLEASE READ THE FOLLOWING TERMS OF USE CAREFULLY. BY CLICKING “I
ACCEPT,” YOU ACKNOWLEDGE THAT YOU HAVE READ, UNDERSTOOD, AND AGREE TO
BE BOUND BY THE FOLLOWING TERMS AND CONDITIONS, INCLUDING THE BV
PRIVACY POLICY (COLLECTIVELY, THESE “TERMS”). If you are not eligible,
or do not agree to these Terms, then please do not use the
Service.</p>
<p>These Terms of Service provide that all disputes between you and BV
will be resolved by binding arbitration. YOU AGREE TO GIVE UP YOUR
RIGHT TO GO TO COURT TO ASSERT OR DEFEND YOUR RIGHTS UNDER THIS
CONTRACT (except for matters that may be taken to small claims
court). YOUR RIGHTS WILL BE DETERMINED BY A NEUTRAL ARBITRATOR AND NOT
A JUDGE OR JURY AND YOUR CLAIMS CANNOT BE BROUGHT AS A CLASS
ACTION. Please review the Arbitration provision in Section 19 below
for the details regarding your agreement to arbitrate any disputes
with BV.<br> 1. BV Service Overview. BV is based on an open-source
software platform that enables data science, advanced analytics, and
machine learning on large datasets.<br> 2. Eligibility. You must be
at least 18 years of age to use the Service. By accepting these terms
or registering for an account for the Service, you represent and
warrant to us: (i) that you are at least 18 years of age; (ii) that
you have not previously been suspended or removed from the Service;
and (iii) that your registration and your use of the Service is in
compliance with any and all applicable laws and regulations. If you
are using the Service on behalf of an entity, organization, or
company, you represent and warrant that you have the authority to bind
that organization to these Terms and you agree to be bound by these
Terms on behalf of that organization.<br> 3. Permission to Use the
Service. Subject to your compliance with these Terms, BV grants to you
a personal, limited, non-exclusive, non-transferable, freely revocable
right and license to access and use the Service and the content made
available via the Service. Certain software made available on or
through the Service may be provided to you under its own licensing
terms.<br> 4. Accounts and Registration. To access most features of
the Service, you must register for an account. When you register for
an account, you may be required to provide us with some information
about yourself (such as your e-mail address or other contact
information). Because we may only permit you to register for an
account for the Service by providing your credentials for certain
third party authentication services (each, an “Authentication
Service”), such as Google or Github, you may also be required to
provide your Google ID, Github ID, or your login credentials for
another Authentication Service. The applicable Authentication Service
may also ask you to provide a password for your account with that
Authentication Service. You agree that the information you provide to
us is accurate and that you will keep it accurate and up-to-date at
all times. By registering for an account for the Service by providing
any account information through an Authentication Service, you agree
that BV may access and use any account information from the
Authentication Service that you have configured to be made available
to third parties in this manner, and you agree to the terms of use of
the Authentication Service regarding your use of the Service via the
Authentication Service. You further agree that any Authentication
Service is a Linked Site (as defined below) and you are solely
responsible for your interactions with the Authentication Service as a
result of accessing the Service through the Authentication
Service. You are solely responsible for maintaining the
confidentiality of your account. You agree to accept responsibility
for all activities that occur under your account. If you have reason
to believe that your account is no longer secure, then you must
immediately notify us at [email protected].<br>
5. Payment. The Service is currently offered to you free of
charge. However, BV reserves the right to charge subscription fees,
now or in the future, for the use of the Service or any part
thereof. You agree to pay to BV all fees for services purchased on or
through the Service under your account at the then-current rates for
those services (including any applicable taxes). For any change in
fees, BV will send you a notice of the change in advance of
commencement (via a message on or through the Service or email).<br>
6. User Content<br> 6.1 User Content Generally. Certain features of
the Service may permit users to upload content, including, without
limitation, data, text, software code, images, and other types of
works (collectively, “User Content”). You retain copyright and any
other proprietary rights that you may hold in the User Content that
you post to the Service.<br> 6.2 Limited License Grant to BV. By
posting or publishing User Content, you grant BV a worldwide,
non-exclusive, fully paid-up, royalty-free, perpetual, sublicensable,
and transferable license to host, store, use, transfer, display,
perform, reproduce, modify, and distribute your User Content and
derivatives thereof, in whole or in part, in any media formats and
through any media channels (now known or hereafter developed), for the
purpose of providing you with the Service and the current and future
services, features and functionality available on or through it, and
for our internal business purposes.<br> 6.3 Limited License Grant to
Other Users. The Service may permit you to share the User Content you
post with other users of the Service. By posting and sharing User
Content with another user of the Service, you hereby grant that user a
non-exclusive license to access and use that User Content as permitted
by these Terms and the functionality of the Service.<br> 6.4 User
Content Representations and Warranties. You are solely responsible for
your User Content and the consequences of posting or publishing User
Content. By posting and publishing User Content, you affirm,
represent, and warrant that:<br> * you are the creator and owner of,
or have the necessary licenses, rights, consents, and permissions to
use and to authorize BV and users of the Service to use and distribute
your User Content as necessary to exercise the licenses granted by you
in this Section 6 and in the manner contemplated by BV and these
Terms; and<br> * your User Content, and the use thereof as
contemplated herein, does not and will not: (i) infringe, violate, or
misappropriate any third-party right, including any copyright,
trademark, patent, trade secret, moral right, privacy right, right of
publicity, or any other intellectual property or proprietary right; or
(ii) slander, defame, libel any third party.<br> 6.5 User Content
Disclaimer. We are under no obligation to edit or control User Content
that you or other users post or publish, and will not be in any way
responsible or liable for User Content. BV may, however, at any time
and without prior notice, screen, remove, edit, or block any User
Content that in our sole judgment violates these Terms or is otherwise
objectionable. You understand that when using the Service you will be
exposed to User Content from a variety of sources and acknowledge that
User Content may be inaccurate, offensive, indecent or
objectionable. You agree to waive, and hereby do waive, any legal or
equitable rights or remedies you have or may have against BV with
respect to User Content. We expressly disclaim any and all liability
in connection with User Content. If notified by a user or content
owner that User Content allegedly does not conform to these Terms, we
may investigate the allegation and determine in our sole discretion
whether to remove the User Content, which we reserve the right to do
at any time and without notice. For clarity, BV does not permit
copyright-infringing activities on the Service.<br> 7. Digital
Millennium Copyright Act<br> 7.1 DMCA Notification. We comply with the
provisions of the Digital Millennium Copyright Act applicable to
internet service providers (17 U.S.C. §512, as amended). If you have
any complaints with respect to material posted on the Service, you may
contact our Designated Agent at the following address:</p>
<p>DMCA c/o BV Inc.<br> PO Box 1036 1237 E WEISGARBER
RD<br>KNOXVILLE, TN 37950-9831<br>Email:
[email protected]</p>
<p>Any notice alleging that materials hosted by or distributed through
the Service infringe intellectual property rights must include the
following information:<br> a. an electronic or physical signature of
the person authorized to act on behalf of the owner of the copyright
or other right being infringed;<br> b. a description of the
copyrighted work or other intellectual property that you claim has
been infringed;<br> c. a description of the material that you claim is
infringing and where it is located on the Service;<br> d. your
address, telephone number, and email address;<br> e. a statement by
you that you have a good faith belief that the use of the materials on
the Service of which you are complaining is not authorized by the
copyright owner, its agent, or the law; and<br> f. a statement by you
that the above information in your notice is accurate and that, under
penalty of perjury, you are the copyright or intellectual property
owner or authorized to act on the copyright or intellectual property
owner’s behalf.<br> 7.2 Repeat Infringers. BV will promptly
terminate without notice the accounts of users that are determined by
BV to be “repeat infringers.” A repeat infringer is a user who has
been notified of infringing activity more than twice and/or has had
User Content removed from the Service more than twice.<br>
8. Prohibited Conduct. BY USING THE SERVICE YOU AGREE NOT TO:<br> 8.1
use the Service for any illegal purpose, or in violation of any local,
state, national, or international law;<br> 8.2 violate, or encourage
others to violate, the rights of third parties, including by
infringing or misappropriating third party intellectual property
rights;<br> 8.3 upload, post, email or transmit or otherwise make
available through the Service any inappropriate, defamatory,
infringing, obscene, or unlawful content;<br> 8.4 download any content
posted on the Service by another user that you know, or reasonably
should know, that cannot be legally distributed in this manner;<br>
8.5 remove any copyright, trademark or other proprietary rights
notices contained in or on the Service or any content made available
on or through the Service;<br> 8.6 impersonate another person or
entity, or falsify or delete any author attributions, legal or other
proper notices or proprietary designations or labels of the origin or
source of software or other material;<br> 8.7 submit content that
falsely expresses or implies that such content is sponsored or
endorsed by BV;<br> 8.8 restrict or inhibit any other user from
using and enjoying Service;<br> 8.9 interfere with security-related
features of the Service, including without limitation by (i) disabling
or circumventing features that prevent or limit use or copying of any
content, or (ii) reverse engineering or otherwise attempting to
discover the source code of the Service or any part thereof except to
the extent that such activity is expressly permitted by applicable
law;<br> 8.10 interfere with the operation of the Service or any
user’s enjoyment of the Service, including without limitation by (i)
uploading or otherwise disseminating viruses, adware, spyware, worms,
or other malicious code, (ii) making unsolicited offers or
advertisements to other users of the Service, (iii) attempting to
collect, personal information about users or third parties without
their consent; or (iv) interfering with or disrupting any networks,
equipment, or servers connected to or used to provide the Service, or
violating the regulations, policies, or procedures of those networks,
equipment, or servers;<br> 8.11 perform any fraudulent activity
including impersonating any person or entity, claiming false
affiliations, accessing the Service accounts of others without
permission, or falsifying your age or date of birth;<br> 8.12 sell or
otherwise transfer the access granted herein or any Materials (as
defined in Section 14 below) or any right or ability to view, access,
or use any Materials; or<br> 8.13 attempt to do any of the foregoing
in this Section 8, or assist or permit any persons in engaging in any
of the activities described in this Section 8.<br> 9. Third-Party
Services and Linked Sites. The Service may include links to other
websites or services (“Linked Sites”) solely as a convenience to you
and other users. The Service may also provide certain tools that
enable you to export information, including User Content, to certain
Linked Sites. By using those tools, you agree that we may transfer
that information to the applicable Linked Sites. These Linked Sites
are not under our control, and we are not responsible for their use of
your exported information. Furthermore, we make no express or implied
warranties with regard to the information, material, products, or
services that are contained on or accessible through Linked
Sites. ACCESS AND USE OF LINKED SITES, INCLUDING THE INFORMATION,
MATERIAL, PRODUCTS, AND SERVICES ON LINKED SITES OR AVAILABLE THROUGH
LINKED SITES, IS SOLELY AT YOUR OWN RISK.<br> 10. Termination and
Suspension; Effects of Termination.<br> 10.1 By BV. If you violate
any provision of these Terms, your permission to use the Service will
terminate automatically. Additionally, BV, in its sole discretion
may terminate your user account on the Service or suspend or terminate
your access to the Service at any time, with or without notice. We
also reserve the right to modify or discontinue the Service at any
time (including, without limitation, by limiting or discontinuing
certain features of the Service) without notice to you. We will have
no liability whatsoever on account of any change to the Service or any
suspension or termination of your access to or use of the Service.<br>
10.2 By You. You may terminate your account at any time through your
account settings or by contacting BV at [email protected]. If you
terminate your account, you will remain obligated to pay all
outstanding fees, if any, relating to your use of the Service incurred
prior to termination.<br> 10.3 Effects of Termination. Upon any
termination or expiration of these Terms, whether by you or BV, ANY
INFORMATION (INCLUDING USER CONTENT) THAT YOU HAVE SUBMITTED ON OR
THROUGH THE SERVICE OR THAT WHICH IS RELATED TO YOUR ACCOUNT MAY NO
LONGER BE ACCESSED BY YOU and BV will have no obligation to maintain
that information in its databases or to forward that information to
you or any third party.<br> 10.4 Survival. Upon any termination of
these Terms, any provision that by its nature or express terms should
survive will survive the termination or expiration of these Terms,
including, but not limited to, Sections 6, 7, and 9 through 20.<br>
11. Feedback. If you provide any comments, suggestions or other
feedback to BV regarding the Service (“Feedback”), you acknowledge
that the Feedback is not confidential and you authorize BV to use
that Feedback without restriction and without payment to
you. Accordingly, you hereby grant to BV a nonexclusive,
royalty-free, fully-paid, perpetual, irrevocable, transferable, and
fully sublicensable right to use the Feedback in any manner and for
any purpose.<br> 12. Privacy Policy; Additional Terms<br> 12.1
Privacy Policy. Please read the BV Privacy Policy carefully for
information relating to our collection, use, storage and disclosure of
your personal information. The BV Privacy Policy is hereby
incorporated by reference into, and made a part of, these Terms.<br>
12.2 Additional Terms. Your use of the Service is subject to any and
all additional terms, policies, rules, or guidelines applicable to the
Service or certain features of the Service that we may post on or link
to on the Service (the “Additional Terms”), such as end-user license
agreements for any downloadable applications that we may offer, or
rules applicable to particular features or content on the Service,
subject to Section 13 below. All Additional Terms are hereby
incorporated by reference into, and made a part of, these Terms.<br>
13. Modification of these Terms. We reserve the right, at our
discretion, to change these Terms on a going-forward basis at any
time. Please check these Terms periodically for changes. In the event
that a change to these Terms materially modifies your rights or
obligations, we will make reasonable efforts to notify you of that
change. We may provide that notice by posting on the Service, by
sending an email to any address you may have used to register for an
account, or through other mechanisms. Our changed Terms will
automatically take effect 60 days after it is made available through
the Site. If you do not accept the changed Terms, you may terminate
your access to and use of the Service. Your continued use of the
Service after the changed Terms have become effective indicates that
you have read, understood and agreed to the current version of the
Terms. Notwithstanding the foregoing, any disputes arising under these
Terms will be resolved in accordance with the Terms in effect that the
time the dispute arose.<br> 14. Ownership; Proprietary Rights. The
Service is owned and operated by BV. The visual interfaces,
graphics, design, compilation, information, data, computer code
(including source code or object code), products, software, services,
and all other elements of, or provided or made available on or
through, the Service (the “Materials”) are protected by all relevant
intellectual property and proprietary rights and applicable laws. All
Materials are the property of BV or our third-party
licensors. Except as expressly authorized by BV, you may not make
use of the Materials. BV reserves all rights to the Materials not
granted expressly in these Terms.<br> 15. Indemnity. You agree that
you will be responsible for your use of the Service, and you agree to
defend, indemnify, and hold harmless BV and its officers, directors,
employees, consultants, affiliates, subsidiaries and agents
(collectively, the “BV Entities”) from and against any and all
claims, liabilities, damages, losses, and expenses, including
reasonable attorneys’ fees and costs, arising out of or in any way
connected with (i) your access to, use of, or alleged use of the
Service; (ii) your violation of these Terms or any representation,
warranty, or agreements referenced herein, or any applicable law or
regulation; (iii) your violation of any third-party right, including
without limitation any intellectual property right, publicity,
confidentiality, property or privacy right; or (iv) any disputes or
issues between you and any third party. We reserve the right, at our
own expense, to assume the exclusive defense and control of any matter
otherwise subject to indemnification by you (and without limiting your
indemnification obligations with respect to that matter), and in that
case, you agree to cooperate with our defense of that claim.<br>
16. Disclaimers; No Warranties<br> THE SERVICE AND ALL MATERIALS AND
CONTENT AVAILABLE ON OR THROUGH THE SERVICE ARE PROVIDED “AS IS” AND
ON AN “AS AVAILABLE” BASIS, WITHOUT WARRANTY OR CONDITION OF ANY KIND,
EITHER EXPRESS OR IMPLIED. THE BV ENTITIES SPECIFICALLY (BUT WITHOUT
LIMITATION) DISCLAIM ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS OR
IMPLIED, RELATING TO THE SERVICE AND ALL MATERIALS AND CONTENT
AVAILABLE THROUGH THE SERVICE, INCLUDING BUT NOT LIMITED TO (i) ANY
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, TITLE, QUIET ENJOYMENT, OR NON-INFRINGEMENT; AND (ii) ANY
WARRANTIES ARISING OUT OF COURSE OF DEALING, USAGE, OR TRADE. THE BV
ENTITIES DO NOT WARRANT THAT THE SERVICE OR ANY PART THEREOF, OR ANY
MATERIALS OR CONTENT OFFERED ON OR THROUGH THE SERVICE, WILL BE
UNINTERRUPTED, SECURE, OR FREE OF ERRORS, VIRUSES, OR OTHER HARMFUL
COMPONENTS, AND DO NOT WARRANT THAT ANY OF THE FOREGOING WILL BE
qCORRECTED.</p>
<p>NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU
FROM THE SERVICE OR ANY MATERIALS OR CONTENT AVAILABLE ON OR THROUGH
THE SERVICE WILL CREATE ANY WARRANTY REGARDING ANY OF THE BV ENTITIES
OR THE SERVICE THAT IS NOT EXPRESSLY STATED IN THESE TERMS. YOU ASSUME
ALL RISK FOR ALL DAMAGES THAT MAY RESULT FROM YOUR USE OF OR ACCESS TO
THE SERVICE, YOUR DEALINGS WITH OTHER SERVICE USERS, AND ANY MATERIALS
OR CONTENT AVAILABLE THROUGH THE SERVICE. YOU UNDERSTAND AND AGREE
THAT YOU USE THE SERVICE AND USE, ACCESS, DOWNLOAD, OR OTHERWISE
OBTAIN MATERIALS OR CONTENT THROUGH THE SERVICE AND ANY ASSOCIATED
SITES OR SERVICES AT YOUR OWN DISCRETION AND RISK, AND YOU WILL BE
SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR PROPERTY (INCLUDING YOUR
COMPUTER SYSTEM USED IN CONNECTION WITH THE SERVICE) OR LOSS OF DATA
THAT RESULTS FROM THE USE OF THE SERVICE OR THE DOWNLOAD OR USE OF
SUCH MATERIALS OR CONTENT.<br> SOME JURISDICTIONS MAY PROHIBIT A
DISCLAIMER OF WARRANTIES AND YOU MAY HAVE OTHER RIGHTS THAT VARY FROM
JURISDICTION TO JURISDICTION.<br> 17. Limitation of Liability<br> IN
NO EVENT WILL THE BV ENTITIES BE LIABLE TO YOU FOR ANY INDIRECT,
INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES (INCLUDING,
WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA,
OR OTHER INTANGIBLE LOSSES) ARISING OUT OF OR RELATING TO YOUR ACCESS
TO OR USE OF, OR YOUR INABILITY TO ACCESS OR USE, THE SERVICE OR ANY
MATERIALS OR CONTENT ON THE SERVICE, WHETHER BASED ON WARRANTY,
CONTRACT, TORT (INCLUDING NEGLIGENCE), STATUTE OR ANY OTHER LEGAL
THEORY, WHETHER OR NOT THE BV ENTITIES HAVE BEEN INFORMED OF THE
POSSIBILITY OF SUCH DAMAGE.<br> YOU AGREE THAT THE AGGREGATE
LIABILITY OF THE BV ENTITIES TO YOU FOR ANY AND ALL CLAIMS ARISING OUT
OF RELATING TO THE USE OF OR ANY INABILITY TO USE THE SERVICE
(INCLUDING ANY MATERIALS OR CONTENT AVAILABLE THROUGH THE SERVICE) OR
OTHERWISE UNDER THESE TERMS, WHETHER IN CONTRACT, TORT, OR OTHERWISE,
IS LIMITED TO THE GREATER OF (i) THE AMOUNTS YOU HAVE PAID TO BV FOR
ACCESS TO AND USE OF THE SERVICE IN THE 12 MONTHS PRIOR TO THE CLAIM
OR (ii) $100.<br> SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR
LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL
DAMAGES. ACCORDINGLY, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.<br>
EACH PROVISION OF THESE TERMS THAT PROVIDES FOR A LIMITATION OF
LIABILITY, DISCLAIMER OF WARRANTIES, OR EXCLUSION OF DAMAGES IS TO
ALLOCATE THE RISKS UNDER THESE TERMS BETWEEN THE PARTIES. THIS
ALLOCATION IS AN ESSENTIAL ELEMENT OF THE BASIS OF THE BARGAIN BETWEEN
THE PARTIES. EACH OF THESE PROVISIONS IS SEVERABLE AND INDEPENDENT OF
ALL OTHER PROVISIONS OF THESE TERMS. THE LIMITATIONS IN THIS SECTION
15 WILL APPLY EVEN IF ANY LIMITED REMEDY FAILS OF ITS ESSENTIAL
PURPOSE.<br> 18. Governing Law. These Terms shall be governed by the
laws of the State of Tennessee without regard to conflict of law
principles. To the extent that any lawsuit or court proceeding is
permitted hereunder, you and BV agree to submit to the personal and
exclusive jurisdiction of the state courts and federal courts located
within Knox County, Tennessee for the purpose of litigating all
disputes.<br> 19. Dispute Resolution and Arbitration<br> 19.1
Generally. In the interest of resolving disputes between you and BV in
the most expedient and cost effective manner, you and BV agree that
any and all disputes arising in connection with these Terms shall be
resolved by binding arbitration. Arbitration is more informal than a
lawsuit in court. Arbitration uses a neutral arbitrator instead of a
judge or jury, may allow for more limited discovery than in court, and
can be subject to very limited review by courts. Arbitrators can award
the same damages and relief that a court can award. Our agreement to
arbitrate disputes includes, but is not limited to all claims arising
out of or relating to any aspect of these Terms, whether based in
contract, tort, statute, fraud, misrepresentation or any other legal
theory, and regardless of whether the claims arise during or after the
termination of these Terms. YOU UNDERSTAND AND AGREE THAT, BY ENTERING
INTO THESE TERMS, YOU AND BV ARE EACH WAIVING THE RIGHT TO A TRIAL BY
JURY OR TO PARTICIPATE IN A CLASS ACTION.<br> 19.2
Exceptions. Notwithstanding subsection 18.1, we both agree that
nothing herein will be deemed to waive, preclude, or otherwise limit
either of our right to (i) bring an individual action in small claims
court, (ii) pursue enforcement actions through applicable federal,
state, or local agencies where such actions are available, (iii) seek
injunctive relief in a court of law, or (iv) to file suit in a court
of law to address intellectual property infringement claims.<br> 19.3
Arbitrator. Any arbitration between you and BV will be governed by the
Commercial Dispute Resolution Procedures and the Supplementary
Procedures for Consumer Related Disputes (collectively, “AAA Rules”)
of the American Arbitration Association (“AAA”), as modified by these
Terms, and will be administered by the AAA. The AAA Rules and filing
forms are available online at www.adr.org, by calling the AAA at
1-800-778-7879, or by contacting BV.<br> 19.4 Notice; Process. A
party who intends to seek arbitration must first send a written notice
of the dispute to the other, by certified mail or Federal Express
(signature required), or in the event that we do not have a physical
address on file for you, by electronic mail (“Notice”). BV’s address
for Notice is: Bruiser Ventures, LLC., PO Box 1036 1237 E WEISGARBER
RD RM 9831 KNOXVILLE, TN 37950-9831. The Notice must (i) describe the
nature and basis of the claim or dispute; and (ii) set forth the
specific relief sought (“Demand”). We agree to use good faith efforts
to resolve the claim directly, but if we do not reach an agreement to
do so within 30 days after the Notice is received, you or BV may
commence an arbitration proceeding. During the arbitration, the amount
of any settlement offer made by you or BV shall not be disclosed to
the arbitrator until after the arbitrator makes a final decision and
award, if any. In the event our dispute is finally resolved through
arbitration in your favor, BV shall pay you (i) the amount awarded by
the arbitrator, if any, (ii) the last written settlement amount
offered by BV in settlement of the dispute prior to the arbitrator’s
award; or (iii) $1,000.00, whichever is greater.<br> 19.5 Fees. In
the event that you commence arbitration in accordance with these
Terms, BV will reimburse you for your payment of the filing fee,
unless your claim is for greater than $10,000, in which case the
payment of any fees shall be decided by the AAA Rules. Any arbitration
hearings will take place at a location to be agreed upon in Knox
County, Tennessee, provided that if the claim is for $10,000 or less,
you may choose whether the arbitration will be conducted (i) solely on
the basis of documents submitted to the arbitrator; (ii) through a
non-appearance based telephonic hearing; or (iii) by an in-person
hearing as established by the AAA Rules in the county (or parish) of
your billing address. If the arbitrator finds that either the
substance of your claim or the relief sought in the Demand is
frivolous or brought for an improper purpose (as measured by the
standards set forth in Federal Rule of Civil Procedure 11(b)), then
the payment of all fees will be governed by the AAA Rules. In that
case, you agree to reimburse BV for all monies previously disbursed by
it that are otherwise your obligation to pay under the AAA
Rules. Regardless of the manner in which the arbitration is conducted,
the arbitrator shall issue a reasoned written decision sufficient to
explain the essential findings and conclusions on which the decision
and award, if any, are based. The arbitrator may make rulings and
resolve disputes as to the payment and reimbursement of fees or
expenses at any time during the proceeding and upon request from
either party made within 14 days of the arbitrator’s ruling on the
merits.<br> 19.6 No Class Actions. YOU AND BV AGREE THAT EACH MAY
BRING CLAIMS AGAINST THE OTHER ONLY IN YOUR OR ITS INDIVIDUAL CAPACITY
AND NOT AS A PLAINTIFF OR CLASS MEMBER IN ANY PURPORTED CLASS OR
REPRESENTATIVE PROCEEDING. Further, unless both you and BV agree
otherwise, the arbitrator may not consolidate more than one person’s
claims, and may not otherwise preside over any form of a
representative or class proceeding.<br> 19.7 Modifications. In the
event that BV makes any future change to this arbitration provision
(other than a change to BV’s address for Notice), you may reject that
change by sending us written notice within 30 days of the change to
BV’s address for Notice, in which case your account with BV shall be
immediately terminated and this arbitration provision, as in effect
immediately prior to the amendments you reject shall survive.<br>
19.8 Enforceability. If Subsection 18.6 is found to be unenforceable
or if the entirety of this Section 19 is found to be unenforceable,
then the entirety of this Section 19 shall be null and void and, in
that case, the parties agree that the exclusive jurisdiction and venue
described in Section 18 shall govern any action arising out of or
related to these Terms.<br> 20. Consent to Electronic
Communications. By using the Service, you consent to receiving certain
electronic communications from us as further described in our Privacy
Policy. Please read our Privacy Policy to learn more about your
choices regarding our electronic communications practices. You agree
that any notices, agreements, disclosures, or other communications
that we send to you electronically will satisfy any legal
communication requirements, including that these communications be in
writing.<br> 21. Miscellaneous. These Terms, together with the
Privacy Policy and any other agreements expressly incorporated by
reference herein, constitute the entire and exclusive understanding
and agreement between you and BV regarding your use of and access to
the Service, and except as expressly permitted above may be amended
only by a written agreement signed by authorized representatives of
all parties to these Terms. You may not assign or transfer these Terms
or your rights hereunder, in whole or in part, by operation of law or
otherwise, without our prior written consent. We may assign these
Terms at any time without notice. The failure to require performance
of any provision will not affect our right to require performance at
any time thereafter, nor shall a waiver of any breach or default of
these Terms or any provision of these Terms constitute a waiver of any
subsequent breach or default or a waiver of the provision itself. Use
of section headers in these Terms is for convenience only and shall
not have any impact on the interpretation of particular provisions. In
the event that any part of these Terms is held to be invalid or
unenforceable, the unenforceable part shall be given effect to the
greatest extent possible and the remaining parts will remain in full
force and effect.<br> 22. Contact Information. The Service is offered
by Bruiser Ventures, LLC., located at PO Box 1036 1237 E WEISGARBER RD
RM 9831 KNOXVILLE, TN 37950-9831. You may contact BV by sending
correspondence to the foregoing address or by emailing us at
[email protected]. If you are a California resident, you
may have these Terms mailed to you electronically by sending a letter
to the foregoing address with your electronic mail address and a
request for these Terms.</p>
</div>
<div class="clearfix"></div>
</div>
</div>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>© 2015 Bruiser Ventures. All Rights
Reserved. Bruiser Ventures and BV are trademarks or
registered trademarks of Bruiser Ventures, LLC. All
other trademarks are the property of their respective
owners. <a href="http://www.bruiser-ventures.com/legal/privacy_policy.html">Privacy
Policy</a> | <a href="http://www.bruiser-ventures.com/legal/terms_of_use.html">Terms
of Use</p>
</div>
</div>
</div>
</footer>
</body>
</html>
|
apache-2.0
|
hisataka/altxt2db
|
src/main/java/jp/co/altxt2db/dto/EnvironmentDto.java
|
236
|
package jp.co.altxt2db.dto;
/**
* 環境情報保持DTO
*
*/
public class EnvironmentDto {
/** 実行用アクションクラスパス */
public String actionClass;
/** 実行時引数 */
public String[] args;
}
|
apache-2.0
|
ViteFalcon/RokLegend
|
source/network/packets/RoDeleteCharacterAcceptRequest.h
|
343
|
#pragma once
#include "RoPacket.h"
roDEFINE_PACKET(RoDeleteCharacterAcceptRequest)
{
public:
RoDeleteCharacterAcceptRequest();
~RoDeleteCharacterAcceptRequest() = default;
void setCharacterId(const uint32 characterId);
void setBirthDate(const RoDate& birthDate);
private:
uint32 mCharacterId;
RoString mBirthDate;
};
|
apache-2.0
|
oehme/analysing-gradle-performance
|
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p438/Test8764.java
|
2111
|
package org.gradle.test.performance.mediummonolithicjavaproject.p438;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8764 {
Production8764 objectUnderTest = new Production8764();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
apache-2.0
|
willmclaren/ensembl
|
sql/patch_39_40_h.sql
|
1081
|
-- Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
# patch_39_40_h
#
# title: oligo_feature analysis id column type change
#
# description:
# Change oligo_feature.analysis_id to be int(10) unsigned. Should have been part of patch_39_40_a.sql
ALTER TABLE oligo_feature CHANGE COLUMN analysis_id analysis_id INT(10) UNSIGNED NOT NULL;
# patch identifier
INSERT INTO meta (meta_key, meta_value) VALUES ('patch', 'patch_39_40_h.sql|oligo_feature_analysis_id_type');
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Ceratonema/Ceratonema tenacissimum/README.md
|
215
|
# Ceratonema tenacissimum (Roth) Roth SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Catalecta botanica 2: 253 (1800)
#### Original name
Byssus tenacissima Roth
### Remarks
null
|
apache-2.0
|
grzegorz2047/UAMRepo
|
POB/po-c1/po-c1.cpp
|
2750
|
#include <iostream>
#include <ctime>
class Stos
{
private:
int dane[100];
int n;
int id;
public:
Stos(int id){
this->id = id;
n=0;
std::cout << "["<< id <<"] Pojawiam sie!" << std::endl;
}
~Stos(){
std::cout << "["<< id <<"] Znikam!" << std::endl;
}
void push(int e) { dane[n++] = e; }
int pop() { return dane[--n]; }
int empty() { return n==0; }
int size(){return n;}
int getId() { return id;}
};
class Data{
private:
int day;
int month;
int year;
public:
Data(){
time_t t = time(0);
struct tm * now = localtime( & t );
this->year = now->tm_year + 1900;
this->month = now->tm_mon + 1;
this->day = now->tm_mday;
}
Data(int day, int month, int year){
this->day = day;
this->month = month;
this->year = year;
}
void set(int d, int m, int r){
this->day = d;
this->month = m;
this->year = r;
}
void print(){
std::cout << day <<"-" << month << "-" << year;
}
};
void ex7(){
std::cout <<"Startuje program" <<std::endl;
for (int i = 0; i < 12; i++){
Stos* stos = new Stos(i);
std::cout << "Stworzylem stos!" << std::endl;
stos->push(2); stos->push(5); stos->push(3);
while(!stos->empty()){
std::cout << stos->pop() << std::endl;
}
delete stos;
std::cout << "Usunalem obiekt!" << std::endl;
}
}
void ex10(){
for (int i = 1; i <= 3; i++){
Stos* stos = new Stos(i);
delete stos;
}
std::cout <<std::endl;
Stos* stacks[3];
for (int i = 1; i <= 3; i++){
stacks[i-1] = new Stos(i);
}
for (int i = 3; i >= 1; i--){
delete stacks[(i-1)] ;
}
std::cout <<std::endl;
for (int i = 1; i <= 3; i++){
stacks[i-1] = new Stos(i);
}
for (int i = 1; i <= 3; i++){
delete stacks[(i-1)] ;
}
}
void dataEx2(){
int day,month, year;
std::cout <<"Podaj swoja date urodzenia! " << std::endl;
std::cout <<"Podaj dzien! " << std::endl;
std::cin >> day;
std::cout <<"Podaj miesiac! " << std::endl;
std::cin >> month;
std::cout <<"Podaj rok! " << std::endl;
std::cin >> year;
Data* date = new Date(day, month, year);
delete date;
}
main()
{
Data date;
}
|
apache-2.0
|
jerrytang67/jw_ionic_myapp
|
wx_youxuan/src/components/buy-item/buy-item.html
|
1151
|
<ion-card>
<ion-row *ngIf="item.Shop">
<h2 style="font-weight:normal;font-size:1.8rem;height:2.5rem;line-height: 2.5rem;padding-left:10px;border-left:solid 8px #EA1A59;">{{item.Shop.ShopName}}</h2>
</ion-row>
<ion-row>
<ion-col col-4>
<img class="logoImg" [src]="item.LogoList[0]+'!w100h100'" (click)="goDetail(item)" />
</ion-col>
<ion-col col-8>
<div class="tag">{{initData.BuyItemType[item.Type].name}}</div>
<div class="distance" *ngIf="item.dis!=undefined" style="position: absolute;right:10px;top:0;height:2rem;line-height: 2rem;font-size:1.6rem;">
距离
<b *ngIf="item.dis<2">{{(item.dis*1000).toFixed(0)}}米</b>
<b *ngIf="item.dis>=2">{{item.dis.toFixed(2)}}公里</b>
</div>
<div class="title">{{item.Name}}</div>
<div class="row3">
<div class="price" *ngIf="showPrice">
<b>¥{{item.VipPrice}}</b>
<i>原价:{{item.Price}}</i>
</div>
<div>
<button ion-button [color]="btnText.color" (click)="goDetail(item)">{{btnText.text}}</button>
</div>
</div>
</ion-col>
</ion-row>
</ion-card>
|
apache-2.0
|
google/agi
|
gapis/resolve/delete_test.go
|
5365
|
// Copyright (C) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resolve
import (
"context"
"testing"
"github.com/google/gapid/core/assert"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/device"
"github.com/google/gapid/core/os/device/bind"
"github.com/google/gapid/gapis/api"
"github.com/google/gapid/gapis/api/test"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/database"
"github.com/google/gapid/gapis/service"
"github.com/google/gapid/gapis/service/path"
)
func createSingleCommandTrace(ctx context.Context) *path.Capture {
h := &capture.Header{ABI: device.WindowsX86_64}
cb := test.CommandBuilder{}
cmds := []api.Cmd{
cb.CmdTypeMix(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, true, test.Voidᵖ(0x12345678), 2),
}
p, err := capture.NewGraphicsCapture(ctx, "test", h, nil, cmds)
if err != nil {
log.F(ctx, true, "Couldn't create capture: %v", err)
}
path, err := p.Path(ctx)
if err != nil {
log.F(ctx, true, "Couldn't get capture path: %v", err)
}
return path
}
func createMultipleCommandTrace(ctx context.Context) *path.Capture {
h := &capture.Header{ABI: device.WindowsX86_64}
cb := test.CommandBuilder{}
cmds := []api.Cmd{
cb.CmdTypeMix(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, true, test.Voidᵖ(0x12345678), 2),
cb.CmdTypeMix(1, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105, false, test.Voidᵖ(0x87654321), 3),
cb.CmdTypeMix(2, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, true, test.Voidᵖ(0xdeadfeed), 3),
}
p, err := capture.NewGraphicsCapture(ctx, "test", h, nil, cmds)
if err != nil {
log.F(ctx, true, "Couldn't create capture: %v", err)
}
path, err := p.Path(ctx)
if err != nil {
log.F(ctx, true, "Couldn't get capture path: %v", err)
}
return path
}
func TestDeleteSingleCommandTrace(t *testing.T) {
ctx := log.Testing(t)
ctx = bind.PutRegistry(ctx, bind.NewRegistry())
ctx = database.Put(ctx, database.NewInMemory(ctx))
p := createSingleCommandTrace(ctx)
ctx = capture.Put(ctx, p)
newTracePath, err := Delete(ctx, p.Command(0).Path(), nil)
assert.For(ctx, "Delete").ThatError(err).DeepEquals(nil)
newCapture := newTracePath.GetCapture()
newBoxedCommands, err := Get(ctx, newCapture.Commands().Path(), nil)
newCommands := newBoxedCommands.(*service.Commands).List
assert.For(ctx, "Deleted Commands").That(len(newCommands)).DeepEquals(0)
}
func TestDeleteMultipleCommandFirstElement(t *testing.T) {
ctx := log.Testing(t)
ctx = bind.PutRegistry(ctx, bind.NewRegistry())
ctx = database.Put(ctx, database.NewInMemory(ctx))
p := createMultipleCommandTrace(ctx)
ctx = capture.Put(ctx, p)
commandPathsBoxed, _ := Get(ctx, p.Commands().Path(), nil)
commandPaths := commandPathsBoxed.(*service.Commands).List
var commands []*api.Command
for i := 0; i < len(commandPaths); i++ {
command, _ := Get(ctx, commandPaths[i].Path(), nil)
commands = append(commands, command.(*api.Command))
}
newTracePath, err := Delete(ctx, commandPaths[0].Path(), nil)
assert.For(ctx, "Delete").ThatError(err).DeepEquals(nil)
newCapture := newTracePath.GetCapture()
newBoxedCommands, err := Get(ctx, newCapture.Commands().Path(), nil)
newCommands := newBoxedCommands.(*service.Commands).List
assert.For(ctx, "Deleted Commands").That(len(newCommands)).DeepEquals(len(commandPaths) - 1)
for i, test := range newCommands {
boxedCommand, err := Get(ctx, test.Path(), nil)
command := boxedCommand.(*api.Command)
assert.For(ctx, "Get(%v) value", test).That(command).DeepEquals(commands[i+1])
assert.For(ctx, "Get(%v) error", test).That(err).DeepEquals(nil)
}
}
func TestDeleteMultipleCommandLastElement(t *testing.T) {
ctx := log.Testing(t)
ctx = bind.PutRegistry(ctx, bind.NewRegistry())
ctx = database.Put(ctx, database.NewInMemory(ctx))
p := createMultipleCommandTrace(ctx)
ctx = capture.Put(ctx, p)
commandPathsBoxed, _ := Get(ctx, p.Commands().Path(), nil)
commandPaths := commandPathsBoxed.(*service.Commands).List
var commands []*api.Command
for i := 0; i < len(commandPaths); i++ {
command, _ := Get(ctx, commandPaths[i].Path(), nil)
commands = append(commands, command.(*api.Command))
}
newTracePath, err := Delete(ctx, commandPaths[len(commandPaths)-1].Path(), nil)
assert.For(ctx, "Delete").ThatError(err).DeepEquals(nil)
newCapture := newTracePath.GetCapture()
newBoxedCommands, err := Get(ctx, newCapture.Commands().Path(), nil)
newCommands := newBoxedCommands.(*service.Commands).List
assert.For(ctx, "Deleted Commands").That(len(newCommands)).DeepEquals(len(commandPaths) - 1)
for i, test := range newCommands {
boxedCommand, err := Get(ctx, test.Path(), nil)
command := boxedCommand.(*api.Command)
assert.For(ctx, "Get(%v) value", test).That(command).DeepEquals(commands[i])
assert.For(ctx, "Get(%v) error", test).That(err).DeepEquals(nil)
}
}
|
apache-2.0
|
archiecobbs/jsimpledb
|
site/apidocs/io/permazen/schema/class-use/SetSchemaField.html
|
9132
|
<!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 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.permazen.schema.SetSchemaField (Permazen 4.1.6 API)</title>
<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 io.permazen.schema.SetSchemaField (Permazen 4.1.6 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="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">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?io/permazen/schema/class-use/SetSchemaField.html" target="_top">Frames</a></li>
<li><a href="SetSchemaField.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 io.permazen.schema.SetSchemaField" class="title">Uses of Class<br>io.permazen.schema.SetSchemaField</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="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</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="#io.permazen.schema">io.permazen.schema</a></td>
<td class="colLast">
<div class="block">Classes for modeling Permazen <a href="../../../../io/permazen/core/Database.html" title="class in io.permazen.core"><code>Database</code></a> schemas.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="io.permazen.schema">
<!-- -->
</a>
<h3>Uses of <a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a> in <a href="../../../../io/permazen/schema/package-summary.html">io.permazen.schema</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../io/permazen/schema/package-summary.html">io.permazen.schema</a> that return <a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a></code></td>
<td class="colLast"><span class="typeNameLabel">SetSchemaField.</span><code><span class="memberNameLink"><a href="../../../../io/permazen/schema/SetSchemaField.html#clone--">clone</a></span>()</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../io/permazen/schema/package-summary.html">io.permazen.schema</a> with parameters of type <a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../io/permazen/schema/SchemaFieldSwitch.html" title="type parameter in SchemaFieldSwitch">R</a></code></td>
<td class="colLast"><span class="typeNameLabel">SchemaFieldSwitch.</span><code><span class="memberNameLink"><a href="../../../../io/permazen/schema/SchemaFieldSwitch.html#caseSetSchemaField-io.permazen.schema.SetSchemaField-">caseSetSchemaField</a></span>(<a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a> field)</code>
<div class="block">Handle a <a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema"><code>SetSchemaField</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../io/permazen/schema/SchemaFieldSwitchAdapter.html" title="type parameter in SchemaFieldSwitchAdapter">R</a></code></td>
<td class="colLast"><span class="typeNameLabel">SchemaFieldSwitchAdapter.</span><code><span class="memberNameLink"><a href="../../../../io/permazen/schema/SchemaFieldSwitchAdapter.html#caseSetSchemaField-io.permazen.schema.SetSchemaField-">caseSetSchemaField</a></span>(<a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a> field)</code>
<div class="block">Handle a <a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema"><code>SetSchemaField</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../io/permazen/util/Diffs.html" title="class in io.permazen.util">Diffs</a></code></td>
<td class="colLast"><span class="typeNameLabel">SetSchemaField.</span><code><span class="memberNameLink"><a href="../../../../io/permazen/schema/SetSchemaField.html#differencesFrom-io.permazen.schema.SetSchemaField-">differencesFrom</a></span>(<a href="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">SetSchemaField</a> that)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="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="../../../../io/permazen/schema/SetSchemaField.html" title="class in io.permazen.schema">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?io/permazen/schema/class-use/SetSchemaField.html" target="_top">Frames</a></li>
<li><a href="SetSchemaField.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 © 2020. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
fpompermaier/onvif
|
onvif-ws-client/src/main/java/org/onvif/ver10/schema/IOCapabilitiesExtension2.java
|
2379
|
package org.onvif.ver10.schema;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.w3c.dom.Element;
/**
* <p>Java class for IOCapabilitiesExtension2 complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="IOCapabilitiesExtension2">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='lax' namespace='http://www.onvif.org/ver10/schema' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IOCapabilitiesExtension2", propOrder = {
"any"
})
public class IOCapabilitiesExtension2 {
@XmlAnyElement(lax = true)
protected List<java.lang.Object> any;
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
* {@link java.lang.Object }
*
*
*/
public List<java.lang.Object> getAny() {
if (any == null) {
any = new ArrayList<java.lang.Object>();
}
return this.any;
}
/**
* Generates a String representation of the contents of this type.
* This is an extension method, produced by the 'ts' xjc plugin
*
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
}
}
|
apache-2.0
|
consulo/consulo-scala
|
src/org/jetbrains/plugins/scala/lang/parser/parsing/types/Type.scala
|
2634
|
package org.jetbrains.plugins.scala
package lang
package parser
package parsing
package types
import com.intellij.lang.PsiBuilder, org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.parser.ScalaElementTypes
import org.jetbrains.plugins.scala.ScalaBundle
import builder.ScalaPsiBuilder
/**
* @author Alexander Podkhalyuzin
* Date: 28.02.2008
*/
/*
* Type ::= InfixType '=>' Type
* | '(' ['=>' Type] ')' => Type
* | InfixType [ExistentialClause]
* | _ [>: Type] [<: Type]
*/
object Type {
def parse(builder: ScalaPsiBuilder): Boolean = parse(builder,star = false)
def parse(builder: ScalaPsiBuilder,star: Boolean): Boolean = parse(builder,star,isPattern = false)
def parse(builder: ScalaPsiBuilder,star: Boolean,isPattern: Boolean): Boolean = {
val typeMarker = builder.mark
if (!InfixType.parse(builder,star,isPattern)) {
builder.getTokenType match {
case ScalaTokenTypes.tUNDER =>
builder.advanceLexer()
builder.getTokenText match {
case ">:" =>
builder.advanceLexer()
if (!Type.parse(builder)) {
builder error ScalaBundle.message("wrong.type")
}
case _ => //nothing
}
builder.getTokenText match {
case "<:" =>
builder.advanceLexer()
if (!Type.parse(builder)) {
builder error ScalaBundle.message("wrong.type")
}
case _ => //nothing
}
typeMarker.done(ScalaElementTypes.WILDCARD_TYPE)
builder.getTokenType match {
case ScalaTokenTypes.tFUNTYPE =>
val funMarker = typeMarker.precede()
builder.advanceLexer() //Ate =>
if (!Type.parse(builder,star = false,isPattern = isPattern)) {
builder error ScalaBundle.message("wrong.type")
}
funMarker.done(ScalaElementTypes.TYPE)
case _ =>
}
return true
case _ =>
typeMarker.drop()
return false
}
}
builder.getTokenType match {
case ScalaTokenTypes.tFUNTYPE =>
builder.advanceLexer() //Ate =>
if (!Type.parse(builder,star = false,isPattern = isPattern)) {
builder error ScalaBundle.message("wrong.type")
}
typeMarker.done(ScalaElementTypes.TYPE)
case ScalaTokenTypes.kFOR_SOME =>
ExistentialClause parse builder
typeMarker.done(ScalaElementTypes.EXISTENTIAL_TYPE)
case _ => typeMarker.drop()
}
true
}
}
|
apache-2.0
|
soeminnminn/LatinIME_ICS_ported
|
src/com/android/inputmethod/compat/ArraysCompatUtils.java
|
2027
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.compat;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ArraysCompatUtils {
private static final Method METHOD_Arrays_binarySearch = CompatUtils
.getMethod(Arrays.class, "binarySearch", int[].class, int.class, int.class, int.class);
public static int binarySearch(int[] array, int startIndex, int endIndex, int value) {
if (METHOD_Arrays_binarySearch != null) {
final Object index = CompatUtils.invoke(null, 0, METHOD_Arrays_binarySearch,
array, startIndex, endIndex, value);
return (Integer)index;
} else {
return compatBinarySearch(array, startIndex, endIndex, value);
}
}
/* package */ static int compatBinarySearch(int[] array, int startIndex, int endIndex,
int value) {
if (startIndex > endIndex) throw new IllegalArgumentException();
if (startIndex < 0 || endIndex > array.length) throw new ArrayIndexOutOfBoundsException();
final int work[] = new int[endIndex - startIndex];
System.arraycopy(array, startIndex, work, 0, work.length);
final int index = Arrays.binarySearch(work, value);
if (index >= 0) {
return index + startIndex;
} else {
return ~(~index + startIndex);
}
}
}
|
apache-2.0
|
aws/aws-sdk-cpp
|
aws-cpp-sdk-inspector2/source/model/GetFindingsReportStatusResult.cpp
|
1854
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/inspector2/model/GetFindingsReportStatusResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Inspector2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetFindingsReportStatusResult::GetFindingsReportStatusResult() :
m_errorCode(ReportingErrorCode::NOT_SET),
m_status(ExternalReportStatus::NOT_SET)
{
}
GetFindingsReportStatusResult::GetFindingsReportStatusResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_errorCode(ReportingErrorCode::NOT_SET),
m_status(ExternalReportStatus::NOT_SET)
{
*this = result;
}
GetFindingsReportStatusResult& GetFindingsReportStatusResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("destination"))
{
m_destination = jsonValue.GetObject("destination");
}
if(jsonValue.ValueExists("errorCode"))
{
m_errorCode = ReportingErrorCodeMapper::GetReportingErrorCodeForName(jsonValue.GetString("errorCode"));
}
if(jsonValue.ValueExists("errorMessage"))
{
m_errorMessage = jsonValue.GetString("errorMessage");
}
if(jsonValue.ValueExists("filterCriteria"))
{
m_filterCriteria = jsonValue.GetObject("filterCriteria");
}
if(jsonValue.ValueExists("reportId"))
{
m_reportId = jsonValue.GetString("reportId");
}
if(jsonValue.ValueExists("status"))
{
m_status = ExternalReportStatusMapper::GetExternalReportStatusForName(jsonValue.GetString("status"));
}
return *this;
}
|
apache-2.0
|
ingarabr/java-object-validator
|
readme.md
|
1387
|
Validation
==========
This is a library used to validate java object against a set of
validation rules.
This is inspired by mockito and hamcrest so it should be familiar
to use if you know those tools.
Limitations
-----------
It requires that the objects follow the java bean convention with
a field and a getter is present.
How to use
----------
build the project and import it with maven.
```xml
<dependency>
<groupId>com.github.ingarabr.validator</groupId>
<artifactId>validation</artifactId>
<version>{validation.version}</version>
</dependency>
```
Building up a rule
------------------
First we need to specify the field we need:
```java
field(SomeBean.class).getValue();
```
Now we can add a validation condition to it:
```java
validation(field(SomeBean.class).getValue(), mustHaveValue());
```
This can be chain into other validation conditions like `and`, `or` etc.
To verify that an object is valid against the validation condition the API
expose two method. `isValidateObject` that gives a boolean result
and `validateObject` that gives a set of violations. The set it empty if
no validation condition is violated.
```java
Validation validation = validation(field(SomeBean.class).getValue(), hasOneOfTheValues("foo1", "foo2"));
boolean isValid = fieldCondition.isValidateObject(new SomeBean().value("foo1"));
```
See the test for more example of usage.
|
apache-2.0
|
asomya/test
|
horizon/test.py
|
14512
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, 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.
import datetime
import cloudfiles as swift_client
from django import http
from django import test as django_test
from django.conf import settings
from django.contrib.messages.storage import default_storage
from django.core.handlers import wsgi
from django.test.client import RequestFactory
from functools import wraps
from glanceclient.v1 import client as glance_client
from keystoneclient.v2_0 import client as keystone_client
from novaclient.v1_1 import client as nova_client
import quantumclient as quantum_client
import httplib2
import mox
from horizon import api
from horizon import context_processors
from horizon import middleware
from horizon import users
from horizon.tests.test_data.utils import load_test_data
from .time import time
from .time import today
from .time import utcnow
# Makes output of failing mox tests much easier to read.
wsgi.WSGIRequest.__repr__ = lambda self: "<class 'django.http.HttpRequest'>"
def create_stubs(stubs_to_create={}):
if not isinstance(stubs_to_create, dict):
raise TypeError, ("create_stub must be passed a dict, but a %s was " \
"given." % type(stubs_to_create).__name__)
def inner_stub_out(fn):
@wraps(fn)
def instance_stub_out(self):
for key in stubs_to_create:
if not (isinstance(stubs_to_create[key], tuple) or \
isinstance(stubs_to_create[key], list)):
raise TypeError, ("The values of the create_stub " \
"dict must be lists or tuples, but is a %s." %
type(stubs_to_create[key]).__name__)
for value in stubs_to_create[key]:
self.mox.StubOutWithMock(key, value)
return fn(self)
return instance_stub_out
return inner_stub_out
class RequestFactoryWithMessages(RequestFactory):
def get(self, *args, **kwargs):
req = super(RequestFactoryWithMessages, self).get(*args, **kwargs)
req.session = []
req._messages = default_storage(req)
return req
def post(self, *args, **kwargs):
req = super(RequestFactoryWithMessages, self).post(*args, **kwargs)
req.session = []
req._messages = default_storage(req)
return req
class TestCase(django_test.TestCase):
"""
Specialized base test case class for Horizon which gives access to
numerous additional features:
* A full suite of test data through various attached objects and
managers (e.g. ``self.servers``, ``self.user``, etc.). See the
docs for :class:`~horizon.tests.test_data.utils.TestData` for more
information.
* The ``mox`` mocking framework via ``self.mox``.
* A set of request context data via ``self.context``.
* A ``RequestFactory`` class which supports Django's ``contrib.messages``
framework via ``self.factory``.
* A ready-to-go request object via ``self.request``.
* The ability to override specific time data controls for easier testing.
* Several handy additional assertion methods.
"""
def setUp(self):
load_test_data(self)
self.mox = mox.Mox()
self.factory = RequestFactoryWithMessages()
self.context = {'authorized_tenants': self.tenants.list()}
def fake_conn_request(*args, **kwargs):
raise Exception("An external URI request tried to escape through "
"an httplib2 client. Args: %s, kwargs: %s"
% (args, kwargs))
self._real_conn_request = httplib2.Http._conn_request
httplib2.Http._conn_request = fake_conn_request
self._real_horizon_context_processor = context_processors.horizon
context_processors.horizon = lambda request: self.context
self._real_get_user_from_request = users.get_user_from_request
tenants = self.context['authorized_tenants']
self.setActiveUser(id=self.user.id,
token=self.token.id,
username=self.user.name,
tenant_id=self.tenant.id,
service_catalog=self.service_catalog,
authorized_tenants=tenants)
self.request = http.HttpRequest()
self.request.session = self.client._session()
self.request.session['token'] = self.token.id
middleware.HorizonMiddleware().process_request(self.request)
def tearDown(self):
self.mox.UnsetStubs()
httplib2.Http._conn_request = self._real_conn_request
context_processors.horizon = self._real_horizon_context_processor
users.get_user_from_request = self._real_get_user_from_request
self.mox.VerifyAll()
def setActiveUser(self, id=None, token=None, username=None, tenant_id=None,
service_catalog=None, tenant_name=None, roles=None,
authorized_tenants=None):
users.get_user_from_request = lambda x: \
users.User(id=id,
token=token,
user=username,
tenant_id=tenant_id,
service_catalog=service_catalog,
roles=roles,
authorized_tenants=authorized_tenants,
request=self.request)
def override_times(self):
""" Overrides the "current" time with immutable values. """
now = datetime.datetime.utcnow()
time.override_time = \
datetime.time(now.hour, now.minute, now.second)
today.override_time = datetime.date(now.year, now.month, now.day)
utcnow.override_time = now
return now
def reset_times(self):
""" Undoes the changes made by ``override_times``. """
time.override_time = None
today.override_time = None
utcnow.override_time = None
def assertRedirectsNoFollow(self, response, expected_url):
"""
Asserts that the given response issued a 302 redirect without
processing the view which is redirected to.
"""
assert (response.status_code / 100 == 3), \
"The response did not return a redirect."
self.assertEqual(response._headers.get('location', None),
('Location', settings.TESTSERVER + expected_url))
self.assertEqual(response.status_code, 302)
def assertNoMessages(self, response=None):
"""
Asserts that no messages have been attached by the ``contrib.messages``
framework.
"""
self.assertMessageCount(response, success=0, warn=0, info=0, error=0)
def assertMessageCount(self, response=None, **kwargs):
"""
Asserts that the specified number of messages have been attached
for various message types. Usage would look like
``self.assertMessageCount(success=1)``.
"""
temp_req = self.client.request(**{'wsgi.input': None})
temp_req.COOKIES = self.client.cookies
storage = default_storage(temp_req)
messages = []
if response is None:
# To gain early access to the messages we have to decode the
# cookie on the test client.
if 'messages' in self.client.cookies:
message_cookie = self.client.cookies['messages'].value
messages = storage._decode(message_cookie)
# Check for messages in the context
elif hasattr(response, "context") and "messages" in response.context:
messages = response.context["messages"]
# Check for messages attached to the request on a TemplateResponse
elif hasattr(response, "_request") and hasattr(response._request,
"_messages"):
messages = response._request._messages._queued_messages
# If we don't have messages and we don't expect messages, we're done.
if not any(kwargs.values()) and not messages:
return
# If we expected messages and have none, that's a problem.
if any(kwargs.values()) and not messages:
error_msg = "Messages were expected, but none were set."
assert 0 == sum(kwargs.values()), error_msg
# Otherwise, make sure we got the expected messages.
for msg_type, count in kwargs.items():
msgs = [m.message for m in messages if msg_type in m.tags]
assert len(msgs) == count, \
"%s messages not as expected: %s" % (msg_type.title(),
", ".join(msgs))
def assertNoFormErrors(self, response, context_name="form"):
"""
Asserts that the response either does not contain a form in it's
context, or that if it does, that form has no errors.
"""
context = getattr(response, "context", {})
if not context or context_name not in context:
return True
errors = response.context[context_name]._errors
assert len(errors) == 0, \
"Unexpected errors were found on the form: %s" % errors
def assertFormErrors(self, response, count=0, message=None,
context_name="form"):
"""
Asserts that the response does contain a form in it's
context, and that form has errors, if count were given,
it must match the exact numbers of errors
"""
context = getattr(response, "context", {})
assert (context and context_name in context), \
"The response did not contain a form."
errors = response.context[context_name]._errors
if count:
assert len(errors) == count, \
"%d errors were found on the form, %d expected" % \
(len(errors), count)
if message and message not in unicode(errors):
self.fail("Expected message not found, instead found: %s"
% ["%s: %s" % (key, [e for e in field_errors]) for
(key, field_errors) in errors.items()])
else:
assert len(errors) > 0, "No errors were found on the form"
class BaseAdminViewTests(TestCase):
"""
A ``TestCase`` subclass which sets an active user with the "admin" role
for testing admin-only views and functionality.
"""
def setActiveUser(self, *args, **kwargs):
if "roles" not in kwargs:
kwargs['roles'] = [self.roles.admin._info]
super(BaseAdminViewTests, self).setActiveUser(*args, **kwargs)
class APITestCase(TestCase):
"""
The ``APITestCase`` class is for use with tests which deal with the
underlying clients rather than stubbing out the horizon.api.* methods.
"""
def setUp(self):
super(APITestCase, self).setUp()
def fake_keystoneclient(request, username=None, password=None,
tenant_id=None, token_id=None, endpoint=None,
admin=False):
"""
Wrapper function which returns the stub keystoneclient. Only
necessary because the function takes too many arguments to
conveniently be a lambda.
"""
return self.stub_keystoneclient()
# Store the original clients
self._original_glanceclient = api.glance.glanceclient
self._original_keystoneclient = api.keystone.keystoneclient
self._original_novaclient = api.nova.novaclient
self._original_quantumclient = api.quantum.quantumclient
# Replace the clients with our stubs.
api.glance.glanceclient = lambda request: self.stub_glanceclient()
api.keystone.keystoneclient = fake_keystoneclient
api.nova.novaclient = lambda request: self.stub_novaclient()
api.quantum.quantumclient = lambda request: self.stub_quantumclient()
def tearDown(self):
super(APITestCase, self).tearDown()
api.glance.glanceclient = self._original_glanceclient
api.nova.novaclient = self._original_novaclient
api.keystone.keystoneclient = self._original_keystoneclient
def stub_novaclient(self):
if not hasattr(self, "novaclient"):
self.mox.StubOutWithMock(nova_client, 'Client')
self.novaclient = self.mox.CreateMock(nova_client.Client)
return self.novaclient
def stub_keystoneclient(self):
if not hasattr(self, "keystoneclient"):
self.mox.StubOutWithMock(keystone_client, 'Client')
self.keystoneclient = self.mox.CreateMock(keystone_client.Client)
return self.keystoneclient
def stub_glanceclient(self):
if not hasattr(self, "glanceclient"):
self.mox.StubOutWithMock(glance_client, 'Client')
self.glanceclient = self.mox.CreateMock(glance_client.Client)
return self.glanceclient
def stub_swiftclient(self, expected_calls=1):
if not hasattr(self, "swiftclient"):
self.mox.StubOutWithMock(swift_client, 'Connection')
self.swiftclient = self.mox.CreateMock(swift_client.Connection)
while expected_calls:
swift_client.Connection(auth=mox.IgnoreArg())\
.AndReturn(self.swiftclient)
expected_calls -= 1
return self.swiftclient
def stub_quantumclient(self):
if not hasattr(self, "quantumclient"):
self.mox.StubOutWithMock(quantum_client, 'Client')
self.quantumclient = self.mox.CreateMock(quantum_client.Client)
return self.quantumclient
|
apache-2.0
|
CanIFuckYou/AirTouch
|
AirTouch/Framework/View/HWKChart/Plots/HWMPlot.h
|
1763
|
//
// HWMPlot.h
// Weather
//
// Created by kenny on 15/9/25.
// Copyright (c) 2015年 honeywell. All rights reserved.
//
#import "HWMLayer.h"
typedef NS_ENUM(NSUInteger, HWMPlotType) {
HWMPlotTypeScatter,
HWMPlotTypeBar
};
@interface HWMRainRange: NSObject
@property (nonatomic, assign) NSUInteger start;
@property (nonatomic, assign) NSUInteger end;
@end
@interface HWMPlot : HWMLayer
@property (nonatomic, strong) NSArray *contentArray;
@property (nonatomic, assign) CGFloat leftPadding;
@property (nonatomic, assign) CGFloat rightPadding;
@property (nonatomic, assign) CGFloat bottomPadding;
@property (nonatomic, assign) CGFloat topPadding;
@property (nonatomic, assign) CGFloat superBottomPadding;
@property (nonatomic, assign) CGFloat superTopPadding;
@property (nonatomic, assign) CGFloat labelLeftPadding;
@property (nonatomic, assign) CGFloat labelRightPadding;
@property (nonatomic, assign) HWMPlotType plotType;
- (id)initWithPlotType:(HWMPlotType)type;
-(void)moveDashedLine:(CGPoint)pos withAnimation:(BOOL)val;
-(void)moveDashedLine:(CGPoint)pos withAnimation:(BOOL)animate checkClickArea:(BOOL)check;
@end
@interface HWMScatterPlot : HWMPlot
//@property (nonatomic, strong) NSArray *contentArray;
//@property (nonatomic, assign) CGFloat leftPadding;
//@property (nonatomic, assign) CGFloat rightPadding;
//@property (nonatomic, assign) CGFloat bottomPadding;
//@property (nonatomic, assign) CGFloat topPadding;
@end
@interface HWMBarPlot : HWMPlot
//@property (nonatomic, strong) NSArray *contentArray;
//@property (nonatomic, assign) CGFloat leftPadding;
//@property (nonatomic, assign) CGFloat rightPadding;
//@property (nonatomic, assign) CGFloat bottomPadding;
//@property (nonatomic, assign) CGFloat topPadding;
@end
|
apache-2.0
|
skyofthinking/AndRapid
|
gankio/src/main/java/com/joyue/tech/gankio/mvp/history/HistoryModel.java
|
764
|
package com.joyue.tech.gankio.mvp.history;
import com.joyue.tech.core.mvp.listener.OnLoadDataListListener;
import com.joyue.tech.gankio.api.GankApi;
import rx.Observer;
public class HistoryModel implements HistoryContract.Model {
@Override
public void history(OnLoadDataListListener listener) {
GankApi.getInstance().history(new Observer<String[]>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//设置页面为加载错误
listener.onFailure(e);
}
@Override
public void onNext(String[] data) {
listener.onSuccess(data);
}
});
}
}
|
apache-2.0
|
eropple/amigrind
|
lib/amigrind/repo.rb
|
6902
|
module Amigrind
class Repo
include Amigrind::Core::Logging::Mixin
attr_reader :path
def initialize(path)
@path = File.expand_path path
raise "'path' (#{path}) is not a directory." unless Dir.exist?(path)
raise "'path' is not an Amigrind root (lacks .amigrind_root file)." \
unless File.exist?(File.join(path, '.amigrind_root'))
info_log "using Amigrind path: #{path}"
end
def environments_path
File.join(path, 'environments')
end
def blueprints_path
File.join(path, 'blueprints')
end
# TODO: Ruby DSL environments
def environment_names
yaml_environments =
Dir[File.join(environments_path, '*.yaml')] \
.map { |f| File.basename(f, '.yaml').to_s.strip.downcase }
rb_environments =
[].map { |f| File.basename(f, '.rb').to_s.strip.downcase }
duplicate_environments = yaml_environments & rb_environments
duplicate_environments.each do |dup_env_name|
warn_log "environment '#{dup_env_name}' found in both YAML and Ruby; skipping."
end
(yaml_environments + rb_environments - duplicate_environments).sort
end
# TODO: cache environments (but make configurable)
def environment(name)
yaml_path = yaml_path_if_exists(name)
rb_path = rb_path_if_exists(name)
raise "found multiple env files for same env #{name}." if !yaml_path.nil? && !rb_path.nil?
raise "TODO: implement Ruby environments." unless rb_path.nil?
env = Environments::Environment.load_yaml_file(yaml_path) unless yaml_path.nil?
raise "no env found for '#{name}'." if env.nil?
IceNine.deep_freeze(env)
env
end
def with_environment(environment_name, &block)
block.call(environment(environment_name))
end
def blueprint_names
Dir[File.join(blueprints_path, "*.rb")].map { |f| File.basename(f, ".rb") }
end
# TODO: cache blueprint/environment tuples (but make configurable)
def evaluate_blueprint(blueprint_name, env)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
if env.is_a?(String)
env = environment(env)
end
ev = Amigrind::Blueprints::Evaluator.new(File.join(blueprints_path,
"#{blueprint_name}.rb"),
env)
ev.blueprint
end
# TODO: refactor these client-y things.
def add_to_channel(env, blueprint_name, id, channel)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'id' must be a Fixnum." unless id.is_a?(Fixnum)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
ec2 = Aws::EC2::Client.new(region: env.aws.region, credentials: credentials)
image = amigrind_client.get_image_by_id(name: blueprint_name, id: id)
tag_key = Amigrind::Core::AMIGRIND_CHANNEL_TAG % { channel_name: channel }
info_log "setting '#{tag_key}' on image #{image.id}..."
ec2.create_tags(
resources: [ image.id ],
tags: [
{
key: tag_key,
value: '1'
}
]
)
end
def remove_from_channel(env, blueprint_name, id, channel)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'id' must be a Fixnum." unless id.is_a?(Fixnum)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
ec2 = Aws::EC2::Client.new(region: env.aws.region, credentials: credentials)
image = amigrind_client.get_image_by_id(name: blueprint_name, id: id)
tag_key = Amigrind::Core::AMIGRIND_CHANNEL_TAG % { channel_name: channel }
info_log "clearing '#{tag_key}' on image #{image.id}..."
ec2.delete_tags(
resources: [ image.id ],
tags: [
{
key: tag_key,
value: nil
}
]
)
end
def get_image_by_channel(env, blueprint_name, channel, steps_back = 0)
raise "'env' must be a String or an Environment." \
unless env.is_a?(String) || env.is_a?(Environments::Environment)
raise "'blueprint_name' must be a String." unless blueprint_name.is_a?(String)
raise "'channel' must be a String or Symbol." \
unless channel.is_a?(String) || channel.is_a?(Symbol)
if env.is_a?(String)
env = environment(env)
end
raise "channel '#{channel}' does not exist in environment '#{env.name}'." \
unless env.channels.key?(channel.to_s) || channel.to_sym == :latest
credentials = Amigrind::Config.aws_credentials(env)
amigrind_client = Amigrind::Core::Client.new(env.aws.region, credentials)
amigrind_client.get_image_by_channel(name: blueprint_name, channel: channel, steps_back: steps_back)
end
class << self
def init(path:)
raise "TODO: implement"
end
def with_repo(path: nil, &block)
path = path || ENV['AMIGRIND_PATH'] || Dir.pwd
repo = Repo.new(path)
Dir.chdir path do
block.call(repo)
end
end
end
private
def yaml_path_if_exists(name)
matches = [
"#{environments_path}/#{name}.yml",
"#{environments_path}/#{name}.yaml",
"#{environments_path}/#{name}.yml.erb",
"#{environments_path}/#{name}.yaml.erb"
].select { |f| File.exist?(f) }
case matches.size
when 0
nil
when 1
matches.first
else
raise "found multiple env files for same env #{name}."
end
end
def rb_path_if_exists(name)
path = "#{environments_path}/#{name}.rb"
File.exist?(path) ? path : nil
end
end
end
|
apache-2.0
|
sendwithus/sendwithus_ruby
|
test/lib/send_with_us/version_test.rb
|
156
|
require_relative '../../test_helper'
class TestVersion < Minitest::Test
def test_version
assert_equal( false, SendWithUs::VERSION.nil? )
end
end
|
apache-2.0
|
sabob/ratel
|
ratel/src/com/google/ratel/deps/jackson/databind/ser/std/StringSerializer.java
|
1752
|
package com.google.ratel.deps.jackson.databind.ser.std;
import java.io.IOException;
import java.lang.reflect.Type;
import com.google.ratel.deps.jackson.core.*;
import com.google.ratel.deps.jackson.databind.JavaType;
import com.google.ratel.deps.jackson.databind.JsonMappingException;
import com.google.ratel.deps.jackson.databind.JsonNode;
import com.google.ratel.deps.jackson.databind.SerializerProvider;
import com.google.ratel.deps.jackson.databind.annotation.JacksonStdImpl;
import com.google.ratel.deps.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
/**
* This is the special serializer for regular {@link java.lang.String}s.
*<p>
* Since this is one of "native" types, no type information is ever
* included on serialization (unlike for most scalar types as of 1.5)
*/
@JacksonStdImpl
public final class StringSerializer
extends NonTypedScalarSerializerBase<String>
{
public StringSerializer() { super(String.class); }
/**
* For Strings, both null and Empty String qualify for emptiness.
*/
@Override
public boolean isEmpty(String value) {
return (value == null) || (value.length() == 0);
}
@Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
jgen.writeString(value);
}
@Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint)
{
return createSchemaNode("string", true);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
throws JsonMappingException
{
if (visitor != null) visitor.expectStringFormat(typeHint);
}
}
|
apache-2.0
|
pellse/decorator
|
src/test/java/io/github/pellse/decorator/collection/InitializedBoundedList.java
|
772
|
/**
* Copyright 2016 Sebastien Pelletier
*
* 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 io.github.pellse.decorator.collection;
public abstract class InitializedBoundedList<E> extends BoundedList<E>{
public InitializedBoundedList() {
super(3);
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.