code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
using System;
namespace TodoListService_ManualJwt.Areas.HelpPage.ModelDescriptions
{
public class ParameterAnnotation
{
public Attribute AnnotationAttribute { get; set; }
public string Documentation { get; set; }
}
} | AzureADSamples/WebAPI-ManuallyValidateJwt-DotNet | TodoListService-ManualJwt/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs | C# | apache-2.0 | 246 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `WCONTINUED` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, WCONTINUED">
<title>libc::WCONTINUED - Rust</title>
<link rel="stylesheet" type="text/css" href="../normalize.css">
<link rel="stylesheet" type="text/css" href="../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc constant">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'WCONTINUED', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Constant <a href='index.html'>libc</a>::<wbr><a class="constant" href=''>WCONTINUED</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../src/libc/unix/notbsd/mod.rs.html#711' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const WCONTINUED: <a class="type" href="../libc/type.c_int.html" title="type libc::c_int">c_int</a><code> = </code><code>8</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../";
window.currentCrate = "libc";
</script>
<script src="../jquery.js"></script>
<script src="../main.js"></script>
<script defer src="../search-index.js"></script>
</body>
</html> | nitro-devs/nitro-game-engine | docs/libc/constant.WCONTINUED.html | HTML | apache-2.0 | 4,307 |
/*
* Copyright 2006-2012 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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 edu.samplu.mainmenu.test;
import org.junit.Test;
/**
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class PeopleFlowCreateNewSTJUnitBkMrkGen extends PeopleFlowCreateNewSTJUnitBase {
@Override
public String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Test
public void testPeopleFlowCreateNewBookmark() throws Exception {
testPeopleFlowCreateNewBookmark(this);
}
}
| ua-eas/ksd-kc5.2.1-rice2.3.6-ua | rice-middleware/sampleapp/src/it/java/edu/samplu/mainmenu/test/PeopleFlowCreateNewSTJUnitBkMrkGen.java | Java | apache-2.0 | 1,051 |
# Niebla pulchribarbara (Rundel & Bowler) Rundel & Bowler SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 6(3): 499 (1978)
#### Original name
Desmazieria pulchribarbara Rundel & Bowler
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Niebla/Niebla pulchribarbara/README.md | Markdown | apache-2.0 | 248 |
/*
* Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. 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
*
* This software 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.cloudera.hoop.fs;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* File system utilities used by Hoop classes.
*/
public class FSUtils {
/**
* Constant for the default permission string ('default').
*/
public static final String DEFAULT_PERMISSION = "default";
/**
* Converts a Unix permission symbolic representation
* (i.e. -rwxr--r--) into a Hadoop permission.
*
* @param str Unix permission symbolic representation.
* @return the Hadoop permission. If the given string was
* 'default', it returns <code>FsPermission.getDefault()</code>.
*/
public static FsPermission getPermission(String str) {
FsPermission permission;
if (str.equals(DEFAULT_PERMISSION)) {
permission = FsPermission.getDefault();
}
else {
//TODO: there is something funky here, it does not detect 'x'
permission = FsPermission.valueOf(str);
}
return permission;
}
/**
* Replaces the <code>SCHEME://HOST:PORT</code> of a Hadoop
* <code>Path</code> with the specified base URL.
*
* @param path Hadoop path to replace the
* <code>SCHEME://HOST:PORT</code>.
* @param hoopBaseUrl base URL to replace it with.
* @return the path using the given base URL.
*/
public static Path convertPathToHoop(Path path, String hoopBaseUrl) {
URI uri = path.toUri();
String filePath = uri.getRawPath();
String hoopPath = hoopBaseUrl + filePath;
return new Path(hoopPath);
}
/**
* Converts a Hadoop permission into a Unix permission symbolic
* representation (i.e. -rwxr--r--) or default if the permission is NULL.
*
* @param p Hadoop permission.
* @return the Unix permission symbolic representation or default if the
* permission is NULL.
*/
private static String permissionToString(FsPermission p) {
return (p == null) ? "default" : "-" + p.getUserAction().SYMBOL + p.getGroupAction().SYMBOL +
p.getOtherAction().SYMBOL;
}
/**
* Converts a Hadoop <code>FileStatus</code> object into a JSON array
* object. It replaces the <code>SCHEME://HOST:PORT</code> of the path
* with the specified URL.
* <p/>
* @param status Hadoop file status.
* @param hoopBaseUrl base URL to replace the
* <code>SCHEME://HOST:PORT</code> in the file status.
* @return The JSON representation of the file status.
*/
@SuppressWarnings("unchecked")
public static Map fileStatusToJSON(FileStatus status, String hoopBaseUrl) {
Map json = new LinkedHashMap();
json.put("path", convertPathToHoop(status.getPath(), hoopBaseUrl).toString());
json.put("isDir", status.isDir());
json.put("len", status.getLen());
json.put("owner", status.getOwner());
json.put("group", status.getGroup());
json.put("permission", permissionToString(status.getPermission()));
json.put("accessTime", status.getAccessTime());
json.put("modificationTime", status.getModificationTime());
json.put("blockSize", status.getBlockSize());
json.put("replication", status.getReplication());
return json;
}
/**
* Converts a Hadoop <code>FileStatus</code> array into a JSON array
* object. It replaces the <code>SCHEME://HOST:PORT</code> of the path
* with the specified URL.
* <p/>
* @param status Hadoop file status array.
* @param hoopBaseUrl base URL to replace the
* <code>SCHEME://HOST:PORT</code> in the file status.
* @return The JSON representation of the file status array.
*/
@SuppressWarnings("unchecked")
public static JSONArray fileStatusToJSON(FileStatus[] status, String hoopBaseUrl) {
JSONArray json = new JSONArray();
if (status != null) {
for (FileStatus s : status) {
json.add(fileStatusToJSON(s, hoopBaseUrl));
}
}
return json;
}
/**
* Converts an object into a Json Map with with one key-value entry.
* <p/>
* It assumes the given value is either a JSON primitive type or a
* <code>JsonAware</code> instance.
*
* @param name name for the key of the entry.
* @param value for the value of the entry.
* @return the JSON representation of the key-value pair.
*/
@SuppressWarnings("unchecked")
public static JSONObject toJSON(String name, Object value) {
JSONObject json = new JSONObject();
json.put(name, value);
return json;
}
}
| showyou/hoop-webhdfs-hue | hoop-server/src/main/java/com/cloudera/hoop/fs/FSUtils.java | Java | apache-2.0 | 5,152 |
/*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bob Jervis
* Google Inc.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN;
import com.google.common.base.Predicate;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.jstype.JSTypeRegistry.ResolveMode;
import java.io.Serializable;
import java.util.Comparator;
/**
* Represents JavaScript value types.<p>
*
* Types are split into two separate families: value types and object types.
*
* A special {@link UnknownType} exists to represent a wildcard type on which
* no information can be gathered. In particular, it can assign to everyone,
* is a subtype of everyone (and everyone is a subtype of it).<p>
*
* If you remove the {@link UnknownType}, the set of types in the type system
* forms a lattice with the {@link #isSubtype} relation defining the partial
* order of types. All types are united at the top of the lattice by the
* {@link AllType} and at the bottom by the {@link NoType}.<p>
*
*/
public abstract class JSType implements Serializable {
private static final long serialVersionUID = 1L;
private boolean resolved = false;
private JSType resolveResult = null;
public static final String UNKNOWN_NAME =
"Unknown class name";
public static final String NOT_A_CLASS =
"Not declared as a constructor";
public static final String NOT_A_TYPE =
"Not declared as a type name";
public static final String EMPTY_TYPE_COMPONENT =
"Named type with empty name component";
/**
* Total ordering on types based on their textual representation.
* This is used to have a deterministic output of the toString
* method of the union type since this output is used in tests.
*/
static final Comparator<JSType> ALPHA = new Comparator<JSType>() {
public int compare(JSType t1, JSType t2) {
return t1.toString().compareTo(t2.toString());
}
};
// A flag set on enum definition tree nodes
public static final int ENUMDECL = 1;
public static final int NOT_ENUMDECL = 0;
final JSTypeRegistry registry;
JSType(JSTypeRegistry registry) {
this.registry = registry;
}
/**
* Utility method for less verbose code.
*/
JSType getNativeType(JSTypeNative typeId) {
return registry.getNativeType(typeId);
}
/**
* Gets the docInfo for this type. By default, documentation cannot be
* attached to arbitrary types. This must be overridden for
* programmer-defined types.
*/
public JSDocInfo getJSDocInfo() {
return null;
}
/**
* Returns a user meaningful label for the JSType instance. For example,
* Functions and Enums will return their declaration name (if they have one).
* Some types will not have a meaningful display name. Calls to
* hasDisplayName() will return true IFF getDisplayName() will return null
* or a zero length string.
*
* @return the display name of the type, or null if one is not available
*/
public String getDisplayName() {
return null;
}
/**
* @return true if the JSType has a user meaningful label.
*/
public boolean hasDisplayName() {
String displayName = getDisplayName();
return displayName != null && !displayName.isEmpty();
}
public boolean isNoType() {
return false;
}
public boolean isNoResolvedType() {
return false;
}
public boolean isNoObjectType() {
return false;
}
public final boolean isEmptyType() {
return isNoType() || isNoObjectType() || isNoResolvedType() ||
(registry.getNativeFunctionType(
JSTypeNative.LEAST_FUNCTION_TYPE) == this);
}
public boolean isNumberObjectType() {
return false;
}
public boolean isNumberValueType() {
return false;
}
/** Whether this is the prototype of a function. */
public boolean isFunctionPrototypeType() {
return false;
}
public boolean isStringObjectType() {
return false;
}
boolean isTheObjectType() {
return false;
}
public boolean isStringValueType() {
return false;
}
/**
* Tests whether the type is a string (value or Object).
* @return {@code this <: (String, string)}
*/
public final boolean isString() {
return this.isSubtype(
getNativeType(JSTypeNative.STRING_VALUE_OR_OBJECT_TYPE));
}
/**
* Tests whether the type is a number (value or Object).
* @return {@code this <: (Number, number)}
*/
public final boolean isNumber() {
return this.isSubtype(
getNativeType(JSTypeNative.NUMBER_VALUE_OR_OBJECT_TYPE));
}
public boolean isArrayType() {
return false;
}
public boolean isBooleanObjectType() {
return false;
}
public boolean isBooleanValueType() {
return false;
}
public boolean isRegexpType() {
return false;
}
public boolean isDateType() {
return false;
}
public boolean isNullType() {
return false;
}
public boolean isVoidType() {
return false;
}
public boolean isAllType() {
return false;
}
public boolean isUnknownType() {
return false;
}
public boolean isCheckedUnknownType() {
return false;
}
public boolean isUnionType() {
return false;
}
public boolean isFunctionType() {
return false;
}
public boolean isEnumElementType() {
return false;
}
public boolean isEnumType() {
return false;
}
boolean isNamedType() {
return false;
}
public boolean isRecordType() {
return false;
}
public boolean isTemplateType() {
return false;
}
/**
* Tests whether this type is an {@code Object}, or any subtype thereof.
* @return {@code this <: Object}
*/
public boolean isObject() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is a constructor or a
* named type that points to such a type.
*/
public boolean isConstructor() {
return false;
}
/**
* Whether this type is a nominal type (a named instance object or
* a named enum).
*/
public boolean isNominalType() {
return false;
}
/**
* Whether this type is an Instance object of some constructor.
*/
public boolean isInstanceType() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is an interface or a named
* type that points to such a type.
*/
public boolean isInterface() {
return false;
}
/**
* Whether this type is a {@link FunctionType} that is an ordinary function or
* a named type that points to such a type.
*/
public boolean isOrdinaryFunction() {
return false;
}
/**
* Checks if two types are equivalent.
*/
public boolean isEquivalentTo(JSType jsType) {
if (jsType instanceof ProxyObjectType) {
return jsType.isEquivalentTo(this);
}
// Relies on the fact that for the base {@link JSType}, only one
// instance of each sub-type will ever be created in a given registry, so
// there is no need to verify members. If the object pointers are not
// identical, then the type member must be different.
return this == jsType;
}
public static boolean isEquivalent(JSType typeA, JSType typeB) {
return (typeA == null || typeB == null) ?
typeA == typeB : typeA.isEquivalentTo(typeB);
}
@Override
public boolean equals(Object jsType) {
return (jsType instanceof JSType) ?
isEquivalentTo((JSType) jsType) : false;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
/**
* This predicate is used to test whether a given type can appear in a
* 'Int32' context. This context includes, for example, the operands of a
* bitwise or operator. Since we do not currently support integer types,
* this is a synonym for {@code Number}.
*/
public final boolean matchesInt32Context() {
return matchesNumberContext();
}
/**
* This predicate is used to test whether a given type can appear in a
* 'Uint32' context. This context includes the right-hand operand of a shift
* operator.
*/
public final boolean matchesUint32Context() {
return matchesNumberContext();
}
/**
* This predicate is used to test whether a given type can appear in a
* numeric context, such as an operand of a multiply operator.
*/
public boolean matchesNumberContext() {
return false;
}
/**
* This predicate is used to test whether a given type can appear in a
* {@code String} context, such as an operand of a string concat (+) operator.
*
* All types have at least the potential for converting to {@code String}.
* When we add externally defined types, such as a browser OM, we may choose
* to add types that do not automatically convert to {@code String}.
*/
public boolean matchesStringContext() {
return false;
}
/**
* This predicate is used to test whether a given type can appear in an
* {@code Object} context, such as the expression in a with statement.
*
* Most types we will encounter, except notably {@code null}, have at least
* the potential for converting to {@code Object}. Host defined objects can
* get peculiar.
*/
public boolean matchesObjectContext() {
return false;
}
/**
* Coerces this type to an Object type, then gets the type of the property
* whose name is given.
*
* Unlike {@link ObjectType#getPropertyType}, returns null if the property
* is not found.
*
* @return The property's type. {@code null} if the current type cannot
* have properties, or if the type is not found.
*/
public JSType findPropertyType(String propertyName) {
ObjectType autoboxObjType = ObjectType.cast(autoboxesTo());
if (autoboxObjType != null) {
return autoboxObjType.findPropertyType(propertyName);
}
return null;
}
/**
* This predicate is used to test whether a given type can be used as the
* 'function' in a function call.
*
* @return {@code true} if this type might be callable.
*/
public boolean canBeCalled() {
return false;
}
/**
* Tests whether values of {@code this} type can be safely assigned
* to values of {@code that} type.<p>
*
* The default implementation verifies that {@code this} is a subtype
* of {@code that}.<p>
*/
public boolean canAssignTo(JSType that) {
if (this.isSubtype(that)) {
return true;
}
return false;
}
/**
* Gets the type to which this type auto-boxes.
*
* @return the auto-boxed type or {@code null} if this type does not auto-box
*/
public JSType autoboxesTo() {
return null;
}
/**
* Gets the type to which this type unboxes.
*
* @return the unboxed type or {@code null} if this type does not unbox.
*/
public JSType unboxesTo() {
return null;
}
/**
* Casts this to an ObjectType, or returns null if this is not an ObjectType.
*
* Does not change the underlying JS type. If you want to simulate JS
* autoboxing or dereferencing, you should use autoboxesTo() or dereference().
* Those methods may change the underlying JS type.
*/
public ObjectType toObjectType() {
return this instanceof ObjectType ? (ObjectType) this : null;
}
/**
* Dereference a type for property access.
*
* Autoboxes the type, filters null/undefined, and returns the result
* iff it's an object.
*/
public final ObjectType dereference() {
JSType restricted = restrictByNotNullOrUndefined();
JSType autobox = restricted.autoboxesTo();
return ObjectType.cast(autobox == null ? restricted : autobox);
}
/**
* Tests whether {@code this} and {@code that} are meaningfully
* comparable. By meaningfully, we mean compatible types that do not lead
* to step 22 of the definition of the Abstract Equality Comparison
* Algorithm (11.9.3, page 55–56) of the ECMA-262 specification.<p>
*/
public final boolean canTestForEqualityWith(JSType that) {
return this.testForEquality(that).equals(UNKNOWN);
}
/**
* Compares {@code this} and {@code that}.
* @return <ul>
* <li>{@link TernaryValue#TRUE} if the comparison of values of
* {@code this} type and {@code that} always succeed (such as
* {@code undefined} compared to {@code null})</li>
* <li>{@link TernaryValue#FALSE} if the comparison of values of
* {@code this} type and {@code that} always fails (such as
* {@code undefined} compared to {@code number})</li>
* <li>{@link TernaryValue#UNKNOWN} if the comparison can succeed or
* fail depending on the concrete values</li>
* </ul>
*/
public TernaryValue testForEquality(JSType that) {
return testForEqualityHelper(this, that);
}
TernaryValue testForEqualityHelper(JSType aType, JSType bType) {
if (bType.isAllType() || bType.isUnknownType() ||
bType.isNoResolvedType() ||
aType.isAllType() || aType.isUnknownType() ||
aType.isNoResolvedType()) {
return UNKNOWN;
}
boolean aIsEmpty = aType.isEmptyType();
boolean bIsEmpty = bType.isEmptyType();
if (aIsEmpty || bIsEmpty) {
if (aIsEmpty && bIsEmpty) {
return TernaryValue.TRUE;
} else {
return UNKNOWN;
}
}
if (aType.isFunctionType() || bType.isFunctionType()) {
JSType otherType = aType.isFunctionType() ? bType : aType;
// In theory, functions are comparable to anything except
// null/undefined. For example, on FF3:
// function() {} == 'function () {\n}'
// In practice, how a function serializes to a string is
// implementation-dependent, so it does not really make sense to test
// for equality with a string.
JSType meet = otherType.getGreatestSubtype(
getNativeType(JSTypeNative.OBJECT_TYPE));
if (meet.isNoType() || meet.isNoObjectType()) {
return TernaryValue.FALSE;
} else {
return TernaryValue.UNKNOWN;
}
}
if (bType.isEnumElementType() || bType.isUnionType()) {
return bType.testForEquality(aType);
}
return null;
}
/**
* Tests whether {@code this} and {@code that} are meaningfully
* comparable using shallow comparison. By meaningfully, we mean compatible
* types that are not rejected by step 1 of the definition of the Strict
* Equality Comparison Algorithm (11.9.6, page 56–57) of the
* ECMA-262 specification.<p>
*/
public final boolean canTestForShallowEqualityWith(JSType that) {
return this.isSubtype(that) || that.isSubtype(this);
}
/**
* Tests whether this type is nullable.
*/
public boolean isNullable() {
return this.isSubtype(getNativeType(JSTypeNative.NULL_TYPE));
}
/**
* Gets the least supertype of {@code this} and {@code that}.
* The least supertype is the join (∨) or supremum of both types in the
* type lattice.<p>
* Examples:
* <ul>
* <li>{@code number ∨ *} = {@code *}</li>
* <li>{@code number ∨ Object} = {@code (number, Object)}</li>
* <li>{@code Number ∨ Object} = {@code Object}</li>
* </ul>
* @return {@code this ∨ that}
*/
public JSType getLeastSupertype(JSType that) {
if (that.isUnionType()) {
// Union types have their own implementation of getLeastSupertype.
return that.getLeastSupertype(this);
}
return getLeastSupertype(this, that);
}
/**
* A generic implementation meant to be used as a helper for common
* getLeastSupertype implementations.
*/
static JSType getLeastSupertype(JSType thisType, JSType thatType) {
boolean areEquivalent = thisType.isEquivalentTo(thatType);
return areEquivalent ? thisType :
filterNoResolvedType(
thisType.registry.createUnionType(thisType, thatType));
}
/**
* Gets the greatest subtype of {@code this} and {@code that}.
* The greatest subtype is the meet (∧) or infimum of both types in the
* type lattice.<p>
* Examples
* <ul>
* <li>{@code Number ∧ Any} = {@code Any}</li>
* <li>{@code number ∧ Object} = {@code Any}</li>
* <li>{@code Number ∧ Object} = {@code Number}</li>
* </ul>
* @return {@code this ∨ that}
*/
public JSType getGreatestSubtype(JSType that) {
if (that.isRecordType()) {
// Record types have their own implementation of getGreatestSubtype.
return that.getGreatestSubtype(this);
}
return getGreatestSubtype(this, that);
}
/**
* A generic implementation meant to be used as a helper for common
* getGreatestSubtype implementations.
*/
static JSType getGreatestSubtype(JSType thisType, JSType thatType) {
if (thisType.isEquivalentTo(thatType)) {
return thisType;
} else if (thisType.isUnknownType() || thatType.isUnknownType()) {
// The greatest subtype with any unknown type is the universal
// unknown type, unless the two types are equal.
return thisType.isEquivalentTo(thatType) ? thisType :
thisType.getNativeType(JSTypeNative.UNKNOWN_TYPE);
} else if (thisType.isSubtype(thatType)) {
return filterNoResolvedType(thisType);
} else if (thatType.isSubtype(thisType)) {
return filterNoResolvedType(thatType);
} else if (thisType.isUnionType()) {
return ((UnionType) thisType).meet(thatType);
} else if (thatType.isUnionType()) {
return ((UnionType) thatType).meet(thisType);
} else if (thisType.isObject() && thatType.isObject()) {
return thisType.getNativeType(JSTypeNative.NO_OBJECT_TYPE);
}
return thisType.getNativeType(JSTypeNative.NO_TYPE);
}
/**
* When computing infimums, we may get a situation like
* inf(Type1, Type2)
* where both types are unresolved, so they're technically
* subtypes of one another.
*
* If this happens, filter them down to NoResolvedType.
*/
static JSType filterNoResolvedType(JSType type) {
if (type.isNoResolvedType()) {
// inf(UnresolvedType1, UnresolvedType2) needs to resolve
// to the base unresolved type, so that the relation is symmetric.
return type.getNativeType(JSTypeNative.NO_RESOLVED_TYPE);
} else if (type instanceof UnionType) {
UnionType unionType = (UnionType) type;
boolean needsFiltering = false;
for (JSType alt : unionType.getAlternates()) {
if (alt.isNoResolvedType()) {
needsFiltering = true;
break;
}
}
if (needsFiltering) {
UnionTypeBuilder builder = new UnionTypeBuilder(type.registry);
for (JSType alt : unionType.getAlternates()) {
if (!alt.isNoResolvedType()) {
builder.addAlternate(alt);
}
}
return builder.build();
}
}
return type;
}
/**
* Computes the restricted type of this type knowing that the
* {@code ToBoolean} predicate has a specific value. For more information
* about the {@code ToBoolean} predicate, see
* {@link #getPossibleToBooleanOutcomes}.
*
* @param outcome the value of the {@code ToBoolean} predicate
*
* @return the restricted type, or the Any Type if the underlying type could
* not have yielded this ToBoolean value
*
* TODO(user): Move this method to the SemanticRAI and use the visit
* method of types to get the restricted type.
*/
public JSType getRestrictedTypeGivenToBooleanOutcome(boolean outcome) {
BooleanLiteralSet literals = getPossibleToBooleanOutcomes();
if (literals.contains(outcome)) {
return this;
} else {
return getNativeType(JSTypeNative.NO_TYPE);
}
}
/**
* Computes the set of possible outcomes of the {@code ToBoolean} predicate
* for this type. The {@code ToBoolean} predicate is defined by the ECMA-262
* standard, 3<sup>rd</sup> edition. Its behavior for simple types can be
* summarized by the following table:
* <table>
* <tr><th>type</th><th>result</th></tr>
* <tr><td>{@code undefined}</td><td>{false}</td></tr>
* <tr><td>{@code null}</td><td>{false}</td></tr>
* <tr><td>{@code boolean}</td><td>{true, false}</td></tr>
* <tr><td>{@code number}</td><td>{true, false}</td></tr>
* <tr><td>{@code string}</td><td>{true, false}</td></tr>
* <tr><td>{@code Object}</td><td>{true}</td></tr>
* </table>
* @return the set of boolean literals for this type
*/
public abstract BooleanLiteralSet getPossibleToBooleanOutcomes();
/**
* Computes the subset of {@code this} and {@code that} types if equality
* is observed. If a value {@code v1} of type {@code null} is equal to a value
* {@code v2} of type {@code (undefined,number)}, we can infer that the
* type of {@code v1} is {@code null} and the type of {@code v2} is
* {@code undefined}.
*
* @return a pair containing the restricted type of {@code this} as the first
* component and the restricted type of {@code that} as the second
* element. The returned pair is never {@code null} even though its
* components may be {@code null}
*/
public TypePair getTypesUnderEquality(JSType that) {
// unions types
if (that instanceof UnionType) {
TypePair p = that.getTypesUnderEquality(this);
return new TypePair(p.typeB, p.typeA);
}
// other types
switch (this.testForEquality(that)) {
case FALSE:
return new TypePair(null, null);
case TRUE:
case UNKNOWN:
return new TypePair(this, that);
}
// switch case is exhaustive
throw new IllegalStateException();
}
/**
* Computes the subset of {@code this} and {@code that} types if inequality
* is observed. If a value {@code v1} of type {@code number} is not equal to a
* value {@code v2} of type {@code (undefined,number)}, we can infer that the
* type of {@code v1} is {@code number} and the type of {@code v2} is
* {@code number} as well.
*
* @return a pair containing the restricted type of {@code this} as the first
* component and the restricted type of {@code that} as the second
* element. The returned pair is never {@code null} even though its
* components may be {@code null}
*/
public TypePair getTypesUnderInequality(JSType that) {
// unions types
if (that instanceof UnionType) {
TypePair p = that.getTypesUnderInequality(this);
return new TypePair(p.typeB, p.typeA);
}
// other types
switch (this.testForEquality(that)) {
case TRUE:
JSType noType = getNativeType(JSTypeNative.NO_TYPE);
return new TypePair(noType, noType);
case FALSE:
case UNKNOWN:
return new TypePair(this, that);
}
// switch case is exhaustive
throw new IllegalStateException();
}
/**
* Computes the subset of {@code this} and {@code that} types under shallow
* equality.
*
* @return a pair containing the restricted type of {@code this} as the first
* component and the restricted type of {@code that} as the second
* element. The returned pair is never {@code null} even though its
* components may be {@code null}.
*/
public TypePair getTypesUnderShallowEquality(JSType that) {
JSType commonType = getGreatestSubtype(that);
return new TypePair(commonType, commonType);
}
/**
* Computes the subset of {@code this} and {@code that} types under
* shallow inequality.
*
* @return A pair containing the restricted type of {@code this} as the first
* component and the restricted type of {@code that} as the second
* element. The returned pair is never {@code null} even though its
* components may be {@code null}
*/
public TypePair getTypesUnderShallowInequality(JSType that) {
// union types
if (that instanceof UnionType) {
TypePair p = that.getTypesUnderShallowInequality(this);
return new TypePair(p.typeB, p.typeA);
}
// Other types.
// There are only two types whose shallow inequality is deterministically
// true -- null and undefined. We can just enumerate them.
if (this.isNullType() && that.isNullType() ||
this.isVoidType() && that.isVoidType()) {
return new TypePair(null, null);
} else {
return new TypePair(this, that);
}
}
/**
* If this is a union type, returns a union type that does not include
* the null or undefined type.
*/
public JSType restrictByNotNullOrUndefined() {
return this;
}
/**
* Checks whether {@code this} is a subtype of {@code that}.<p>
*
* Subtyping rules:
* <ul>
* <li>(unknown) — every type is a subtype of the Unknown type.</li>
* <li>(no) — the No type is a subtype of every type.</li>
* <li>(no-object) — the NoObject type is a subtype of every object
* type (i.e. subtypes of the Object type).</li>
* <li>(ref) — a type is a subtype of itself.</li>
* <li>(union-l) — A union type is a subtype of a type U if all the
* union type's constituents are a subtype of U. Formally<br>
* {@code (T<sub>1</sub>, …, T<sub>n</sub>) <: U} if and only
* {@code T<sub>k</sub> <: U} for all {@code k ∈ 1..n}.</li>
* <li>(union-r) — A type U is a subtype of a union type if it is a
* subtype of one of the union type's constituents. Formally<br>
* {@code U <: (T<sub>1</sub>, …, T<sub>n</sub>)} if and only
* if {@code U <: T<sub>k</sub>} for some index {@code k}.</li>
* <li>(objects) — an Object {@code O<sub>1</sub>} is a subtype
* of an object {@code O<sub>2</sub>} if it has more properties
* than {@code O<sub>2</sub>} and all common properties are
* pairwise subtypes.</li>
* </ul>
*
* @return {@code this <: that}
*/
public abstract boolean isSubtype(JSType that);
/**
* Whether this type is meaningfully different from {@code that} type.
* This is a trickier check than pure equality, because it has to properly
* handle unknown types.
*
* @see <a href="http://www.youtube.com/watch?v=_RpSv3HjpEw">Unknown
* unknowns</a>
*/
public boolean differsFrom(JSType that) {
// if there are no unknowns, just use normal equality.
if (!this.isUnknownType() && !that.isUnknownType()) {
return !this.isEquivalentTo(that);
}
// otherwise, they're different iff one is unknown and the other is not.
return this.isUnknownType() ^ that.isUnknownType();
}
/**
* A generic implementation meant to be used as a helper for common subtyping
* cases.
*/
static boolean isSubtype(JSType thisType, JSType thatType) {
// unknown
if (thatType.isUnknownType()) {
return true;
}
// equality
if (thisType.isEquivalentTo(thatType)) {
return true;
}
// all type
if (thatType.isAllType()) {
return true;
}
// unions
if (thatType instanceof UnionType) {
UnionType union = (UnionType)thatType;
for (JSType element : union.alternates) {
if (thisType.isSubtype(element)) {
return true;
}
}
}
// named types
if (thatType instanceof NamedType) {
return thisType.isSubtype(((NamedType)thatType).getReferencedType());
}
return false;
}
/**
* Visit this type with the given visitor.
* @see com.google.javascript.rhino.jstype.Visitor
* @return the value returned by the visitor
*/
public abstract <T> T visit(Visitor<T> visitor);
/**
* Force this type to resolve, even if the registry is in a lazy
* resolving mode.
* @see #resolve
*/
public final JSType forceResolve(ErrorReporter t, StaticScope<JSType> scope) {
ResolveMode oldResolveMode = registry.getResolveMode();
registry.setResolveMode(ResolveMode.IMMEDIATE);
JSType result = resolve(t, scope);
registry.setResolveMode(oldResolveMode);
return result;
}
/**
* Resolve this type in the given scope.
*
* The returned value must be equal to {@code this}, as defined by
* {@link #isEquivalentTo}. It may or may not be the same object. This method
* may modify the internal state of {@code this}, as long as it does
* so in a way that preserves Object equality.
*
* For efficiency, we should only resolve a type once per compilation job.
* For incremental compilations, one compilation job may need the
* artifacts from a previous generation, so we will eventually need
* a generational flag instead of a boolean one.
*/
public final JSType resolve(ErrorReporter t, StaticScope<JSType> scope) {
if (resolved) {
// TODO(nicksantos): Check to see if resolve() looped back on itself.
// Preconditions.checkNotNull(resolveResult);
if (resolveResult == null) {
return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
return resolveResult;
}
resolved = true;
resolveResult = resolveInternal(t, scope);
resolveResult.setResolvedTypeInternal(resolveResult);
return resolveResult;
}
/**
* @see #resolve
*/
abstract JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope);
void setResolvedTypeInternal(JSType type) {
resolveResult = type;
resolved = true;
}
/** Whether the type has been resolved. */
public final boolean isResolved() {
return resolved;
}
/** Clears the resolved field. */
public final void clearResolved() {
resolved = false;
resolveResult = null;
}
/**
* A null-safe resolve.
* @see #resolve
*/
static final JSType safeResolve(
JSType type, ErrorReporter t, StaticScope<JSType> scope) {
return type == null ? null : type.resolve(t, scope);
}
/**
* Certain types have constraints on them at resolution-time.
* For example, a type in an {@code @extends} annotation must be an
* object. Clients should inject a validator that emits a warning
* if the type does not validate, and return false.
*/
public boolean setValidator(Predicate<JSType> validator) {
return validator.apply(this);
}
public static class TypePair {
public final JSType typeA;
public final JSType typeB;
public TypePair(JSType typeA, JSType typeB) {
this.typeA = typeA;
this.typeB = typeB;
}
}
/**
* A hash code function for diagnosing complicated issues
* around type-identity.
*/
public String toDebugHashCodeString() {
return "{" + this.hashCode() + "}";
}
}
| nuxleus/closure-compiler | src/com/google/javascript/rhino/jstype/JSType.java | Java | apache-2.0 | 32,020 |
using System;
using System.Xml;
using System.Xml.Serialization;
using dk.nita.saml20.Schema.XmlDSig;
namespace dk.nita.saml20.Schema.XEnc
{
/// <summary>
/// The AgreementMethod element appears as the content of a ds:KeyInfo since, like other ds:KeyInfo children,
/// it yields a key. This ds:KeyInfo is in turn a child of an EncryptedData or EncryptedKey element. The
/// Algorithm attribute and KeySize child of the EncryptionMethod element under this EncryptedData or
/// EncryptedKey element are implicit parameters to the key agreement computation. In cases where this
/// EncryptionMethod algorithm URI is insufficient to determine the key length, a KeySize MUST have been
/// included. In addition, the sender may place a KA-Nonce element under AgreementMethod to assure that different
/// keying material is generated even for repeated agreements using the same sender and recipient public keys.
/// </summary>
[Serializable]
[XmlType(Namespace=Saml20Constants.XENC)]
[XmlRoot(ELEMENT_NAME, Namespace=Saml20Constants.XENC, IsNullable=false)]
public class AgreementMethod
{
/// <summary>
/// The XML Element name of this class
/// </summary>
public const string ELEMENT_NAME = "AgreementMethod";
private string algorithmField;
private XmlNode[] anyField;
private byte[] kANonceField;
private KeyInfo originatorKeyInfoField;
private KeyInfo recipientKeyInfoField;
/// <summary>
/// Gets or sets the KA nonce.
/// </summary>
/// <value>The KA nonce.</value>
[XmlElement("KA-Nonce", DataType="base64Binary")]
public byte[] KANonce
{
get { return kANonceField; }
set { kANonceField = value; }
}
/// <summary>
/// Gets or sets any.
/// </summary>
/// <value>Any.</value>
[XmlText]
[XmlAnyElement]
public XmlNode[] Any
{
get { return anyField; }
set { anyField = value; }
}
/// <summary>
/// Gets or sets the originator key info.
/// </summary>
/// <value>The originator key info.</value>
public KeyInfo OriginatorKeyInfo
{
get { return originatorKeyInfoField; }
set { originatorKeyInfoField = value; }
}
/// <summary>
/// Gets or sets the recipient key info.
/// </summary>
/// <value>The recipient key info.</value>
public KeyInfo RecipientKeyInfo
{
get { return recipientKeyInfoField; }
set { recipientKeyInfoField = value; }
}
/// <summary>
/// Gets or sets the algorithm.
/// </summary>
/// <value>The algorithm.</value>
[XmlAttribute(DataType="anyURI")]
public string Algorithm
{
get { return algorithmField; }
set { algorithmField = value; }
}
}
} | symplified/Symplified.Auth | lib/OIOSAML.NET/Schema/XEnc/AgreementMethod.cs | C# | apache-2.0 | 3,134 |
package com.foo;
@DemoRepository
public class TestRepository {
public String testMethod() {
return "hello world";
}
}
| jadekler/git-misc-2 | java-annotations-testing/src/test/java/com/foo/TestRepository.java | Java | apache-2.0 | 135 |
Import-Module -Name $CI_MODULE_MANIFEST_PATH -Force
$systemUnderTest = ( Split-Path -Leaf $MyInvocation.MyCommand.Path ) -replace '\.Tests\.', '.'
$function = $systemUnderTest.Split( '.' )[0]
$describe = $Global:FORM_FUNCTION_PUBLIC -f $function
Describe -Name $describe -Tag 'Function', 'Public', $function -Fixture {
#region init
$help = Get-Help -Name $function -Full
$Global:ArmorSession = [ArmorSession]::New()
$Global:ArmorSession.Accounts += [ArmorAccount] @{
ID = 1
Name = 'Armor Defense, Inc.'
Currency = 'USD'
Status = 'Claimed'
Parent = -1
Products = @()
}
$Global:ArmorSession.Accounts += [ArmorAccount] @{
ID = 2
Name = 'Old Armor QA Account, Ltd'
Currency = 'GBP'
Status = 'Cancelled'
Parent = 1
Products = @()
}
#endregion
$splat = @{
ExpectedFunctionName = $function
FoundFunctionName = $help.Name
}
Test-AdvancedFunctionName @splat
Test-AdvancedFunctionHelpMain -Help $help
Test-AdvancedFunctionHelpInput -Help $help
$splat = @{
ExpectedOutputTypeNames = 'ArmorAccount'
Help = $help
}
Test-AdvancedFunctionHelpOutput @splat
$splat = @{
ExpectedParameterNames = @()
Help = $help
}
Test-AdvancedFunctionHelpParameter @splat
$splat = @{
ExpectedNotes = $Global:FORM_FUNCTION_HELP_NOTES
Help = $help
}
Test-AdvancedFunctionHelpNote @splat
Context -Name $Global:EXECUTION -Fixture {
#region init
$invalidID = 0
#endregion
$testCases = @(
@{ ID = $invalidID }
)
$testName = 'should fail when set to: ID: <ID>'
It -Name $testName -TestCases $testCases -Test {
param ( [String] $ID )
{ Get-ArmorAccountContext -ID $ID } |
Should -Throw
}
$testCases = @(
@{ ID = $Global:ArmorSession.Accounts[0].ID },
@{ ID = $Global:ArmorSession.Accounts[1].ID }
)
$testName = 'should not fail when set to: ID: <ID>'
It -Name $testName -TestCases $testCases -Test {
param ( [String] $ID )
$Global:ArmorSession.SetAccountContext( $ID )
( Get-ArmorAccountContext ).ID |
Should -Be $ID
}
}
Context -Name $Global:RETURN_TYPE_CONTEXT -Fixture {
$testCases = @(
@{
FoundReturnType = ( Get-ArmorAccountContext -ErrorAction 'Stop' ).GetType().FullName
ExpectedReturnType = 'ArmorAccount'
}
)
$testName = $Global:FORM_RETURN_TYPE
It -Name $testName -TestCases $testCases -Test {
param ( [String] $FoundReturnType, [String] $ExpectedReturnType )
$FoundReturnType |
Should -Be $ExpectedReturnType
}
$testName = "has an 'OutputType' entry for <FoundReturnType>"
It -Name $testName -TestCases $testCases -Test {
param ( [String] $FoundReturnType, [String] $ExpectedReturnType )
$FoundReturnType |
Should -BeIn ( Get-Help -Name 'Get-ArmorAccountContext' -Full ).ReturnValues.ReturnValue.Type.Name
}
}
}
| tlindsay42/ArmorPowerShell | tests/public/Get-ArmorAccountContext.Tests.ps1 | PowerShell | apache-2.0 | 3,372 |
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.myboss.cn.common.persistence.dialect.db;
import com.myboss.cn.common.persistence.dialect.Dialect;
/**
* DB2的分页数据库方言实现
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class DB2Dialect implements Dialect {
@Override
public boolean supportsLimit() {
return true;
}
private static String getRowNumber(String sql) {
StringBuilder rownumber = new StringBuilder(50)
.append("rownumber() over(");
int orderByIndex = sql.toLowerCase().indexOf("order by");
if (orderByIndex > 0 && !hasDistinct(sql)) {
rownumber.append(sql.substring(orderByIndex));
}
rownumber.append(") as rownumber_,");
return rownumber.toString();
}
private static boolean hasDistinct(String sql) {
return sql.toLowerCase().contains("select distinct");
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
int startOfSelect = sql.toLowerCase().indexOf("select");
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100)
.append(sql.substring(0, startOfSelect)) //add the comment
.append("select * from ( select ") //nest the main query in an outer select
.append(getRowNumber(sql)); //add the rownnumber bit into the outer query select list
if (hasDistinct(sql)) {
pagingSelect.append(" row_.* from ( ") //add another (inner) nested select
.append(sql.substring(startOfSelect)) //add the main query
.append(" ) as row_"); //close off the inner nested select
} else {
pagingSelect.append(sql.substring(startOfSelect + 6)); //add the main query
}
pagingSelect.append(" ) as temp_ where rownumber_ ");
//add the restriction to the outer select
if (offset > 0) {
// int end = offset + limit;
String endString = offsetPlaceholder + "+" + limitPlaceholder;
pagingSelect.append("between ").append(offsetPlaceholder)
.append("+1 and ").append(endString);
} else {
pagingSelect.append("<= ").append(limitPlaceholder);
}
return pagingSelect.toString();
}
}
| ChDiego/myboss | src/main/java/com/myboss/cn/common/persistence/dialect/db/DB2Dialect.java | Java | apache-2.0 | 3,237 |
// Copyright © 2011 - Present RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace chocolatey.infrastructure.app.runners
{
using System;
using System.Linq;
using SimpleInjector;
using adapters;
using attributes;
using configuration;
using infrastructure.commands;
using logging;
using Console = System.Console;
using Environment = System.Environment;
public sealed class GenericRunner
{
public void run(ChocolateyConfiguration config, Container container, bool isConsole, Action<ICommand> parseArgs)
{
var commands = container.GetAllInstances<ICommand>();
var command = commands.Where((c) =>
{
var attributes = c.GetType().GetCustomAttributes(typeof (CommandForAttribute), false);
return attributes.Cast<CommandForAttribute>().Any(attribute => attribute.CommandName.is_equal_to(config.CommandName));
}).FirstOrDefault();
if (command == null)
{
//todo add a search among other location/extensions for the command
if (!string.IsNullOrWhiteSpace(config.CommandName))
{
throw new Exception("Could not find a command registered that meets '{0}'".format_with(config.CommandName));
}
if (isConsole) Environment.ExitCode = 1;
}
else
{
if (parseArgs != null)
{
parseArgs.Invoke(command);
}
this.Log().Debug(() => "Configuration: {0}".format_with(config.ToString()));
if (isConsole && config.HelpRequested)
{
#if DEBUG
Console.WriteLine("Press enter to continue...");
Console.ReadKey();
#endif
Environment.Exit(1);
}
var token = Assembly.GetExecutingAssembly().get_public_key_token();
if (string.IsNullOrWhiteSpace(token) || token != ApplicationParameters.OfficialChocolateyPublicKey)
{
if (!config.AllowUnofficialBuild)
{
throw new Exception(@"
Custom unofficial builds are not allowed by default.
To override this behavior, explicitly set --allow-unofficial.
See the help menu (choco -h) for options.");
}
else
{
this.Log().Warn(ChocolateyLoggers.Important, @"
choco.exe is not an official build (bypassed with --allow-unofficial).
If you are seeing this message and it is not expected, your system may
now be in a bad state. Only official builds are to be trusted.
"
);
}
}
if (config.Noop)
{
if (config.RegularOuptut)
{
this.Log().Info("_ {0}:{1} - Noop Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
}
command.noop(config);
}
else
{
this.Log().Debug("_ {0}:{1} - Normal Run Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
command.run(config);
}
}
}
}
} | mwrock/choco | src/chocolatey/infrastructure.app/runners/GenericRunner.cs | C# | apache-2.0 | 4,108 |
package com.thinkgem.jeesite.modules.edu.entity;
import com.thinkgem.jeesite.common.persistence.IdEntity;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Created by abcd on 15/3/24.
*/
@Entity
@Table(name = "edu_question_category")
@DynamicInsert
@DynamicUpdate
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class QuestionCategory extends IdEntity<QuestionCategory> {
private String name;
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mawanjin/edu | src/main/java/com/thinkgem/jeesite/modules/edu/entity/QuestionCategory.java | Java | apache-2.0 | 851 |
# LZBScrollViewFoucs-Three-ImageView
三个imageView实现轮播图
#使用方法
1.导入我的头文件#import "LZBInifiteScrollView.h"
2.最好采用懒加载控件LZBInifiteScrollView(在这里是个人习惯,但是这里有个注意点:我们都知道控件的属性保存@property一般是用weak修饰,因为在addSubview的时候就已经有strong强引用这个控件了,但是懒加载的时候一定要用strong,原因:创建控件后(alloc或者new),都会使引用计数器加1,默认是强指针指向他,假如用weak修饰,返回的是_(下划线)+属性是弱引用,会自动销毁,可能返回nil,懒加载控件不成功)
3.设置轮播图的滚动图片数组支持(里面可以存放UIImage对象、NSString对象【本地图片名】、NSURL对象【远程图片的URL】注意:设置SDWebImage加载图片的时候注意设置info.plist里面,支持网络https请求App Transport Security Settings)
#下面是功能参数介绍
placeholder : 可选设置,可以设置占位图片,默认是我LZBInifiteScrollView.bundle/placeHoder
images: 必选设置,图片数据(里面可以存放UIImage对象、NSString对象【本地图片名】、NSURL对象【远程图片的URL】)
interValTime:可选设置,定时器时间设置,默认是2s
foucsDelegate:可选设置,实现滚动图片的点击
指示器操作
pageControlPosition:可选设置,指示器的为位置,默认底部中心/* LZBFocusScrollViewPageControllPosition_None, //默认底部中心
LZBFocusScrollViewPageControllPosition_Hidden, //隐藏
LZBFocusScrollViewPageControllPosition_BottomCenter, //底部中心*/
/**
* 自定义设置分页指示器的图片
*
* @param currentImage 选择图片
* @param otherImage 其他图片
*/
- (void)setPageControlCurrentImage:(UIImage *)currentImage OtherImage:(UIImage *)otherImage;
/**
* 自定义设置分页指示器的颜色
*
* @param currentColor 选中得颜色
* @param otherColor 其他颜色
*/
#实现原理
核心思想:从当前的imageView滚动到下一个imageView,然后把下一个imageView滚动到三个imageView的中心位置,在这过程中赋值的时候是三个imageView同时赋值,滚动的时候找到距离滚动最近的一个imageView currentDelta = ABS(imageView.frame.origin.x - self.scrollView.contentOffset.x);
把这个imageView的索引设置为当前的索引,滚动完成后把这个imageView设置为中心滚动位置。
| lzbgithubcode/LZBScrollViewFoucs-Three-ImageView | README.md | Markdown | apache-2.0 | 2,495 |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import com.google.common.collect.ImmutableCollection;
import com.google.devtools.build.lib.actions.Artifact.SourceArtifact;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skyframe.BuildConfigurationValue;
import javax.annotation.Nullable;
import net.starlark.java.eval.ClassObject;
/**
* A {@link ConfiguredTarget} is conceptually a {@link TransitiveInfoCollection} coupled with the
* {@link com.google.devtools.build.lib.packages.Target} and {@link
* com.google.devtools.build.lib.analysis.config.BuildConfiguration} objects it was created from.
*
* <p>This interface is supposed to only be used in {@link BuildView} and above. In particular, rule
* implementations should not be able to access the {@link ConfiguredTarget} objects associated with
* their direct dependencies, only the corresponding {@link TransitiveInfoCollection}s. Also, {@link
* ConfiguredTarget} objects should not be accessible from the action graph.
*/
public interface ConfiguredTarget extends TransitiveInfoCollection, ClassObject {
/** All <code>ConfiguredTarget</code>s have a "label" field. */
String LABEL_FIELD = "label";
/** All <code>ConfiguredTarget</code>s have a "files" field. */
String FILES_FIELD = "files";
default String getConfigurationChecksum() {
return getConfigurationKey() == null
? null
: getConfigurationKey().getOptionsDiff().getChecksum();
}
/**
* Returns the {@link BuildConfigurationValue.Key} naming the {@link
* com.google.devtools.build.lib.analysis.config.BuildConfiguration} for which this configured
* target is defined. Configuration is defined for all configured targets with exception of {@link
* com.google.devtools.build.lib.analysis.configuredtargets.InputFileConfiguredTarget} and {@link
* com.google.devtools.build.lib.analysis.configuredtargets.PackageGroupConfiguredTarget} for
* which it is always <b>null</b>.
*/
@Nullable
BuildConfigurationValue.Key getConfigurationKey();
/** Returns keys for a legacy Starlark provider. */
@Override
ImmutableCollection<String> getFieldNames();
/**
* Returns a legacy Starlark provider.
*
* <p>Overrides {@link ClassObject#getValue(String)}, but does not allow EvalException to be
* thrown.
*/
@Nullable
@Override
Object getValue(String name);
/** Returns a source artifact if this is an input file. */
@Nullable
default SourceArtifact getSourceArtifact() {
return null;
}
/**
* If the configured target is an alias, return the actual target, otherwise return the current
* target. This follows alias chains.
*/
default ConfiguredTarget getActual() {
return this;
}
/**
* If the configured target is an alias, return the original label, otherwise return the current
* label. This is not the same as {@code getActual().getLabel()}, because it does not follow alias
* chains.
*/
default Label getOriginalLabel() {
return getLabel();
}
}
| davidzchen/bazel | src/main/java/com/google/devtools/build/lib/analysis/ConfiguredTarget.java | Java | apache-2.0 | 3,660 |
# AUTOGENERATED FILE
FROM balenalib/coral-dev-debian:buster-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.6.15
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" \
&& echo "6030ab4b6b2279ac25451fb4bde00f6090bf0bf2a66c82002bf5bd3dc21a67b2 Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | resin-io-library/base-images | balena-base-images/python/coral-dev/debian/buster/3.6.15/run/Dockerfile | Dockerfile | apache-2.0 | 4,090 |
/*
* 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.river.outrigger;
/**
* This interface defines the methods that any OutriggerServerImpl store must
* implement.
*
* @author Sun Microsystems, Inc.
*
* @see OutriggerServerImpl
* @see LogOps
* @see Recover
*/
public interface Store {
/**
* Set up the store. Recovery (if any) will be completed
* before this method returns. That is, no calls will be made by
* <code>setupStore</code> on the <code>Recover</code> object
* after it returns.
*
* @param space object used for recovery of previous state (if any)
*
* @return object used to persist state
*/
public LogOps setupStore(Recover space);
/**
* Destroy any persistent state and release
* any resources associated with this store.
* @throws java.io.IOException if an IO related exception occurs.
*/
public void destroy() throws java.io.IOException;
/**
* Close the store, release VM resources (stop independent
* threads, close files, etc.) but do not destroy any persistent
* state. This method is used when there is a failure
* in <code>OutriggerServerImpl</code> constructor.
* @throws java.io.IOException if an IO related exception occurs.
*/
public void close() throws java.io.IOException;
}
| pfirmstone/river-internet | JGDMS/services/outrigger/outrigger-service/src/main/java/org/apache/river/outrigger/Store.java | Java | apache-2.0 | 2,165 |
(function() {
'use strict';
angular
.module('cribbleApp')
.factory('JhiMetricsService', JhiMetricsService);
JhiMetricsService.$inject = ['$rootScope', '$http'];
function JhiMetricsService ($rootScope, $http) {
var service = {
getMetrics: getMetrics,
threadDump: threadDump
};
return service;
function getMetrics () {
return $http.get('management/metrics').then(function (response) {
return response.data;
});
}
function threadDump () {
return $http.get('management/dump').then(function (response) {
return response.data;
});
}
}
})();
| fjuriolli/scribble | src/main/webapp/app/admin/metrics/metrics.service.js | JavaScript | apache-2.0 | 737 |
# AUTOGENERATED FILE
FROM balenalib/etcher-pro-ubuntu:bionic-run
ENV NODE_VERSION 14.16.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "2b78771550f8a3e6e990d8e60e9ade82c7a9e2738b6222e92198bcd5ea857ea6 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/node/etcher-pro/ubuntu/bionic/14.16.0/run/Dockerfile | Dockerfile | apache-2.0 | 2,914 |
/*
Theme Name: farjun
Theme URI: http://dinkk.com
Author: thedinh.trinh@gmail.com
Author URI: http://dinhkk.com/
Description: In 2014, our default theme lets you create a responsive magazine website with a sleek, modern design. Feature your favorite homepage content in either a grid or a slider. Use the three widget areas to customize your website, and change your content's layout with a full-width page template and a contributor page to show off your authors. Creating a magazine website with WordPress has never been easier.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: black, green, white, light, dark, two-columns, three-columns, left-sidebar, right-sidebar, fixed-layout, responsive-layout, custom-background, custom-header, custom-menu, editor-style, featured-images, flexible-header, full-width-template, microformats, post-formats, rtl-language-support, sticky-post, theme-options, translation-ready, accessibility-ready
Text Domain: farjun
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/
/**
* -------------------------------------------------------------------------------
*/
/**--------------------------------------------------------------------------------
*Global
*/
body{
background: transparent;
font-family:arial;
}
.full-width{
clear:both;
display:table;
width:100%;
}
.left{float:left;}
.right{float:right;}
.home_arrow .circle_arrow{
float:right;
}
#menu-footer #menu-item-62{
background:none;
}
/**--------------------------------------------------------------------------------
*HEADER
*/
#header{
width:100%;
background:url(./images/bg_header_menus.jpg) center bottom;
margin:0 auto;
height:53px;
}
#header .header_menu_content{
margin:0 auto;
height:53px;
background:url("./images/bg_top_nav_menu.jpg") repeat-x scroll center top rgba(0, 0, 0, 0);
}
#top_top_header{
width:100%;
min-height:150px;
margin:0 auto;
background: url('./images/bg_top_top_header_content.jpg') scroll top center no-repeat transparent ;
overflow:hidden;
}
#top_top_header .top_top_header_content{
margin:0 auto;
width:100%;
height:74px;
}
.top_search{
height:auto;
float: right;
}
.top_logo{
float:left;
}
#searchform{
background:url('./images/bg_search.png') scroll top left no-repeat transparent ;
margin-top:23px;
height:33px;
width:210px;
}
#searchform label{
margin-top:5px;
}
#searchform .search-field{
border:none;
background:none;
margin-left:15px;
font-weight:normal;
}
#searchform input[type="image"]{
float: right;
margin-right: 10px;
margin-top: 10px;
}
/****top top menu****/
.top_top_header_content .top_logo img{
margin-top: 13px;
}
#top_top_header_menus{
width:100%;
}
#top_top_header_menus #menu-top_top_menus{
text-align:center;
width:100%;
padding:0;
}
#top_top_header_menus .navbar-nav .menu-item{
display: inline-block;
float:none;
text-align:left;
}
#top_top_header_menus .navbar{
background:none;
}
#top_top_header_menus .navbar .navbar-nav > li > a{
color:#fff;
background:url("./images/top_top_nav_space.png") no-repeat scroll left center rgba(0, 0, 0, 0);
padding-top:40px;
text-transform: uppercase;
}
#top_top_header_menus .navbar .menu-affixing{
background:url("./images/menu-affixing.png") no-repeat scroll center -7px rgba(0, 0, 0, 0);
}
#top_top_header_menus .navbar .menu-formica{
background:url("./images/menu-formica.png") no-repeat scroll center -3px rgba(0, 0, 0, 0);
}
#top_top_header_menus .navbar .menu-affixing a{
padding-left: 26px;
text-transform: uppercase;
background: none !important;
}
#top_top_header_menus .navbar .menu-woodproducts{
background:url("./images/menu-woodproducts.png") no-repeat scroll center -3px rgba(0, 0, 0, 0);
}
#top_top_header_menus .navbar .menu-woodproducts a{
padding-left: 26px;
}
#top_top_header_menus .navbar .menu-homedesign{
background:url("./images/menu-homedesign.png") no-repeat scroll center -3px rgba(0, 0, 0, 0);
}
#top_top_header_menus .navbar .menu-homedesign a{
padding-left: 26px;
}
#top_top_header_menus .navbar .menu-tools{
background:url("./images/menu-tools.png") no-repeat scroll center -3px rgba(0, 0, 0, 0);
}
#top_top_header_menus .navbar{
border:none;
margin-bottom:0;
}
/****hadermenu***/
.header_menu_content .navbar{
background:none;
border:none;
box-shadow: none;
margin-bottom:0;
}
.header_menu_content .navbar .menu-item a{
text-transform:uppercase;
color:#fff;
font-family:times new roman;
}
.header_menu_content .navbar .menu-item{
float:left;
}
.header_menu_content .navbar .menu-item a:hover{
background:url(./images/bg_hover_header_menu.png) repeat-x center bottom transparent;
box-shadow: none;
color: #fff;
}
#menu-header,#header {
z-index: 9999;
}
.header_menu_content .social_links{
height:43px;
width:18%;
}
.header_menu_content .social_links{
margin-top: 10px;
margin-right:5px;
margin-left:5px;
}
.menu-header-container{
float:left;
}
#menu-header > li > a:hover,#menu-header > li > a.active{
background-image:url('./images/bg_main_nav_active.png');
background-position: center bottom;
background-repeat:repeat-x;
}
.menu-header-container{
height:53px;
display:table;
}
#menu-header{
display:table-cell;
vertical-align:bottom;
margin-top:3px;
padding:0;
}
#menu-header > li > a{
color:#fff;
text-shadow:none;
text-transform:uppercase;
font-family:arial;
font-size:12px;
}
#menu-header .open > a,
#menu-header .open > a:hover,
#menu-header .open > a:focus{
background-image:url('./images/bg_main_nav_active.png');
background-position: center bottom;
background-repeat:repeat-x;
}
#menu-header .dropdown-menu > li > a:hover,
#menu-header .dropdown-menu > li > a:focus{
background:#F07901;
}
#menu-header li.open > ul.dropdown-menu{
display:block !important;
z-index:20;
padding:0;
right:0;
left:auto;
background:url(./images/bg_sub_menu_container.png) center bottom repeat-y;
width:183px;
}
#menu-header li.open > ul.dropdown-menu > li{
margin-right:10px;
width:165px;
background:url(./images/bg_sub_menu_item.png) 0 30px no-repeat;
height:38px;
padding-bottom:10px;
}
#menu-header li.open > ul.dropdown-menu > li#menu-item-291{
background:none;
}
#menu-header li.open > ul.dropdown-menu > li > a{
color:#fff;
text-transform:uppercase;
padding:5px 20px;
}
/**
*Nav menu
*/
/*******-----------------------------------------------------------------------------
*Content
*/
.content{
margin:0 auto;
clear:both;
overflow:hidden;
}
.header_menu_content .content{
overflow:visible;
}
#content{
width:100%;
margin-left:auto;
margin-right:auto;
margin-top:0;
margin-bottom:20px;
background: url('./images/bg_content_head_content.jpg') scroll top center repeat-x transparent ;
background-size:100% auto ;
z-index: 1;
}
#content .row.home_content .home_video img{
width:100%;
height:auto;
}
#content .row.home_content .home_video{
padding:0;
margin:0;
}
#content .row.home_content .home_video iframe{
padding:0;
margin:0;
}
.home_content h2.website_name{
color:#E36F00;
font-family:times new roman;
}
.home_content .home_video_container{
box-shadow: 0 7px 11px #888888;
height:260px;
width: 500px;
background: #221D1B;
}
.home_content .col-sm-6{
margin-bottom:20px;
}
#middle-content-home{
margin:0 auto;
clear:both;
margin-bottom:50px;
}
#content .home_content{
margin-left:0;
margin-right:0;
}
#content .container{
padding:0;
margin: 0 auto;
z-index: 1;
}
#content .head_content{
}
#home_banner img{
margin:0 auto;
width:100%;
height:auto;
z-index: 1;
}
#home_banner{
width:100%;
margin:0 auto;
}
#home_banner{
position:relative;
z-index: 1;
}
#home_banner .page_banner{
background: none repeat scroll 0 0 #FFFFFF;
bottom: 0;
height: 117px;
opacity: 0.8;
position: absolute;
width: 100%;
}
.middle_content_space{
clear:both;
margin:0 auto;
width:100%;
}
.middle_content_space img{
width:100%;
margin:0 auto;
}
.page_title .page-title{
font-size:30px;
border-bottom:3px solid #80C9C2;
text-align:center;
}
.display_table{
display:table;
height:100%;
}
#content .display_table .row.container{
display:table-cell;
vertical-align: middle;
clear:both;
margin: 10px 0;
}
.circle_arrow{
width: 58px;
height:58px;
}
.circle_arrow img{
width:100%;
height:auto;
}
#content .middle_content_breadcrum{
width:100%;
clear:both;
margin-top:20px;
margin-bottom:20px;
}
#content .middle_content_breadcrum .left_side{
background: url('./images/breadcrum_left_en.png') scroll top right no-repeat transparent ;
}
#content .middle_content_breadcrum .right_side{
background: url('./images/breadcrum_right_en.png') scroll top left no-repeat transparent ;
position: relative;
}
#content .middle_content_breadcrum .right_side #go_back{
position: absolute;
right:0;
bottom:32%;
background:url("./images/icon_product_arrow_en.png") no-repeat scroll 75px top rgba(0, 0, 0, 0);
padding-right:30px;
}
#content .middle_content_breadcrum .right_side #go_back a{
padding-left:20px;
color:#888;
}
.breadcrumbs{
height: 46px;
line-height: 46px;
padding-left: 19px;
}
.breadcrumbs a,.breadcrumbs span{
color: #888888;
float: left;
padding:0 5px;
}
/**----------------------------------------------------------------------------------
*Footer
*/
#footer{
width:100%;
margin:0 auto;
overflow:hidden;
}
#menu_footer{
background: url('./images/bg_footer_bottom.jpg') scroll top center repeat-x transparent ;
height:89px;
}
#menu-footer{
text-align:center;
}
#menu-footer .menu-item{
display: inline;
float: none;
list-style: disc outside none;
background:url("./images/footer_menu_space.jpg") no-repeat scroll left 8px rgba(0, 0, 0, 0);
padding-left: 20px;
padding-right: 14px;
}
#menu-footer #menu-item-16{
background:none;
}
#menu-footer .menu-item a{
color:#fff;
}
.menu-footer-container{
clear:both;
margin:15px 0 auto;
width:100%;
display:table;
}
.footer-copyright{
width:300px;
text-align:center;
color:#fff;
clear:both;
margin:0 auto;
}
#footer .partners {
border-top:1px solid #ccc;
padding-top:20px;
}
/**
****CATEGORY PAGE
**/
.tax-product_cat #content,
.single-product #content,
.page #content,
.single #content,
.search-results #content,
.post-type-archive #content{
background: url('./images/cat_content_bg.jpg') scroll top center no-repeat transparent ;
}
.tax-product_cat .display_table .page-title.category,
.single-product .display_table .page-title.product,
.page .display_table .page-title.single_page,
.single .display_table .page-title.single_page,
.search-results .display_table .page-title.single_page{
margin:11px 0 11px 10px;
text-transform:uppercase;
font-weight:500;
line-height:1.5;
border:none;
text-align:left;
}
.tax-product_cat .display_table .page-title.category span,
.single-product .display_table .page-title.product span,
.page .display_table .page-title.single_page span,
.single .display_table .page-title.single_page span,
.search-results .display_table .page-title.single_page span,
.post-type-archive .display_table .page-title.single_page span{
border-bottom: 3px solid #7CC3BD;
}
.tax-product_cat #home_banner .page_title,
.single-product #home_banner .page_title,
.page #home_banner .page_title,
.single #home_banner .page_title,
.search-results #home_banner .page_title,
.post-type-archive #home_banner .page_title{
height:67px;
overflow: hidden;
}
.tax-product_cat #home_banner .page_title .title-outter,
.single-product #home_banner .page_title .title-outter,
.page #home_banner .page_title .title-outter,
.single #home_banner .page_title .title-outter,
.search-results #home_banner .page_title .title-outter{
margin:0;
padding:0
}
.category_content,
.product_content,
.page_content{
width:100%;
clear:both;
}
.category_description{
width:100%;
clear:both;
}
.category_description h2{
margin-top: 0;
}
.tax-product_cat .product_listing{
padding-left:0;
padding-right:0;
margin-left: 0;
margin-right: 0;
}
.tax-product_cat .product_listing .product_item{
margin-bottom:10px;
float:left;
padding:0 10px;
}
.tax-product_cat .product_listing .product_item img{
width:100%;
}
.tax-product_cat .product_listing .product_item p{
border-bottom:2px solid #80C9C2;
padding-bottom:5px;
min-height:50px;
}
.tax-product_cat .product_listing .product_item a{
color:#6F6F6F;
width:100%;
height:100%;
}
.tax-product_cat .product_listing .product_item.first-item{
padding-left:0;
padding-right:10px;
}
.tax-product_cat .product_listing .product_item.last-item{
padding-right:0;
padding-left:10px;
}
/**sidebar menus**/
.sidebar.left{
padding-left:0;
}
#menu-left_categories{
border:7px solid #E5E5E3;
border-radius: 5px;
padding:0;
background:#F1F1F1;
}
#menu-left_categories li{
list-style:none;
}
#menu-left_categories .dcjq-parent-li{
list-style:none;
width:100%;
}
#menu-left_categories .menu-item .sub-menu,
#menu-left_categories .cat-item .children{
padding-left:5px;
}
#menu-left_categories .menu-item .dcjq-parent,
#menu-left_categories .cat-item .dcjq-parent{
width:100%;
height:40px;
background:url('./images/left_menu_inactive.jpg')no-repeat scroll left 13px #F58B0C;
display:block;
line-height:40px;
color:#fff;
padding-left:20px;
font-weight:500;
border-bottom:1px solid;
text-transform: uppercase;
}
#menu-left_categories .menu-item a,
#menu-left_categories .cat-item a,
#primary-sidebar .latest_posts li a{
color:#4F4F4F;
}
#menu-left_categories .menu-item .dcjq-parent.active,
#menu-left_categories .cat-item .dcjq-parent.active{
background:#F4810E;
background:url('./images/left_menu_active.jpg')no-repeat scroll left 14px #F58B0C;
}
#menu-left_categories .menu-item .sub-menu,
#menu-left_categories .cat-item .sub-menu{
padding-right:0px;
padding-left:20px;
}
#menu-left_categories .menu-item .sub-menu li,
#menu-left_categories .cat-item .sub-menu li{
list-style:none;
}
#menu-left_categories .menu-item .sub-menu li a,
#menu-left_categories .cat-item .children li a,
#primary-sidebar .latest_posts li a{
display:block;
width:100%;
padding:5px 0px 5px 13px;
background:url("./images/bg_arrow_sidebar_menu_en.jpg") no-repeat scroll left 10px rgba(0, 0, 0, 0);
}
#menu-left_categories .menu-item .sub-menu li:hover,
#menu-left_categories .cat-item .children li:hover{
}
#menu-left_categories .menu-item .sub-menu li a:hover,
#menu-left_categories .menu-item .sub-menu li a.active,
#menu-left_categories .cat-item .children li a:hover,
#menu-left_categories .cat-item .children li a.active,
#primary-sidebar .latest_posts li a:hover,
#primary-sidebar .latest_posts li a.active{
background:#282828;
color:#fff;
border-radius:3px;
border-color:#105D59 ;
border-width: 2px;
background-image:url("./images/bg_arrow_sidebar_menu_active_en.jpg");
background-repeat:no-repeat;
background-position:left 10px;
font-weight:bold;
}
/****
****PRODUCT DETAILS
****/
.single-product .product-title{
font-weight:500;
text-transform: uppercase;
font-family:times new roman;
}
.single-product .product-info-title{
text-transform: uppercase;
}
.single-product .product_thumbnail img{
width:auto;
max-height:600px;
max-width:100%;
}
.product_thumbnail{
display:inline;
}
.catelog_download{
display:table;
margin-bottom: 10px!important;
}
.catelog_download img{
max-width:100%;
}
.catelog_download .catelog_download_botton{
position:relative;
display:table-cell;
vertical-align:bottom;
}
.catelog_download .catelog_download_botton a{
display:inline;
}
.product-catalog-title{
width:100%;
clear:both;
}
.product-catalog-title p,.product-catalog-title h4{
width:100%;
clear:both;
}
.product-details .row{
width:100%;
clear:both;
margin:0;
}
.product-details .product_thumbnail{
text-align:center;
display:block;
}
.product_big_thumb{
padding-left:0px;
padding-right:15px;
}
.product-info-top{
background:#F7F7F9;
}
.product-info-top .product-info-detail-text h4{
}
.product-info-bottom{
background:#EEEDF3;
}
.product-info-detail-text p,
.product-info-outter h4.product-info-title,
.product-catalog-title p{
padding:5px 10px;
}
.single-product #home_banner{
min-height:182px;
}
.single-product #product_thumb{
float:right;
}
#small_thumb_list ul,
#small_thumb_list li{
list-style: none;
}
#small_thumb_list li{
float:right;
}
.single-product .related_products h4{
background: url("./images/related_posts_dot_bg.jpg") repeat-x scroll 0 bottom rgba(0, 0, 0, 0);
font-family: times new roman;
font-size: 25px;
padding-bottom:4px;
}
.single-product .related_products h4 span{
border-bottom: 3px solid #F4810E;
}
.single-product .related_products{
margin-top:20px;
}
.single-product .related_products .title-container{
width:100%;
clear:both;
margin:0;
}
.single-product .product-info-outter{
padding-right:0;
}
.product-info-bottom .catelog_download{
padding-top:10px;
}
.product_listing .products{
margin:0;
padding:0;
}
/***
****SINGLE PAGE
***/
.page .sidebar,
.single .sidebar{
margin:0;
padding: 0 15px 0 0;
}
.page .sidebar aside,
.single .sidebar aside{
text-align: left;
}
.page .sidebar aside .menu,
.single .sidebar aside .menu{
margin:0;
}
.page .page_content_outer,
.single .page_content_outer,
.search-results .page_content_outer{
padding:0;
margin:0;
}
.page .page_content_outer .page_content,
.single .page_content_outer .page_content,
.search-results .page_content_outer .page_content{
padding:0;
margin:0;
}
.page .page_content_outer .page_content article,
.single .page_content_outer .page_content article,
.search-results .page_content_outer .page_content article{
padding:0;
margin:0;
}
.page .page_content_outer .page_content .entry-content,
.single .page_content_outer .page_content .entry-content,
.search-results .page_content_outer .page_content .entry-content{
padding:10px 10px 10px 20px;
margin:0;
}
.page .page_content_outer .page_content .entry-content blockquote,
.single .page_content_outer .page_content .entry-content blockquote{
border-right: 5px solid #63CCC8;
border-left: none;
}
.page .post-content-single,
.search-results .post-content-single{
border-bottom: 1px solid #DEDEDC;
margin: 40px 0 5px;
padding: 0 0 40px;
width: 100%;
}
.page .post-header,
.page .post-content,
.search-results .post-content,
.single .post-header,.post-header .post-content{
margin:0;
}
.page .post-header,
.search-results .post-header,
.single .post-header{
margin-bottom: 10px;
}
.page .post-content-single .post-header .post-title,
.search-results .post-content-single .post-header .post-title,
.single .page_content .post-header .post-title{
display: table;
padding-left:0;
}
.page .post-content-single .post-header .post-title h4,
.search-results .post-content-single .post-header .post-title h4,
.single .page_content .post-header .post-title h4{
font-size: 25px;
padding-left:0;
}
.page .post-content-single .post-header .post-title h4 a,
.search-results .post-content-single .post-header .post-title h4 a,
.single .page_content .post-header .post-title h4 a{
color:#525252;
}
.page .post-content-single .post-header .month_year,
.search-results .post-content-single .post-header .month_year,
.single .page_content .post-header .month_year{
font-family: times new roman;
font-size: 17px;
color:#838383;
display: table-row;
}
.page .post-content-single .post-header .date,
.search-results .post-content-single .post-header .date,
.single .page_content .post-header .date{
font-family: times new roman;
font-size: 35px;
color:#838383;
display: table-row;
}
.page .post-content-single .post-header .date_of_post,
.search-results .post-content-single .post-header .date_of_post,
.single .page_content .post-header .date_of_post{
border-right: 2px solid #838383;
line-height: 20px;
display: table;
width:14%;
padding-right: 0;
}
.post-content-single .post-content .post-exceprt{
display: table;
color:#A1A1A1;
margin-top:15px;
}
.page .post-content-single .post-exceprt p.read_more,
.search-results .post-content-single .post-exceprt p.read_more{
margin:0;
display: table-row;
}
.page .post-content-single.first_post,
.search-results .post-content-single.first_post{
margin-top: 0px;
}
.page .post-content-single.last_post,
.search-results .post-content-single.last_post{
border-bottom: none;
}
.post-content-single .post-content{
padding-right:0;
}
.post-content-single .post-thumbnail{
padding-right:0;
margin-right:0;
}
.post-content-single .post-thumbnail img{
width:100%;
}
.post-content-single .post-exceprt{
padding-right:0;
margin-right:0;
}
.post-content-single .exceprt_inner{
padding:0;
margin-right:0;
margin-left: 0;
}
.post-content-single .post-exceprt p{
width:100%;
overflow: hidden;
}
.post-meta{
background: none repeat scroll 0 0 #F8F8F8;
margin: 0;
padding: 5px 0;
width: 98%;
color: #C6C6C6;
font-style: italic;
}
.post-meta .author{
margin-left:10px;
}
.post-meta a{
color:#BBBABB;
}
.post-meta .left{
padding-left:0;
}
.post-content-single .post-content{
padding-left:15px;
margin-left:0px;
}
.languages{
margin-top:29px;
}
.languages .flag{
margin:0 5px;
}
.page-template-default .post-title a{
font-size:20px;
}
/**contact page**/
#contact_fomr_outer .form_inner{
background: #F7F7F7;
padding: 20px;
padding-left: 40px;
}
#contact_fomr_outer .form_inner input,
#contact_fomr_outer .form_inner textarea{
width:100%;
}
#contact_fomr_outer .form_inner input.reset,
#contact_fomr_outer .form_inner input.wpcf7-submit{
height:31px;
width: 92px;
text-transform: uppercase;
float:right;
}
#contact_fomr_outer .form_inner .ajax-loader{
float:left;
}
#contact_fomr_outer .form_inner input.reset{
background: #B5B5B5;
color:#fff;
border:none;
margin-right: 10px;
}
#contact_fomr_outer .form_inner input.wpcf7-submit{
background: #0BB0A9;
color:#fff;
border:none;
margin-right: 20px;
}
#contact_fomr_outer .inquiry_icon,
#contact_fomr_outer .inquiry_text{
padding-right:0;
}
#contact_fomr_outer .head-title{
margin-left:0;
margin-right:0;
margin-bottom: 10px;
}
#contact_fomr_outer .form_inner{
margin-right:0px;
}
.contact_page_content .contact_content_left{
margin:0;
padding:0;
}
.contact_page_content .contact_content_left .header_content_left,
.contact_page_content .contact_content_left .map_area{
width:100%;
margin:0;
}
.contact_page_content .contact_content_left .header_content_left p{
width:100%;
}
/***
Pagenavi && sidebar
***/
.wp-pagenavi a,
.wp-pagenavi span.pages,
.wp-pagenavi span.extend{
float: right;
}
.wp-pagenavi span.current{
float: right;
}
#primary-sidebar{
background: none repeat scroll 0 0 #F1F1F1;
border: 7px solid #E5E5E3;
border-radius: 5px;
padding: 0;
}
#primary-sidebar .widget-title{
background: #F58B0C;
border-bottom: 1px solid;
color: #FFFFFF;
display: block;
font-weight: 500;
height: 40px;
line-height: 40px;
padding-right: 30px;
text-transform: uppercase;
width: 100%;
margin: 5px 0;
padding-left: 15px;
}
#primary-sidebar .latest_posts{
margin:0;
padding:0;
}
#primary-sidebar .latest_posts ul,
#primary-sidebar .latest_posts li{
list-style: none outside none;
}
#home_banner .ls-bottom-nav-wrapper,
#home_banner .ls-below-thumbnails{
position:absolute;
left:0;
bottom:115px;
}
#home_banner .ls-wp-container .ls-nav-prev,
#home_banner .ls-wp-container .ls-nav-next{
display:none;
}
#home_banner .ls-wp-container:hover .ls-nav-prev,
#home_banner .ls-wp-container:hover .ls-nav-next{
display:block;
}
.home_video_container{
height:500px;
}
.product_big_thumb #small_thumb_list .jcarousel-skin-tango .jcarousel-prev-horizontal{
background: url("./images/left_arrow.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
height: 70px;
left: -24px;
top: 14px;
width: 50px;
}
.product_big_thumb #small_thumb_list .jcarousel-skin-tango .jcarousel-next-horizontal{
background: url("./images/right_arrow.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
height: 70px;
right: -38px;
top: 17px;
width: 50px;
}
.product-info-detail h2{padding:0 10px;}
@media screen and (min-width: 1260px) {
.container{
max-width:1280px;
}
.container .container{
max-width:1000px;
}
.content{
width:1000px;
}
}
| dinhkk/farjun | style.css | CSS | apache-2.0 | 25,358 |
/**
* 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.camel.component.sql;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
/**
* @version
*/
public class SqlRouteTest extends CamelTestSupport {
protected String driverClass = "org.hsqldb.jdbcDriver";
protected String url = "jdbc:hsqldb:mem:camel_jdbc";
protected String user = "sa";
protected String password = "";
private DataSource ds;
private JdbcTemplate jdbcTemplate;
@Test
public void testSimpleBody() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:simple", "XXX");
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
Map row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Linux", row.get("PROJECT"));
}
@Test
public void testQueryAsHeader() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:simple", "Camel", SqlConstants.SQL_QUERY, "select * from projects where project = ? order by id");
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
Map row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals(1, row.get("id"));
assertEquals("ASF", row.get("license"));
mock.reset();
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:simple", 3, SqlConstants.SQL_QUERY, "select * from projects where id = ? order by id");
mock.assertIsSatisfied();
received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Linux", row.get("PROJECT"));
assertEquals("XXX", row.get("license"));
}
@Test
public void testListBody() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
List<Object> body = new ArrayList<Object>();
body.add("ASF");
body.add("Camel");
template.sendBody("direct:list", body);
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
Map row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals(1, row.get("ID"));
}
@Test
public void testLowNumberOfParameter() throws Exception {
try {
template.sendBody("direct:list", "ASF");
fail();
} catch (RuntimeCamelException e) {
// should have DataAccessException thrown
assertTrue("Exception thrown is wrong", e.getCause() instanceof DataAccessException);
}
}
@Test
public void testHighNumberOfParameter() throws Exception {
try {
template.sendBody("direct:simple", new Object[] {"ASF", "Foo"});
fail();
} catch (RuntimeCamelException e) {
// should have DataAccessException thrown
assertTrue("Exception thrown is wrong", e.getCause() instanceof DataAccessException);
}
}
@Test
public void testListResult() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedHeaderReceived(SqlConstants.SQL_ROW_COUNT, "2");
mock.expectedMessageCount(1);
List<Object> body = new ArrayList<Object>();
body.add("ASF");
template.sendBody("direct:simple", body);
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
assertEquals(2, received.size());
Map row1 = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Camel", row1.get("PROJECT"));
Map row2 = assertIsInstanceOf(Map.class, received.get(1));
assertEquals("AMQ", row2.get("PROJECT"));
}
@Test
public void testListLimitedResult() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
List<Object> body = new ArrayList<Object>();
body.add("ASF");
template.sendBody("direct:simpleLimited", body);
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
assertEquals(1, received.size());
Map row1 = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Camel", row1.get("PROJECT"));
}
@Test
public void testInsert() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:insert", new Object[] {10, "test", "test"});
mock.assertIsSatisfied();
try {
String projectName = (String)jdbcTemplate.queryForObject("select project from projects where id = 10", String.class);
assertEquals("test", projectName);
} catch (EmptyResultDataAccessException e) {
fail("no row inserted");
}
Integer actualUpdateCount = mock.getExchanges().get(0).getIn().getHeader(SqlConstants.SQL_UPDATE_COUNT, Integer.class);
assertEquals((Integer) 1, actualUpdateCount);
}
@Test
public void testNoBody() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:no-param", null);
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
Map row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Camel", row.get("PROJECT"));
}
@Test
public void testHashesInQuery() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:no-param-insert", "XGPL");
mock.assertIsSatisfied();
Number received = assertIsInstanceOf(Number.class, mock.getReceivedExchanges().get(0).getIn().getHeader(SqlConstants.SQL_UPDATE_COUNT));
assertEquals(1, received.intValue());
Map projectNameInserted = jdbcTemplate.queryForMap("select project, license from projects where id = 5");
assertEquals("#", projectNameInserted.get("PROJECT"));
assertEquals("XGPL", projectNameInserted.get("LICENSE"));
}
@Test
public void testBodyButNoParams() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBody("direct:no-param", "Mock body");
mock.assertIsSatisfied();
List received = assertIsInstanceOf(List.class, mock.getReceivedExchanges().get(0).getIn().getBody());
Map row = assertIsInstanceOf(Map.class, received.get(0));
assertEquals("Camel", row.get("PROJECT"));
}
@Before
public void setUp() throws Exception {
Class.forName(driverClass);
super.setUp();
jdbcTemplate = new JdbcTemplate(ds);
jdbcTemplate.execute("create table projects (id integer primary key,"
+ "project varchar(10), license varchar(5))");
jdbcTemplate.execute("insert into projects values (1, 'Camel', 'ASF')");
jdbcTemplate.execute("insert into projects values (2, 'AMQ', 'ASF')");
jdbcTemplate.execute("insert into projects values (3, 'Linux', 'XXX')");
}
@After
public void tearDown() throws Exception {
super.tearDown();
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
jdbcTemplate.execute("drop table projects");
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
ds = new SingleConnectionDataSource(url, user, password, true);
getContext().getComponent("sql", SqlComponent.class).setDataSource(ds);
errorHandler(noErrorHandler());
from("direct:simple").to("sql:select * from projects where license = # order by id")
.to("mock:result");
from("direct:list")
.to("sql:select * from projects where license = # and project = # order by id")
.to("mock:result");
from("direct:simpleLimited")
.to("sql:select * from projects where license = # order by id?template.maxRows=1")
.to("mock:result");
from("direct:insert").to("sql:insert into projects values (#, #, #)").to("mock:result");
from("direct:no-param").to("sql:select * from projects order by id").to("mock:result");
from("direct:no-param-insert").to("sql:insert into projects values (5, '#', param)?placeholder=param").to("mock:result");
}
};
}
}
| chicagozer/rheosoft | components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlRouteTest.java | Java | apache-2.0 | 10,617 |
package com.example.fw;
public class HelpersBase {
protected final ApplicationManager manager;
public HelpersBase(ApplicationManager applicationManager) {
this.manager = applicationManager;
}
}
| Angy1/addressbook-native-tests | src/com/example/fw/HelpersBase.java | Java | apache-2.0 | 203 |
go build -o colony-test-read-data-1
mv colony-test-read-data-1 $EC_APP_PATH/web
cd $EC_APP_PATH/web
./colony-test-read-data-1
| eaciit/colony-app | data-root/sample-application/colony-test-read-data-1/install.sh | Shell | apache-2.0 | 126 |
# Matthiola odorata (Jacq.) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Guettarda/Guettarda odorata/ Syn. Matthiola odorata/README.md | Markdown | apache-2.0 | 189 |
package com.dm.wallpaper.board.databases;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.SparseArrayCompat;
import android.util.Log;
import com.danimahardhika.android.helpers.core.TimeHelper;
import com.dm.wallpaper.board.helpers.JsonHelper;
import com.dm.wallpaper.board.items.Category;
import com.dm.wallpaper.board.items.Wallpaper;
import com.dm.wallpaper.board.preferences.Preferences;
import com.dm.wallpaper.board.utils.LogUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/*
* Wallpaper Board
*
* Copyright (c) 2017 Dani Mahardhika
*
* 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.
*/
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "wallpaper_board_database";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_WALLPAPERS = "wallpapers";
private static final String TABLE_CATEGORIES = "categories";
private static final String KEY_ID = "id";
private static final String KEY_NAME= "name";
private static final String KEY_AUTHOR = "author";
private static final String KEY_URL = "url";
private static final String KEY_THUMB_URL = "thumbUrl";
private static final String KEY_FAVORITE = "favorite";
private static final String KEY_CATEGORY = "category";
private static final String KEY_SELECTED = "selected";
private static final String KEY_MUZEI_SELECTED = "muzeiSelected";
private static final String KEY_ADDED_ON = "addedOn";
private final Context mContext;
@NonNull
public static Database get(@NonNull Context context) {
return new Database(context);
}
private Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_CATEGORY = "CREATE TABLE " +TABLE_CATEGORIES+ "(" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
KEY_NAME + " TEXT NOT NULL," +
KEY_SELECTED + " INTEGER DEFAULT 1," +
KEY_MUZEI_SELECTED + " INTEGER DEFAULT 1, " +
"UNIQUE (" +KEY_NAME+ "))";
String CREATE_TABLE_WALLPAPER = "CREATE TABLE IF NOT EXISTS " +TABLE_WALLPAPERS+ "(" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
KEY_NAME+ " TEXT NOT NULL, " +
KEY_AUTHOR + " TEXT, " +
KEY_URL + " TEXT NOT NULL, " +
KEY_THUMB_URL + " TEXT NOT NULL, " +
KEY_CATEGORY + " TEXT NOT NULL," +
KEY_FAVORITE + " INTEGER DEFAULT 0," +
KEY_ADDED_ON + " TEXT NOT NULL, " +
"UNIQUE (" +KEY_URL+ "))";
db.execSQL(CREATE_TABLE_CATEGORY);
db.execSQL(CREATE_TABLE_WALLPAPER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
resetDatabase(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
resetDatabase(db);
}
private void resetDatabase(SQLiteDatabase db) {
Preferences.get(mContext).setAutoIncrement(0);
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type=\'table\'", null);
SparseArrayCompat<String> tables = new SparseArrayCompat<>();
if (cursor.moveToFirst()) {
do {
tables.append(tables.size(), cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
for (int i = 0; i < tables.size(); i++) {
try {
String dropQuery = "DROP TABLE IF EXISTS " + tables.get(i);
if (!tables.get(i).equalsIgnoreCase("SQLITE_SEQUENCE"))
db.execSQL(dropQuery);
} catch (Exception ignored) {}
}
onCreate(db);
}
public void close() {
if (this.getWritableDatabase().isOpen()) {
try {
this.getWritableDatabase().close();
LogUtil.e("database forced to close");
} catch (Exception e) {
LogUtil.e(Log.getStackTraceString(e));
}
}
}
public void addCategories(List<?> list) {
String query = "INSERT OR IGNORE INTO " +TABLE_CATEGORIES+ " (" +KEY_NAME+ ") VALUES (?);";
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement statement = db.compileStatement(query);
db.beginTransaction();
for (int i = 0; i < list.size(); i++) {
statement.clearBindings();
Category category;
if (list.get(i) instanceof Category) {
category = (Category) list.get(i);
} else {
category = JsonHelper.getCategory(list.get(i));
}
if (category != null) {
statement.bindString(1, category.getName());
statement.execute();
}
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
public void addWallpapers(@NonNull List<?> list) {
String query = "INSERT OR IGNORE INTO " +TABLE_WALLPAPERS+ " (" +KEY_NAME+ "," +KEY_AUTHOR+ "," +KEY_URL+ ","
+KEY_THUMB_URL+ "," +KEY_CATEGORY+ "," +KEY_ADDED_ON+ ") VALUES (?,?,?,?,?,?);";
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement statement = db.compileStatement(query);
db.beginTransaction();
for (int i = 0; i < list.size(); i++) {
statement.clearBindings();
Wallpaper wallpaper;
if (list.get(i) instanceof Wallpaper) {
wallpaper = (Wallpaper) list.get(i);
} else {
wallpaper = JsonHelper.getWallpaper(list.get(i));
}
if (wallpaper != null) {
if (wallpaper.getUrl() != null) {
String name = JsonHelper.getGeneratedName(mContext, wallpaper.getName());
statement.bindString(1, name);
if (wallpaper.getAuthor() != null) {
statement.bindString(2, wallpaper.getAuthor());
} else {
statement.bindNull(2);
}
statement.bindString(3, wallpaper.getUrl());
statement.bindString(4, wallpaper.getThumbUrl());
statement.bindString(5, wallpaper.getCategory());
statement.bindString(6, TimeHelper.getLongDateTime());
statement.execute();
}
}
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
public void selectCategory(int id, boolean isSelected) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SELECTED, isSelected ? 1 : 0);
db.update(TABLE_CATEGORIES, values, KEY_ID +" = ?", new String[]{String.valueOf(id)});
db.close();
}
public void selectCategoryForMuzei(int id, boolean isSelected) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_MUZEI_SELECTED, isSelected ? 1 : 0);
db.update(TABLE_CATEGORIES, values, KEY_ID +" = ?", new String[]{String.valueOf(id)});
db.close();
}
public void favoriteWallpaper(int id, boolean isFavorite) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FAVORITE, isFavorite ? 1 : 0);
db.update(TABLE_WALLPAPERS, values, KEY_ID +" = ?", new String[]{String.valueOf(id)});
db.close();
}
private List<String> getSelectedCategories(boolean isMuzei) {
List<String> categories = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String column = isMuzei ? KEY_MUZEI_SELECTED : KEY_SELECTED;
Cursor cursor = db.query(TABLE_CATEGORIES, new String[]{KEY_NAME}, column +" = ?",
new String[]{"1"}, null, null, KEY_NAME);
if (cursor.moveToFirst()) {
do {
categories.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return categories;
}
public List<Category> getCategories() {
List<Category> categories = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CATEGORIES, null, null, null, null, null, KEY_NAME);
if (cursor.moveToFirst()) {
do {
Category category = new Category(
cursor.getInt(0),
cursor.getString(1),
cursor.getInt(2) == 1,
cursor.getInt(3) == 1,
0);
categories.add(category);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return categories;
}
public int getCategoryCount(String category) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, "LOWER(" +KEY_CATEGORY+ ") LIKE ?",
new String[]{"%" +category.toLowerCase(Locale.getDefault())+ "%"}, null, null, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public List<Wallpaper> getFilteredWallpapers() {
List<Wallpaper> wallpapers = new ArrayList<>();
List<String> selected = getSelectedCategories(false);
List<String> selection = new ArrayList<>();
if (selected.size() == 0) return wallpapers;
StringBuilder CONDITION = new StringBuilder();
for (String item : selected) {
if (CONDITION.length() > 0 ) {
CONDITION.append(" OR ").append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
} else {
CONDITION.append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
}
selection.add("%" +item.toLowerCase(Locale.getDefault())+ "%");
}
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, CONDITION.toString(),
selection.toArray(new String[selection.size()]),
null, null, KEY_ADDED_ON+ " DESC, " +KEY_ID);
if (cursor.moveToFirst()) {
do {
Wallpaper wallpaper = new Wallpaper(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getInt(6) == 1);
wallpapers.add(wallpaper);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return wallpapers;
}
public List<Wallpaper> getWallpapers() {
List<Wallpaper> wallpapers = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null,
KEY_ADDED_ON+ " DESC, " +KEY_ID);
if (cursor.moveToFirst()) {
do {
Wallpaper wallpaper = new Wallpaper(
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5));
wallpapers.add(wallpaper);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return wallpapers;
}
@Nullable
public Wallpaper getRandomWallpaper() {
Wallpaper wallpaper = null;
List<String> selected = getSelectedCategories(true);
List<String> selection = new ArrayList<>();
if (selected.size() == 0) return null;
StringBuilder CONDITION = new StringBuilder();
for (String item : selected) {
if (CONDITION.length() > 0 ) {
CONDITION.append(" OR ").append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
} else {
CONDITION.append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
}
selection.add("%" +item.toLowerCase(Locale.getDefault())+ "%");
}
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, CONDITION.toString(),
selection.toArray(new String[selection.size()]), null, null, "RANDOM()", "1");
if (cursor.moveToFirst()) {
do {
wallpaper = new Wallpaper(
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return wallpaper;
}
public int getWallpapersCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, null, null, null, null, null, null);
int rowCount = cursor.getCount();
cursor.close();
db.close();
return rowCount;
}
public List<Wallpaper> getFavoriteWallpapers() {
List<Wallpaper> wallpapers = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WALLPAPERS, null, KEY_FAVORITE +" = ?",
new String[]{"1"}, null, null, KEY_ADDED_ON+ " DESC, " +KEY_ID);
if (cursor.moveToFirst()) {
do {
Wallpaper wallpaper = new Wallpaper(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getInt(6) == 1);
wallpapers.add(wallpaper);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return wallpapers;
}
public void deleteWallpapers(@NonNull List<Wallpaper> wallpapers) {
SQLiteDatabase db = this.getWritableDatabase();
for (int i = 0; i < wallpapers.size(); i++) {
db.delete(TABLE_WALLPAPERS, KEY_URL +" = ?",
new String[]{wallpapers.get(i).getUrl()});
}
db.close();
}
public void deleteWallpapers() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("SQLITE_SEQUENCE", "NAME = ?", new String[]{TABLE_WALLPAPERS});
db.delete(TABLE_WALLPAPERS, null, null);
db.close();
}
public void deleteCategories() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("SQLITE_SEQUENCE", "NAME = ?", new String[]{TABLE_CATEGORIES});
db.delete(TABLE_CATEGORIES, null, null);
db.close();
}
}
| SikanderKamran/wallpaperboard | library/src/main/java/com/dm/wallpaper/board/databases/Database.java | Java | apache-2.0 | 16,661 |
December 18, 2019 19:51:18 Library.fmp12 - deleteLearnMainRecord -1-
learn: deleteLearnMainRecord
#
#
#If node that created this record as its primary
#creator is currenlty locked then stop script,
#inform user.
If [ tagTLNodePrimary::orderOrLock ≠ "" ]
Show Custom Dialog [ Message: "The node that created this record, " & tagTLNodePrimary::tag & ", is locked, so all this node's
records are locked too. Go back to Setup to unlock it."; Default Button: “OK”, Commit: “Yes” ]
Exit Script [ ]
End If
#
#If in find mode, exit script.
If [ $$findMode ≠ "" ]
Show Custom Dialog [ Message: "Currently in find mode. Click done in the tag menus window to exit find mode, and then click
this button."; Default Button: “OK”, Commit: “Yes” ]
Exit Script [ ]
End If
#
#Exit field so user can see red delete
#formatting later on.
Go to Field [ ]
#
#If either the brainstorm or test fields are filled show
#message below.
If [ testlearn::kcbrainstorm ≠ "" and testlearn::kctestSubsectionInfo ≠ "" ]
If [ TEMP::InventoryLibraryYN = "" ]
Show Custom Dialog [ Message: "Tagged by brainstorm and test tags. Remove these tags to delete. 1) Click the
'brainstorm' button. 2) Scroll to the highlighted tags. 3) Click the square buttons next to each. 4) Click the 'test' button
and repeat steps 2 and 3."; Default Button: “OK”, Commit: “Yes” ]
Else
Show Custom Dialog [ Message: "Tagged by inventory list and test tags. Remove these tags to delete. 1) Click the
'inventory list' button. 2) Scroll to the highlighted tags. 3) Click the square buttons next to each. 4) Click the 'test' button
and repeat steps 2 and 3."; Default Button: “OK”, Commit: “Yes” ]
End If
Exit Script [ ]
Else If [ //The following tests insures that paragraph returns with no numbes in them will not prevent delete. So field can be full of
paragraph returns, but have no ID numers, and so can be deleted.
testlearn::kcbrainstorm ≠ "" and Length ( testlearn::kcbrainstorm ) ≠ ValueCount ( testlearn::kcbrainstorm ) ]
If [ TEMP::InventoryLibraryYN = "" ]
Show Custom Dialog [ Message: "Tagged by brainstorm tags. Remove these tags to delete. 1) Click the 'brainstorm' button.
2) Scroll to the highlighted tags. 3) Click the square buttons next to each."; Default Button: “OK”, Commit: “Yes” ]
Else
Show Custom Dialog [ Message: "Tagged by inventory list tags. Remove these tags to delete. 1) Click the 'inventory list'
button. 2) Scroll to the highlighted tags. 3) Click the square buttons next to each."; Default Button: “OK”, Commit: “Yes” ]
End If
Exit Script [ ]
Else If [ testlearn::kctestSubsectionInfo ≠ "" ]
Show Custom Dialog [ Message: "Tagged by test tags. Remove these tags to delete. 1) Click the 'test' button. 2) Scroll to the
highlighted tags. 3) Click the square buttons next to each."; Default Button: “OK”, Commit: “Yes” ]
Exit Script [ ]
End If
#
#
#
#
#If the library is not an inventory library, and
#if the record has references or links to other
#Learn records, ask the user if they would like
#to remove these or delete the selected record.
If [ TEMP::InventoryLibraryYN = "" ]
If [ refLearn::referenceShort ≠ ""
or
refTestLearn::concatenateLong ≠ ""
or
Filter ( testlearn::kcreference ; "L" ) ≠ "" ]
#
#
# If references and links ...
If [ refLearn::referenceShort ≠ "" and refTestLearn::concatenateLong ≠ ""
or
refLearn::referenceShort ≠ "" and Filter ( testlearn::kcreference ; "L" ) ≠ "" ]
Show Custom Dialog [ Message: "Remove record's references, links to other Learn records, or delete this record.
NOTE: You be given the chance to cancel after answering this question."; Default Button: “references”, Commit:
“Yes”; Button 2: “links”, Commit: “No”; Button 3: “delete”, Commit: “No” ]
If [ Get ( LastMessageChoice ) = 1 ]
Set Variable [ $remove; Value:"1c" ]
End If
If [ Get ( LastMessageChoice ) = 2 ]
Set Variable [ $remove; Value:"2c" ]
End If
#
# If only references ...
Else If [ refLearn::referenceShort ≠ "" ]
Show Custom Dialog [ Message: "Remove record's references or delete this record."; Default Button: “references”,
Commit: “Yes”; Button 2: “delete”, Commit: “No”; Button 3: “cancel”, Commit: “No” ]
If [ Get ( LastMessageChoice ) = 1 ]
Set Variable [ $remove; Value:1 ]
End If
#
# If cancel is selected, then cancel this script.
If [ Get ( LastMessageChoice ) = 3 ]
Exit Script [ ]
End If
#
# If only links ...
Else If [ refTestLearn::concatenateLong ≠ ""
or
Filter ( testlearn::kcreference ; "L" ) ≠ "" ]
Show Custom Dialog [ Message: "Remove links to other Learn records or delete this record."; Default Button: “links”,
Commit: “Yes”; Button 2: “delete”, Commit: “No”; Button 3: “cancel”, Commit: “No” ]
If [ Get ( LastMessageChoice ) = 1 ]
Set Variable [ $remove; Value:2 ]
End If
#
# If cancel is selected, then cancel this script.
If [ Get ( LastMessageChoice ) = 3 ]
Exit Script [ ]
End If
End If
#
#
#If they select references, then remove all
#reference record ID numbers.
If [ $remove = 1 or $remove = "1c" ]
#
If [ $remove = "1c" ]
Show Custom Dialog [ Message: "Are you sure you want to remove this record's references?"; Default Button:
“yes”, Commit: “Yes”; Button 2: “cancel”, Commit: “No” ]
#
# If cancel is selected, then cancel this script.
If [ Get ( LastMessageChoice ) = 2 ]
Exit Script [ ]
End If
End If
#
Set Variable [ $$stoploadCitation; Value:1 ]
Set Variable [ $count; Value:ValueCount ( testlearn::kcreference ) ]
Loop
If [ Filter ( GetValue ( testlearn::kcreference ; $count ) ; "L" ) ≠ "L" ]
Set Field [ testlearn::kcreference; //last item in list has no paragraph mark, so a valuecount test needs to be
done and if item is not removed, then the removal calc without the paragraph mark is used
If ( ValueCount ( testlearn::kcreference) ≠ ValueCount ( Substitute ( testlearn::kcreference ; GetValue
( testlearn::kcreference ; $count ) & "¶" ; "" ) ) ;
Substitute ( testlearn::kcreference ; GetValue ( testlearn::kcreference ; $count ) & "¶" ; "" ) ;
Substitute ( testlearn::kcreference ; GetValue ( testlearn::kcreference ; $count ); "" )
) ]
End If
Set Variable [ $count; Value:$count - 1 ]
Exit Loop If [ $count = 0 ]
End Loop
Set Variable [ $$stoploadCitation ]
#
#Exit script once removal is completed.
Perform Script [ “loadLearnOrRefMainRecord” ]
Exit Script [ ]
End If
#
#
#If they select links, then remove all
#Learn record ID numbers.
If [ $remove = 2 or $remove = "2c" ]
#
If [ $remove = "2c" ]
Show Custom Dialog [ Message: "Are you sure you want to remove this record's links to other Learn records?";
Default Button: “yes”, Commit: “Yes”; Button 2: “cancel”, Commit: “No” ]
#
# If cancel is selected, then cancel this script.
If [ Get ( LastMessageChoice ) = 2 ]
Exit Script [ ]
End If
End If
#
Set Variable [ $$stoploadCitation; Value:1 ]
Set Variable [ $count; Value:ValueCount ( testlearn::kcreference ) ]
Loop
If [ Filter ( GetValue ( testlearn::kcreference ; $count ) ; "L" ) = "L" ]
Set Field [ testlearn::kcreference; //last item in list has no paragraph mark, so a valuecount test needs to be
done and if item is not removed, then the removal calc without the paragraph mark is used
If ( ValueCount ( testlearn::kcreference) ≠ ValueCount ( Substitute ( testlearn::kcreference ; GetValue
( testlearn::kcreference ; $count ) & "¶" ; "" ) ) ;
Substitute ( testlearn::kcreference ; GetValue ( testlearn::kcreference ; $count ) & "¶" ; "" ) ;
Substitute ( testlearn::kcreference ; GetValue ( testlearn::kcreference ; $count ); "" )
) ]
End If
Set Variable [ $count; Value:$count - 1 ]
Exit Loop If [ $count = 0 ]
End Loop
Set Variable [ $$stoploadCitation ]
#
#Exit script once removal is completed.
Perform Script [ “loadLearnOrRefMainRecord” ]
Exit Script [ ]
End If
End If
End If
#
#
#
#
#Prevent all record load scripts (they slow down
#this script and are uneccessary).
Set Variable [ $$stoploadCitation; Value:1 ]
#
#Set variables to conditionally format section to
#be deleted, and its record number so if the
#user cancels the delete, the system can return
#to this record.
Set Variable [ $delete; Value:testlearn::_Ltestlearn ]
Set Variable [ $deleteName; Value:testlearn::_Number ]
Set Variable [ $recordNumber; Value:Get (RecordNumber) ]
#
#Because there may be no records found, stop
#the system from informing the user of this.
Allow User Abort [ Off ]
Set Error Capture [ On ]
#
#Open a new window and look for record being
#cited or used as a reference by another record.
New Window [ Style: Document; Height: 1; Width: 1; Top: 10000; Left: 10000; Close: Yes; Minimize: Yes; Maximize: Yes; Resize: Yes ]
#
#See if learn record is used by any learn
#records as a reference.
Go to Layout [ “tableTestLearn” (testlearn) ]
Enter Find Mode [ ]
Set Field [ testlearn::kcreference; $delete ]
Perform Find [ ]
#
If [ Get (LastError) ≠ 401 ]
If [ $inUse ≠ "" ]
Set Variable [ $addToInUse; Value:$inUse ]
Set Variable [ $inUse; Value:$addToInUse & ", " & Get (FoundCount) & " Learn" ]
Else If [ $inUse = "" ]
Set Variable [ $inUse; Value:Get (FoundCount) & " Learn" ]
End If
End If
#
#See if learn record is used by any tag records
#as a picture. NOTE: The ability to add learn
#record pictures is no longer possible since
#version 3.
Go to Layout [ “tableTag” (tagTable) ]
#picture1
Enter Find Mode [ ]
Set Field [ tagTable::Kpicture1; $delete ]
Perform Find [ ]
Set Variable [ $tagFound1; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#picture2
Enter Find Mode [ ]
Set Field [ tagTable::Kpicture2; $delete ]
Perform Find [ ]
Set Variable [ $tagFound2; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#picture3
Enter Find Mode [ ]
Set Field [ tagTable::Kpicture3; $delete ]
Perform Find [ ]
Set Variable [ $tagFound3; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#
If [ $tagFound1 + $tagFound2 + $tagFound3 ≠ 0 ]
If [ $inUse ≠ "" ]
Set Variable [ $addToInUse; Value:$inUse ]
Set Variable [ $inUse; Value:$addToInUse & ", " & ($tagFound1 + $tagFound2 + $tagFound3) & " tag menu picture(s) (" &
$tagName & ")" ]
Else If [ $inUse = "" ]
Set Variable [ $inUse; Value:($tagFound1 + $tagFound2 + $tagFound3) & " tag menu picture(s) (" & $tagName & ")" ]
End If
End If
#
Set Variable [ $tagFound1 ]
Set Variable [ $tagFound2 ]
Set Variable [ $tagFound3 ]
Set Variable [ $tagNameADD ]
Set Variable [ $tagName ]
#
#See if learn record is used by any tag records
#as a web link. NOTE: Since version 3 this
#function is no longer available.
Go to Layout [ “tableTag” (tagTable) ]
#link1
Enter Find Mode [ ]
Set Field [ tagTable::Ktitle1; $delete ]
Perform Find [ ]
Set Variable [ $tagFound1; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#link2
Enter Find Mode [ ]
Set Field [ tagTable::Ktitle2; $delete ]
Perform Find [ ]
Set Variable [ $tagFound2; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#link3
Enter Find Mode [ ]
Set Field [ tagTable::Ktitle3; $delete ]
Perform Find [ ]
Set Variable [ $tagFound3; Value:Get (FoundCount) ]
If [ Get (FoundCount) > 0 ]
Go to Record/Request/Page
[ First ]
Loop
Set Variable [ $tagNameADD; Value:$tagName ]
Set Variable [ $tagName; Value:Case (
$tagNameAdd = "" ;
tagTable::tag ;
$tagNameAdd & "; " & tagTable::tag ) ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
End If
#
If [ $tagFound1 + $tagFound2 + $tagFound3 ≠ 0 ]
If [ $inUse ≠ "" ]
Set Variable [ $addToInUse; Value:$inUse ]
Set Variable [ $inUse; Value:$addToInUse & ", " & ($tagFound1 + $tagFound2 + $tagFound3) & " tag menu link(s) (" &
$tagName & ")" ]
Else If [ $inUse = "" ]
Set Variable [ $inUse; Value:($tagFound1 + $tagFound2 + $tagFound3) & " tag menu link(s) (" & $tagName & ")" ]
End If
End If
#
Set Variable [ $tagFound1 ]
Set Variable [ $tagFound2 ]
Set Variable [ $tagFound3 ]
Set Variable [ $tagNameADD ]
Set Variable [ $tagName ]
#
#
Close Window [ Current Window ]
#
#
#
#
#Report on findings and if none found
#delete record.
#
#If record was found tell user.
If [ $inUse ≠ "" ]
Set Variable [ $delete ]
Refresh Window
If [ $$LinkedLearnRecords ≠ "" ]
Show Custom Dialog [ Message: "Record cannot be deleted as it in use in these windows: " & $inUse & ". To see them 1)
Click 'find' (above). 2) Click 'linked' in the popup window."; Default Button: “OK”, Commit: “Yes” ]
Else
Show Custom Dialog [ Message: "Record cannot be deleted as it in use in these windows: " & $inUse & "."; Default Button:
“OK”, Commit: “Yes” ]
End If
Set Variable [ $$addTagToCitation ]
Set Variable [ $$stopLoadCitation ]
Set Variable [ $$stopLoadTagRecord ]
Exit Script [ ]
End If
#
#If the record being deleted was not found in
#use make sure the user really wants it deleted.
Set Variable [ $group ]
Refresh Window
If [ Filter ( testlearn::kcreference ; "L" ) ≠ "" and TEMP::InventoryLibraryYN = ""
or
$$LinkedLearnRecords ≠ "" and TEMP::InventoryLibraryYN = "" ]
Show Custom Dialog [ Message: "NOTE: This record has links to other learn records. Are you sure you want to delete it? To
see them 1) click 'cancel'. 2) Click 'find' (above). 3) Click 'linked' in the popup window."; Default Button: “cancel”, Commit:
“Yes”; Button 2: “delete”, Commit: “No” ]
Else
Show Custom Dialog [ Message: "Delete current record?"; Default Button: “cancel”, Commit: “No”; Button 2: “delete”, Commit:
“No” ]
End If
Set Variable [ $group; Value:tagMenus::kGroupOrTest ]
Set Variable [ $deleteGroup; Value:tagMenuGroup::name ]
#
#If the user cancels, stop the delete.
If [ Get ( LastMessageChoice ) = 1 ]
Go to Field [ ]
Set Variable [ $delete ]
Set Variable [ $group ]
Refresh Window
Refresh Window
Set Variable [ $$addTagToCitation ]
Set Variable [ $$stopLoadCitation ]
Set Variable [ $$stopLoadTagRecord ]
Exit Script [ ]
#
#If the user says yes, then delete the record.
Else If [ Get ( LastMessageChoice ) = 2 ]
Delete Record/Request
[ No dialog ]
#
End If
Set Variable [ $delete ]
Set Variable [ $group ]
Refresh Window
Set Variable [ $$addTagToCitation ]
Set Variable [ $$stopLoadCitation ]
Set Variable [ $$stopLoadTagRecord ]
#
Perform Script [ “loadLearnOrRefMainRecord” ]
#
#
| HelpGiveThanks/Library | scripts/learn/deleteLearnMainRecord.c | C | apache-2.0 | 15,482 |
package com.fflorio.simplevalueconverter.activities;
import android.app.AlertDialog;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import com.fflorio.simplevalueconverter.R;
/**
* This Class was created for SimpleValueConverter on 20/12/16
* Designed and developed by Francesco Florio
* All Right Reserved.
*/
public abstract class AbstractActivity extends AppCompatActivity {
public void showWarningDialog(@StringRes int messageResId) {
showMessageDialog(R.string.warning, messageResId);
}
public void showInfoDialog(@StringRes int messageResId) {
showMessageDialog(R.string.info, messageResId);
}
public void showMessageDialog(@StringRes int titleResId, @StringRes int messageResId) {
new AlertDialog.Builder(this)
.setTitle(titleResId)
.setMessage(messageResId)
.setPositiveButton(R.string.ok, null)
.create().show();
}
}
| fr4style/converter | SimpleValueConverter/app/src/main/java/com/fflorio/simplevalueconverter/activities/AbstractActivity.java | Java | apache-2.0 | 995 |
// Copyright 2019 Jeremy Edwards
//
// 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 filesystem
import (
"net/http"
"path/filepath"
)
func newNative(directory string) (http.Handler, error) {
dir, err := filepath.Abs(directory)
if err != nil {
return nil, err
}
return http.FileServer(http.Dir(dirPath(dir))), nil
}
| jeremyje/gowebserver | filesystem/native.go | GO | apache-2.0 | 840 |
package io.cattle.platform.servicediscovery.api.action;
import io.cattle.platform.api.action.ActionHandler;
import io.cattle.platform.core.addon.ServiceLink;
import io.cattle.platform.core.constants.ServiceConstants;
import io.cattle.platform.core.dao.ServiceConsumeMapDao;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.object.util.DataAccessor;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class AddServiceLinkActionHandler implements ActionHandler {
@Inject
JsonMapper jsonMapper;
@Inject
ServiceConsumeMapDao consumeMapDao;
@Override
public String getName() {
return ServiceConstants.PROCESS_SERVICE_ADD_SERVICE_LINK;
}
@Override
public Object perform(String name, Object obj, ApiRequest request) {
if (!(obj instanceof Service)) {
return null;
}
Service service = (Service) obj;
ServiceLink serviceLink = DataAccessor.fromMap(request.getRequestObject()).withKey(
ServiceConstants.FIELD_SERVICE_LINK).as(jsonMapper, ServiceLink.class);
consumeMapDao.createServiceLink(service, serviceLink);
return service;
}
}
| vincent99/cattle | code/iaas/service-discovery/api/src/main/java/io/cattle/platform/servicediscovery/api/action/AddServiceLinkActionHandler.java | Java | apache-2.0 | 1,298 |
package com.chenpan.commoner.mvp.presenter;
import com.chenpan.commoner.base.pbase.BasePresenter;
import com.chenpan.commoner.mvp.view.IMusicLocalView;
/**
* Created by Administrator on 2016/7/6.
*/
public class MusicLocalPresenter extends BasePresenter<IMusicLocalView> {
}
| a616707902/Commoner | Commoner/app/src/main/java/com/chenpan/commoner/mvp/presenter/MusicLocalPresenter.java | Java | apache-2.0 | 279 |
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link LoadBalancerUriTools}.
*
* @author Olga Maciaszek-Sharma
*/
class LoadBalancerUriToolsTests {
@Test
void originalURIReturnedIfDataMatches() {
TestServiceInstance serviceInstance = new TestServiceInstance();
URI original = UriComponentsBuilder.fromUriString("http://test.example:8080/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isEqualTo(original);
}
@Test
void serviceInstanceHostSet() {
TestServiceInstance serviceInstance = new TestServiceInstance();
URI original = UriComponentsBuilder.fromUriString("http://testHost.example:8080/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getHost()).isEqualTo(serviceInstance.getHost());
}
@Test
void serviceInstanceSchemeSet() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme("https");
URI original = UriComponentsBuilder.fromUriString("http://test.example/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getScheme()).isEqualTo(serviceInstance.getScheme());
}
@Test
void originalSchemeSetIfServiceInstanceSchemeMissing() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme(null);
URI original = UriComponentsBuilder.fromUriString("https://test.example/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getScheme()).isEqualTo(original.getScheme());
}
@Test
void secureSchemeSetIfServiceInstanceSchemeMissingAndServiceInstanceSecure() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme(null).withSecure(true);
URI original = UriComponentsBuilder.fromUriString("http://test.example/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getScheme()).isEqualTo("https");
}
@Test
void secureWsSchemeSetIfServiceInstanceSchemeMissingAndServiceInstanceSecure() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme(null).withSecure(true);
URI original = UriComponentsBuilder.fromUriString("ws://test.example/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getScheme()).isEqualTo("wss");
}
@Test
void defaultSchemeSetIfMissing() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme(null);
URI original = UriComponentsBuilder.fromUriString("//test.example/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getScheme()).isEqualTo("http");
}
@Test
void serviceInstancePortSet() {
TestServiceInstance serviceInstance = new TestServiceInstance().withPort(0);
URI original = UriComponentsBuilder.fromUriString("http://test.example:8080/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getPort()).isEqualTo(serviceInstance.getPort());
}
@Test
void defaultHttpPortSetIfServiceInstancePortIncorrect() {
TestServiceInstance serviceInstance = new TestServiceInstance().withPort(-1);
URI original = UriComponentsBuilder.fromUriString("http://test.example:8888/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getPort()).isEqualTo(80);
}
@Test
void defaultHttpsPortSetIfServiceInstancePortIncorrect() {
TestServiceInstance serviceInstance = new TestServiceInstance().withScheme("https").withPort(-1);
URI original = UriComponentsBuilder.fromUriString("http://test.example:8888/xxx").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getPort()).isEqualTo(443);
}
@Test
void originalUserInfoSet() {
TestServiceInstance serviceInstance = new TestServiceInstance();
URI original = UriComponentsBuilder
.fromUriString("http://testUser@testHost.example/path?query1=test1&query2=test2#fragment").build()
.toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getRawUserInfo()).isEqualTo(original.getRawUserInfo());
assertThat(reconstructed.getRawQuery()).isEqualTo(original.getRawQuery());
assertThat(reconstructed.getRawPath()).isEqualTo(original.getRawPath());
assertThat(reconstructed.getRawQuery()).isEqualTo(original.getRawQuery());
assertThat(reconstructed.getRawFragment()).isEqualTo(original.getRawFragment());
assertThat(reconstructed.getHost()).isEqualTo(serviceInstance.getHost());
assertThat(reconstructed.getPort()).isEqualTo(serviceInstance.getPort());
}
@Test
void reconstructedURIEncodedCorrectly() {
TestServiceInstance serviceInstance = new TestServiceInstance();
URI original = UriComponentsBuilder
.fromUriString("http://test.example/path%40%21%242?query=val%40%21%242#frag%40%21%242").build().toUri();
URI reconstructed = LoadBalancerUriTools.reconstructURI(serviceInstance, original);
assertThat(reconstructed).isNotNull();
assertThat(reconstructed.getRawUserInfo()).isEqualTo(original.getRawUserInfo());
assertThat(reconstructed.getRawQuery()).isEqualTo(original.getRawQuery());
assertThat(reconstructed.getRawPath()).isEqualTo(original.getRawPath());
assertThat(reconstructed.getRawQuery()).isEqualTo(original.getRawQuery());
assertThat(reconstructed.getRawFragment()).isEqualTo(original.getRawFragment());
assertThat(reconstructed.getHost()).isEqualTo(serviceInstance.getHost());
assertThat(reconstructed.getPort()).isEqualTo(serviceInstance.getPort());
}
}
class TestServiceInstance implements ServiceInstance {
private URI uri;
private String scheme = "http";
private String host = "test.example";
private int port = 8080;
private boolean secure;
private Map<String, String> metadata = new LinkedHashMap<>();
TestServiceInstance withScheme(String scheme) {
this.scheme = scheme;
return this;
}
TestServiceInstance withPort(int port) {
this.port = port;
return this;
}
TestServiceInstance withSecure(boolean secure) {
this.secure = secure;
return this;
}
@Override
public String getServiceId() {
return "test-service";
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean isSecure() {
return secure;
}
@Override
public URI getUri() {
return uri;
}
@Override
public Map<String, String> getMetadata() {
return metadata;
}
@Override
public String getScheme() {
return scheme;
}
}
| spring-cloud/spring-cloud-commons | spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerUriToolsTests.java | Java | apache-2.0 | 8,292 |
# AUTOGENERATED FILE
FROM balenalib/raspberrypi4-64-fedora:33-run
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warnin
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 33 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/python/raspberrypi4-64/fedora/33/3.5.10/run/Dockerfile | Dockerfile | apache-2.0 | 2,438 |
# Quercus pedunculiflora var. typica VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Quercus/Quercus robur/ Syn. Quercus pedunculiflora typica/README.md | Markdown | apache-2.0 | 191 |
package com.twu.biblioteca.database;
import com.twu.biblioteca.databasehandlers.MediaHandler;
import com.twu.biblioteca.valueobjects.Book;
import com.twu.biblioteca.valueobjects.Media;
import com.twu.biblioteca.valueobjects.Movie;
import com.twu.biblioteca.valueobjects.User;
import java.util.ArrayList;
/**
* Created by Robert on 29/07/15.
*/
public class MockDatabase implements Database {
private final MediaHandler mediaHandler = new MediaHandler();
private ArrayList<Media> books;
private ArrayList<Media> movies;
private ArrayList<User> users;
public MockDatabase(){
books = createBooks();
movies = createMovies();
users = createUsers();
}
private ArrayList<User> createUsers() {
ArrayList<User> tempUsers = new ArrayList<User>();
tempUsers.add(new User("123-4567", "pass123-4567", "Robert Bagge", "robert.bagge@example.com", "0751234567"));
tempUsers.add(new User("234-5678", "pass234-5678", "Test User1", "test.user1@example.com", "0752345678"));
tempUsers.add(new User("345-6789", "pass345-6789", "Test User2", "test.user2@example.com", "0753456789"));
tempUsers.add(new User("456-7890", "pass456-7890", "Test User3", "test.user3@example.com", "0754567890"));
tempUsers.add(new User("567-8901", "pass567-8901", "Test User4", "test.user4@example.com", "0755678901"));
return tempUsers;
}
private ArrayList<Media> createBooks(){
ArrayList<Media> tempBooks = new ArrayList<Media>();
tempBooks.add(new Book("In Search of Lost Time", "Marcel Proust", "1955", 1));
tempBooks.add(new Book("Ulysses", "James Joyce", "1830", 2));
tempBooks.add(new Book("Don Quixote", "Miguel de Cervantes", "1783", 3));
tempBooks.add(new Book("Moby Dick", "Herman Melville", "1921", 4));
tempBooks.add(new Book("Hamlet", "William Shakespeare", "1563", 5));
tempBooks.add(new Book("War and Peace", "Leo Tolstoy", "1920", 6));
tempBooks.add(new Book("The Odyssey", "Homer", "300 BC", 7));
tempBooks.add(new Book("The Great Gatsby", "F. Scott Fitzgerald", "1983", 8));
tempBooks.add(new Book("The Divine Comedy", "Dante Alighieri", "1467", 9));
tempBooks.add(new Book("Madame Bovary", "Gustave Flaubert", "1963", 10));
tempBooks.add(new Book("The Brothers Karamazov", "Fyodor Dostoyevsky", "1890", 11));
tempBooks.add(new Book("One Hundred Years of Solitude", "Gabriel Garcia Marquez", "1999", 12));
tempBooks.add(new Book("The Adventures of Huckleberry Finn", "Mark Twain", "1930", 13));
tempBooks.add(new Book("The Iliad", "Homer", "300 BC", 14));
tempBooks.add(new Book("Lolita", "Vladimir Nabokov", "1860", 15));
tempBooks.add(new Book("Anna Karenina", "Leo Tolstoy", "1840", 16));
tempBooks.add(new Book("Crime and Punishment", "Fyodor Dostoyevsky", "1914", 17));
tempBooks.add(new Book("The Sound and the Fury", "William Faulkner", "1967", 18));
tempBooks.add(new Book("Pride and Prejudice", "Jane Austen", "1937", 19));
tempBooks.add(new Book("The Catcher in the Rye", "J. D. Salinger", "1979", 20));
return tempBooks;
}
private ArrayList<Media> createMovies(){
ArrayList<Media> tempMovies = new ArrayList<Media>();
tempMovies.add(new Movie("Shawshank Redemption", 1, "1994", "Frank Darabont", "9"));
tempMovies.add(new Movie("The Godfather", 2, "1972", "Francis Ford Coppola", "9"));
tempMovies.add(new Movie("The Godfather:Part II", 3, "1974", "Francis Ford Coppola", "9"));
tempMovies.add(new Movie("The Dark Knight", 4, "2008", "Christopher Nolan", "9"));
tempMovies.add(new Movie("Citizen Kane", 5, "1941", "Orson Welles", "8"));
tempMovies.add(new Movie("Rocky", 6, "1976", "Sylvester Stalone", "8"));
tempMovies.add(new Movie("Spread", 7, "2009", "David Mackenzi", "6"));
tempMovies.add(new Movie("Catch Me If You Can", 8, "2002", "Steven Spielberg", "8"));
tempMovies.add(new Movie("The Human Centipede", 9, "2009", "Tom Six", "Unrated"));
tempMovies.add(new Movie("Gladiator", 10, "2000", "Ridley Scott", "8"));
return tempMovies;
}
public ArrayList<Media> getAllBooks(){
return books;
}
@Override
public ArrayList<Media> getAllMovies() {
return movies;
}
@Override
public ArrayList<User> getAllUsers() {
return users;
}
}
| BaggeRob/twu-biblioteca-robertbagge | src/com/twu/biblioteca/database/MockDatabase.java | Java | apache-2.0 | 4,493 |
# Panicum spectabile var. spectabile VARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Echinochloa/Echinochloa polystachya/Panicum spectabile spectabile/README.md | Markdown | apache-2.0 | 176 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description" content="Search the HanDeDict open-source Chinese-German dictionary online."/>
<meta name="viewport" content="user-scalable=0"/>
<title>HanDeDict Chinese-German dictionary</title>
<link href='https://fonts.googleapis.com/css?family=Noto+Sans:400,400italic&subset=latin,latin-ext' rel='stylesheet'
type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:700&subset=latin,latin-ext' rel='stylesheet'
type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Neuton&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static/tooltipster.css">
<link rel="stylesheet" href="static/style-v1.3.css">
</head>
<body class="loading">
<div id="loading-box">
<div class="loading-anim">...</div>
</div>
<nav id="menu">
<div id="menu-horiz">
<ul>
<li><a href="/">Search</a></li>
<li class="active"><a href="/options">Options</a></li>
<li><a href="/about">About</a></li>
<li class="imprint"><a ref="https://zydeo.net/imprint">Imprint</a></li>
</ul>
<div id="langsel">
<div id="langsel-inner">
<a class="active" id="langselDe" href="?ui=de">DE</a> <a id="langselEn" href="?ui=en">EN</a> <a class="zho" id="langselJian" href="?ui=jian">简体中文</a> <a class="zho" id="langselFan" href="?ui=fan">繁体中文</a>
</div>
</div>
</div>
</nav>
<div id="content" class="hei">
<div id="content-core">
<div id="page-header">
<div id="cell-menu">
<span id="btn-menu"><img id="img-menu" src="static/hamburger.svg" alt="Menu"/></span>
</div>
<h1>Search options</h1>
</div>
<div id="staticContent">
<div id="strokeAnimCanvas">
<input type="text" id="txtHanzi" maxlength="1" style="width: 2em;"/>
<input type="button" id="btnHanzi" value="Look up"/><br/>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewbox='0 0 1024 1024' id="strokeAnimSVG"></svg>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-inside">
<span>HanDeDict @ Zydeo v1.0 • ©2015 Gábor L Ugray • <a id="linkFooterImprint" href="http://zydeo.net/imprint">Imprint</a></span>
</div>
</div>
<div id="bittercookie">
This website relies on cookies for some of its functionality.
By using the site, you agree to its use of cookies.
<a id="swallowbitterpill" href="#">Got it</a>
<a id="cookierecipe" href="#">Learn more</a>
</div>
<!-- Includes for every page -->
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="lib/jquery.tooltipster.min.js"></script>
<script src="lib/jquery.color-2.1.2.min.js"></script>
<script src="lib/raphael-2.1.2.min.js"></script>
<script src="js-1.1/ui-en.js"></script>
<script src="js-1.1/ui-de.js"></script>
<script src="js-1.1/ui-jian.js"></script>
<script src="js-1.1/ui-fan.js"></script>
<script src="js-1.1/common.js"></script>
<!-- Page-specific includes -->
<script src="js-1.1/strokeanim.js"></script>
</body>
</html>
| zydeo/Zydeo | ZDO.Sitebuild/index-strokes.html | HTML | apache-2.0 | 3,074 |
/**
*
*
* @module AppsMallUI.directivesModule
* @submodule AppsMallUI.FileUploadModule
* @requires amlApp.directives
*/
'use strict';
/**
* HTML element directive: Renders clickable image viewing area, and HTML5 file input control to handle file uploading.
*
* Usage: ```<file-upload app-object="[Object]" field="[String]" file-upload-id="[String]" field-name="[String]" min-height="[Number]" min-width="[Number]" max-height="[Number]"
* max-width="[Number]" valid-heights="[Array]" valid-widths="[Array]" delete-button="true"></file-upload>```
*
* @class AppsMallUI.FileUploadDirective
* @static
*/
/**
* @class AppsMallUI.FileUploadDirective
* @constructor
* @param FileUpload {Object} an Angular-injected instance of {{#crossLink "AppsMallUI.FileUploadService"}}{{/crossLink}}
*/
/**
* The App object containing the URL of the uploaded file
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 2-way binding)**_
*
* @attribute {Object} app-object
* @required
*/
/**
* App object-path field name where the URL will be saved to, using dot notation to denote sub-objects
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {String} field
* @required
*/
/**
* Relative name of file object, used by {{#crossLink "AppsMallUI.FileUploadService"}}{{/crossLink}} when resolving server file path
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {String} field-name
* @required
*/
/**
* Minimum height in pixels for uploaded file
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Number} min-height
* @optional
*/
/**
* Minimum width in pixels for uploaded file
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Number} min-width
* @optional
*/
/**
* Maximum height in pixels for uploaded file
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Number} max-height
* @optional
*/
/**
* Maximum width in pixels for uploaded file
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Number} max-width
* @optional
*/
/**
* ID of existing file to upload, if it exists
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Number} file-upload-id
* @optional
*/
/**
* Boolean flag to determine visibility of 'Delete Image' button
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Boolean} delete-button
* @optional
*/
/**
* An array of valid image height values, in array literal form. Any value outside this list is invalid.
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Array} valid-heights
* @optional
*/
/**
* An array of valid image width values, in array literal form. Any value outside this list is invalid.
*
* {{#crossLinkModule "AppsMallUI.AngularScope"}}{{/crossLinkModule}}: _**(scoped to directive as 1-way binding)**_
*
* @attribute {Array} valid-widths
* @optional
*/
var FileUploadDirective = ['FileUpload', function(FileUpload) {
var setStatusMessage = function(msgFunc, msg, isError) {
if (_.isFunction(msgFunc)) {
if (isError) {
msgFunc({errorMessage: msg});
}
else {
msgFunc({successMessage: msg});
}
}
else if (isError) {
alert('Error: ' + msg);
}
};
// Performing dimension check using one of: min H/W, max H/W, or selected H/W values.
// Standard JS truthiness checks are made on each value, which is fine because valid height and width values should not be zero.
var dimensionCheck = function(height, width, dimensionChecker) {
if ((dimensionChecker.minHeight && (height < dimensionChecker.minHeight)) ||
(dimensionChecker.minWidth && (width < dimensionChecker.minWidth))) {
return ("Uploaded image must be at least " + dimensionChecker.minWidth + " pixels in width, and at least " + dimensionChecker.minHeight + " pixels in height.");
}
if ((dimensionChecker.maxHeight && (height > dimensionChecker.maxHeight)) ||
(dimensionChecker.maxWidth && (width > dimensionChecker.maxWidth))) {
return ("Uploaded image cannot be more than " + dimensionChecker.maxWidth + " pixels in width, or more than " + dimensionChecker.maxHeight + " pixels in height.");
}
if (_.isArray(dimensionChecker.validHeights) && _.isArray(dimensionChecker.validWidths) &&
(dimensionChecker.validHeights.length > 0) && (dimensionChecker.validWidths.length > 0)
) {
// converting arrays X and Y into [[x0,y0], ...] array of arrays
var pairedValues = _.zip(dimensionChecker.validHeights, dimensionChecker.validWidths);
if (!_.find(pairedValues, function(pair) { return ((pair[0] === height) && (pair[1] === width)); })) {
// create array of "A x B" dimension strings
var pixelDimensions = pairedValues.map(function(pair) {
if (pair[0] && pair[1]) {
return (pair[0] + 'x' + pair[1] + ' px');
}
});
return ("Uploaded image must have the following dimensions: " + common.humanizedArrayString(pixelDimensions, true) + ".");
}
}
return true;
};
return {
restrict: 'E',
replace: true,
scope: {
appObject: '=',
deleteButton: '@',
field: '@',
fileUploadId: '@',
fieldName: '@',
minHeight: '@',
minWidth: '@',
maxHeight: '@',
maxWidth: '@',
validHeights: '@',
validWidths: '@',
},
template: '<div><input type="file" name="image" style="display:none" />' +
'<div class="clickable-file-upload-area" ng-hide="fileUploadId"><span class="icon-upload icon-camera-outline"></span><br /> <p>Upload New Image</p> </div>' +
'<div class="image-viewing-area" ng-show="fileUploadId"><div class="image-viewing-area-container"><img src="{{getFileUrl(fileUploadId, fieldName)}}" /></div>' +
'<a href="#" class="icon-pencil edit-image-link" ng-hide="deleteButton"></a>' +
'<a href="#" class="icon-artwork delete-image-link icon-minus" ng-show="deleteButton"></a>' +
'</div></div>',
link: function(scope, element, attrs) {
// copying service function into scope
scope.getFileUrl = FileUpload.getFileUrl;
// DOM elements that will stay within scope of bind event
var $uploadClickArea = $(element).find('.clickable-file-upload-area');
var $imageView = $(element).find('.image-viewing-area');
var $fileInput = $(element).find('input[type=file]');
var $imageElement = $(element).find('.image-viewing-area > img');
var $imageUpdateElement = $(element).find('.image-viewing-area .edit-image-link');
var $imageDeleteElement = $(element).find('.image-viewing-area .delete-image-link');
var getCallback = function(callbackAttrName) {
if (attrs[callbackAttrName]) {
if (attrs.parentScopeCallback) {
return attrs[callbackAttrName] && (_.isFunction(scope.$parent[attrs[callbackAttrName]])) && scope.$parent[attrs[callbackAttrName]];
}
else {
return attrs[callbackAttrName] && (_.isFunction(scope[attrs[callbackAttrName]])) && scope[attrs[callbackAttrName]];
}
}
};
var clickEditEvent = function() {
$fileInput.trigger('click');
};
var clickDeleteEvent = function() {
if (_.isFunction(deleteCallback)) {
deleteCallback({_id: scope.fileUploadId}, attrs);
}
};
var callback = getCallback('callback');
var deleteCallback = getCallback('deleteCallback');
$uploadClickArea.click(clickEditEvent);
$imageUpdateElement.click(clickEditEvent);
$imageDeleteElement.click(clickDeleteEvent);
// add change event to hidden file input, fired after user selects a file from file browser
$fileInput.bind('change', function(event) {
var app = scope[attrs.appObject] || scope.$parent[attrs.appObject];
// throw error if app object doesn't exist
if (!_.isObject(app)) {
return setStatusMessage(scope.setStatusMessage, 'Invalid app.', true);
}
scope.app = app;
var appAttribute = attrs.field || 'image';
var files = event.target.files;
var fileObj = files[0];
if (files && fileObj && (fileObj instanceof File)) {
var postUploadCallback = function(data) {
data = data || {};
if (_.isArray(data)) {
data = data.shift(); //get first element of array
}
if (data._id) {
scope.$eval('app.' + appAttribute + ' = "' + data._id + '"'); // using scope.eval to assign attributes with dots
// setImageFunction(data._id);
if (callback) {
callback(data, attrs);
}
else {
setStatusMessage(scope.setStatusMessage, (data.filename + ' (' + (data.length || 0) + ' bytes) has been successfully uploaded.'), false);
}
}
else {
setStatusMessage(scope.setStatusMessage, (data.error || 'Error saving file.'), true);
}
};
// getting dimension values and converting to numeric form. validHeights and validWidths may contain a list of numeric values.
var dimensionChecker = {
minHeight: parseInt(attrs.minHeight),
minWidth: parseInt(attrs.minWidth),
maxHeight: parseInt(attrs.maxHeight),
maxWidth: parseInt(attrs.maxWidth),
validHeights: _((attrs.validHeights || '').split(/\,\s*/)).map(function(v) { return parseInt(v); } ).compact().value(),
validWidths: _((attrs.validWidths || '').split(/\,\s*/)).map(function(v) { return parseInt(v); } ).compact().value()
};
// If any truthy dimension values exist in object, then perform dimension check
if (_(dimensionChecker).values().compact().any()) {
// performing image height/width check using HTML5 File API
var reader = new FileReader();
var fileImage = new Image();
reader.readAsDataURL(fileObj);
reader.onload = function(_file) {
fileImage.src = _file.target.result;
fileImage.onload = function() {
// performing dimension check, where method returns True or an error string.
var dimensionCheckResult = dimensionCheck(this.height, this.width, dimensionChecker);
if (dimensionCheckResult === true) {
FileUpload.upload(fileObj).then(postUploadCallback);
}
else {
setStatusMessage(scope.setStatusMessage, dimensionCheckResult, true);
}
}
}
}
else {
FileUpload.upload(fileObj).then(postUploadCallback);
}
}
}); // end $fileInput.bind('change', ...)
}
}
}];
directivesModule.directive('fileUpload', FileUploadDirective);
| ozone-development/depricated-ozp-center | apps/appsmall/public/js/directives/FileUpload.js | JavaScript | apache-2.0 | 13,048 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: yyg
@Create: 2016MMDD
@LastUpdate: 2016-12-15 HH:MM:SS
@Version: 0.0
"""
from json import load
from logging import (Formatter, _defaultFormatter, exception,
getLogger, FileHandler, basicConfig, StreamHandler)
from cloghandler import ConcurrentRotatingFileHandler
from params import (LOG_CONF_FILE, LOG_LVL, LOGGER_NAME,
LOG_FILE, LOG_DAT_FMT, LOG_FMT)
class LaserjetLogger(object):
"""
Compatible to python 2.6+
"""
def __init__(self):
self.fmt = LOG_FMT
self.datefmt = LOG_DAT_FMT
self._start()
def _start(self):
logger = getLogger(LOGGER_NAME)
log_handler = ConcurrentRotatingFileHandler(LOG_FILE)
log_formatter = Formatter(self.fmt, self.datefmt)
log_handler.setFormatter(log_formatter)
console_handler = StreamHandler()
console_handler.setFormatter(log_formatter)
logger.setLevel(LOG_LVL)
logger.addHandler(log_handler)
logger.addHandler(console_handler)
logger.info("Logger activated")
def print_func(anything_str):
log = getLogger(LOGGER_NAME)
log.info(anything_str)
if __name__ == "__main__":
logger = LaserjetLogger()
test_pool = Pool()
for i in range(5):
test_pool.apply_async(print_func, args=(i,))
test_pool.close()
test_pool.join()
| hipnusleo/laserjet | lib/core/loggers.py | Python | apache-2.0 | 1,506 |
package ru.maizy.ambient7.mt8057agent
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.filter.ThresholdFilter
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.classic.{ Level, LoggerContext, Logger => LogbackLogger }
import ch.qos.logback.core.{ ConsoleAppender, FileAppender, OutputStreamAppender }
import com.google.common.collect.{ EvictingQueue, Queues }
import org.slf4j.LoggerFactory
import ru.maizy.ambient7.core.config.options.Writers
import ru.maizy.ambient7.core.config.{ Ambient7Options, ParsingError }
/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/
object Mt8057AgentAppLauncher extends App {
Mt8057ConfigReader.readAppConfig(args.toIndexedSeq) match {
case Left(parsingError) =>
agentLogger.error(ParsingError.formatErrorsForLog(parsingError))
Console.err.println(ParsingError.formatErrorsAndUsage(parsingError))
case Right(opts) if opts.mt8057AgentSpecificOptions.isEmpty =>
agentLogger.error("unknown error")
case Right(opts) =>
setupLogging(opts)
val writersMap = Map[Writers.Value, Ambient7Options => Writer](
Writers.Console -> { new ConsoleWriter(_) },
Writers.Interactive -> { new InteractiveWriter(_) },
Writers.InfluxDb -> { new InfluxDbWriter(_) }
)
agentLogger.info(
"Start agent with writers: " +
opts.mt8057AgentSpecificOptions.map(_.writers.mkString(", ")).getOrElse("")
)
val writers = opts.mt8057AgentSpecificOptions
.map(_.writers.map(writersMap.apply).map(_(opts)))
.getOrElse(Set.empty)
writers.foreach(_.onInit())
val MAX_QUEUE_SIZE = 100
val queue = Queues.synchronizedQueue(EvictingQueue.create[Event](MAX_QUEUE_SIZE))
val consumerThread = new Thread {
override def run(): Unit = {
while(true) {
Option(queue.poll()) foreach { event =>
writers.foreach(_.write(event))
}
Thread.sleep(100)
}
}
}
consumerThread.setName("agent-consumer")
consumerThread.start()
// has infinity loop inside
if (opts.mt8057AgentSpecificOptions.exists(_.useEmulator)) {
agentLogger.info("Use emulator mode")
new DeviceEmulator(queue).run()
} else {
MT8057Service.run(queue)
}
}
def setupLogging(opts: Ambient7Options): Unit = {
val logContext = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[LogbackLogger]
val verboseLogging = opts.mt8057AgentSpecificOptions.exists(_.verboseLogging)
def setupAppender(appender: OutputStreamAppender[ILoggingEvent], pattern: String, normalLevel: String): Unit = {
val encoder = new PatternLayoutEncoder
encoder.setPattern(pattern)
encoder.setContext(logContext)
encoder.start()
if (!verboseLogging) {
val filter = new ThresholdFilter
filter.setLevel(normalLevel)
filter.start()
appender.addFilter(filter)
}
appender.setEncoder(encoder)
appender.setContext(logContext)
appender.start()
rootLogger.addAppender(appender)
}
val consoleAppender = new ConsoleAppender[ILoggingEvent]
consoleAppender.setTarget("System.err")
setupAppender(
consoleAppender,
pattern = "%gray(%d{HH:mm:ss.SSS}) %highlight(%.-1level) [%cyan(%logger{5})]: %msg%n",
normalLevel = "WARN"
)
opts.mt8057AgentSpecificOptions.flatMap(_.logFile).foreach { file =>
val fileAppender = new FileAppender[ILoggingEvent]
fileAppender.setAppend(true)
fileAppender.setFile(file.toString)
setupAppender(
fileAppender,
pattern = "%d %level [%logger]: %msg%n",
normalLevel = "INFO"
)
}
if (!verboseLogging) {
rootLogger.setLevel(Level.INFO)
}
}
}
| maizy/ambient7 | mt8057-agent/src/main/scala/ru/maizy/ambient7/mt8057agent/Mt8057AgentAppLauncher.scala | Scala | apache-2.0 | 4,000 |
# This file is automatically generated by puppet-swagger-generator and
# any manual changes are likely to be clobbered when the files
# are regenerated.
require_relative '../../../puppet_x/puppetlabs/kubernetes/provider'
Puppet::Type.type(:kubernetes_ingress_tls).provide(:swagger, :parent => PuppetX::Puppetlabs::Kubernetes::Provider) do
mk_resource_methods
def self.instance_to_hash(instance)
{
ensure: :present,
name: instance.metadata.name,
hosts: instance.hosts.respond_to?(:to_hash) ? instance.hosts.to_hash : instance.hosts,
secret_name: instance.secretName.respond_to?(:to_hash) ? instance.secretName.to_hash : instance.secretName,
object: instance,
}
end
def create
Puppet.info("Creating kubernetes_ingress_tls #{name}")
create_instance_of('ingress_tls', name, build_params)
end
def flush
unless @property_hash.empty?
unless resource[:ensure] == :absent
flush_instance_of('ingress_tls', name, @property_hash[:object], build_params)
end
end
end
def destroy
Puppet.info("Deleting kubernetes_ingress_tls #{name}")
destroy_instance_of('ingress_tls', name)
@property_hash[:ensure] = :absent
end
private
def self.list_instances
list_instances_of('ingress_tls')
end
def build_params
params = {
hosts: resource[:hosts],
secretName: resource[:secret_name],
}
params.delete_if { |key, value| value.nil? }
params
end
end
| garethr/garethr-kubernetes | lib/puppet/provider/kubernetes_ingress_tls/swagger.rb | Ruby | apache-2.0 | 1,629 |
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace BollerTuneZ
{
[Activity (Label = "BollerTuneZ", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Bootstrapper.Register ();
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
StartActivity(typeof(ActivityRegLoginTest));
};
}
}
}
| Juanah/Android-BollerTuneZApp | MainActivity.cs | C# | apache-2.0 | 789 |
/*
* The Apache License
*
* Copyright 2009 Marcelo Guimaraes <ataxexe@backpackcloud.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 com.backpackcloud.trugger.util.factory;
public class ToNullConverter implements Converter {
@Override
public Object convert(Object object) {
return null;
}
}
| devnull-tools/trugger | src/test/java/com/backpackcloud/trugger/util/factory/ToNullConverter.java | Java | apache-2.0 | 840 |
var classorg_1_1onosproject_1_1cli_1_1net_1_1HostRemoveCommand =
[
[ "execute", "classorg_1_1onosproject_1_1cli_1_1net_1_1HostRemoveCommand.html#a4960a063b349a69cf44f0b607ce4cabb", null ]
]; | onosfw/apis | onos/apis/classorg_1_1onosproject_1_1cli_1_1net_1_1HostRemoveCommand.js | JavaScript | apache-2.0 | 194 |
/*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* 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.bladecoder.engineeditor.ui;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.bladecoder.engine.model.BaseActor;
import com.bladecoder.engine.model.InteractiveActor;
import com.bladecoder.engine.model.Verb;
import com.bladecoder.engine.model.VerbManager;
import com.bladecoder.engineeditor.Ctx;
import com.bladecoder.engineeditor.common.ElementUtils;
import com.bladecoder.engineeditor.model.Project;
import com.bladecoder.engineeditor.ui.panels.CellRenderer;
import com.bladecoder.engineeditor.ui.panels.EditModelDialog;
import com.bladecoder.engineeditor.ui.panels.ModelList;
import com.bladecoder.engineeditor.ui.panels.ScopePanel;
import com.bladecoder.engineeditor.undo.UndoDeleteVerb;
public class VerbList extends ModelList<VerbManager, Verb> {
public static final String VERBS[] = { "lookat", "pickup", "talkto", "use", "leave", "enter", "exit", "init",
"test", "custom" };
private ActionList actionList;
private ScopePanel scopePanel;
public VerbList(Skin skin) {
super(skin, true);
clearChildren();
scopePanel = new ScopePanel(skin) {
@Override
public void scopeChanged(String scope) {
if (WORLD_SCOPE.equals(scope)) {
addElements(Ctx.project.getWorld().getVerbManager(), Arrays
.asList(Ctx.project.getWorld().getVerbManager().getVerbs().values().toArray(new Verb[0])));
} else if (SCENE_SCOPE.equals(scope)) {
if (Ctx.project.getSelectedScene() != null)
addElements(Ctx.project.getSelectedScene().getVerbManager(), Arrays.asList(Ctx.project
.getSelectedScene().getVerbManager().getVerbs().values().toArray(new Verb[0])));
else
addElements(null, null);
} else if (ACTOR_SCOPE.equals(scope)) {
BaseActor a = Ctx.project.getSelectedActor();
if (a instanceof InteractiveActor) {
addElements(((InteractiveActor) a).getVerbManager(), Arrays.asList(
((InteractiveActor) a).getVerbManager().getVerbs().values().toArray(new Verb[0])));
} else {
addElements(null, null);
}
}
}
};
add(scopePanel).expandX().fillX();
row();
add(toolbar).expandX().fillX();
row().fill();
add(container).expandY().fill();
actionList = new ActionList(skin);
row();
add(actionList).expand().fill();
list.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
addActions();
}
});
list.setCellRenderer(listCellRenderer);
listCellRenderer.layout(list.getStyle());
container.minHeight(listCellRenderer.getItemHeight() * 5);
container.maxHeight(listCellRenderer.getItemHeight() * 5);
Ctx.project.addPropertyChangeListener(Project.NOTIFY_ELEMENT_CREATED, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() instanceof Verb && !(evt.getSource() instanceof EditVerbDialog)) {
if (ScopePanel.WORLD_SCOPE.equals(scopePanel.getScope())) {
addElements(Ctx.project.getWorld().getVerbManager(), Arrays.asList(
Ctx.project.getWorld().getVerbManager().getVerbs().values().toArray(new Verb[0])));
} else if (ScopePanel.SCENE_SCOPE.equals(scopePanel.getScope())) {
addElements(Ctx.project.getSelectedScene().getVerbManager(), Arrays.asList(Ctx.project
.getSelectedScene().getVerbManager().getVerbs().values().toArray(new Verb[0])));
} else if (ScopePanel.ACTOR_SCOPE.equals(scopePanel.getScope())) {
BaseActor a = Ctx.project.getSelectedActor();
if (a instanceof InteractiveActor) {
addElements(((InteractiveActor) a).getVerbManager(), Arrays.asList(
((InteractiveActor) a).getVerbManager().getVerbs().values().toArray(new Verb[0])));
} else {
addElements(null, null);
}
}
}
}
});
}
public void changeActor() {
scopePanel.scopeChanged(scopePanel.getScope());
}
@Override
protected EditModelDialog<VerbManager, Verb> getEditElementDialogInstance(Verb e) {
return new EditVerbDialog(skin, scopePanel.getScope(), parent, e);
}
@Override
public void addElements(VerbManager vm, List<Verb> elements) {
super.addElements(vm, elements);
addActions();
}
@Override
protected void delete() {
Verb v = removeSelected();
parent.getVerbs().remove(v.getHashKey());
// TRANSLATIONS
if (scopePanel.getScope().equals(ScopePanel.WORLD_SCOPE))
Ctx.project.getI18N().putTranslationsInElement(v, true);
else
Ctx.project.getI18N().putTranslationsInElement(v, false);
// UNDO
Ctx.project.getUndoStack().add(new UndoDeleteVerb(parent, v));
// Clear actions here because change event doesn't call when deleting
// the last element
if (list.getSelectedIndex() == -1)
addActions();
Ctx.project.setModified();
}
@Override
protected void copy() {
Verb e = list.getSelected();
if (e == null)
return;
clipboard = (Verb) ElementUtils.cloneElement(e);
toolbar.disablePaste(false);
// TRANSLATIONS
if (scopePanel.getScope().equals(ScopePanel.WORLD_SCOPE))
Ctx.project.getI18N().putTranslationsInElement(clipboard, true);
else
Ctx.project.getI18N().putTranslationsInElement(clipboard, false);
}
@Override
protected void paste() {
Verb newElement = (Verb) ElementUtils.cloneElement(clipboard);
// Check for id duplicates
String[] keys = new String[parent.getVerbs().size()];
Verb[] values = parent.getVerbs().values().toArray(new Verb[0]);
for (int i = 0; i < keys.length; i++) {
keys[i] = values[i].getId();
}
newElement.setId(ElementUtils.getCheckedId(newElement.getId(), keys));
int pos = list.getSelectedIndex() + 1;
list.getItems().insert(pos, newElement);
parent.addVerb(newElement);
if (scopePanel.getScope().equals(ScopePanel.WORLD_SCOPE))
Ctx.project.getI18N().extractStrings(null, null, newElement);
else if (scopePanel.getScope().equals(ScopePanel.SCENE_SCOPE))
Ctx.project.getI18N().extractStrings(Ctx.project.getSelectedScene().getId(), null, newElement);
else
Ctx.project.getI18N().extractStrings(Ctx.project.getSelectedScene().getId(),
Ctx.project.getSelectedActor().getId(), newElement);
list.setSelectedIndex(pos);
list.invalidateHierarchy();
Ctx.project.setModified();
}
private void addActions() {
int pos = list.getSelectedIndex();
Verb v = null;
if (pos != -1) {
v = list.getItems().get(pos);
actionList.setScope(scopePanel.getScope());
actionList.addElements(v, v.getActions());
} else {
actionList.addElements(null, null);
actionList.setScope(null);
}
}
// -------------------------------------------------------------------------
// ListCellRenderer
// -------------------------------------------------------------------------
private final CellRenderer<Verb> listCellRenderer = new CellRenderer<Verb>() {
@Override
protected String getCellTitle(Verb e) {
return e.getId();
}
@Override
protected String getCellSubTitle(Verb e) {
String state = e.getState();
String target = e.getTarget();
StringBuilder sb = new StringBuilder();
if (state != null)
sb.append("when ").append(state);
if (target != null)
sb.append(" target: '").append(target).append("'");
if (e.getIcon() != null)
sb.append(" icon: '").append(e.getIcon()).append("'");
return sb.toString();
}
@Override
public TextureRegion getCellImage(Verb e) {
boolean custom = true;
String verbName = e.getId();
for (String v : VERBS) {
if (v.equals(verbName)) {
custom = false;
break;
}
}
String iconName = MessageFormat.format("ic_{0}", e.getId());
TextureRegion image = null;
if (!custom)
image = Ctx.assetManager.getIcon(iconName);
else
image = Ctx.assetManager.getIcon("ic_custom");
return image;
}
@Override
protected boolean hasSubtitle() {
return true;
}
@Override
protected boolean hasImage() {
return true;
}
};
}
| bladecoder/bladecoder-adventure-engine | adventure-editor/src/main/java/com/bladecoder/engineeditor/ui/VerbList.java | Java | apache-2.0 | 8,958 |
package cobar.client.demo.test;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Random;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import cobar.client.demo.model.User;
import cobar.client.demo.service.UserService;
@ContextConfiguration(locations={"classpath:applicationContext-jndi.xml"})
public class JndiTest extends BaseTest{
@Resource
private UserService userService;
@BeforeClass
public static void initDataSources() throws RemoteException, NamingException {
LocateRegistry.createRegistry(1099);
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
System.setProperty(Context.PROVIDER_URL, "rmi://localhost:1099");
InitialContext context0 = new InitialContext();
Reference ref0 = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory", null);
ref0.add(new StringRefAddr("driverClassName", "oracle.jdbc.driver.OracleDriver"));
ref0.add(new StringRefAddr("url", "jdbc:oracle:thin:@localhost:1521/xe"));
ref0.add(new StringRefAddr("username", "dbtest1"));
ref0.add(new StringRefAddr("password", "root"));
context0.rebind("jdbc/dbtest1", ref0);
context0.close();
InitialContext context1 = new InitialContext();
Reference ref1 = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory", null);
ref1.add(new StringRefAddr("driverClassName", "oracle.jdbc.driver.OracleDriver"));
ref1.add(new StringRefAddr("url", "jdbc:oracle:thin:@localhost:1521/xe"));
ref1.add(new StringRefAddr("username", "dbtest2"));
ref1.add(new StringRefAddr("password", "root"));
context1.rebind("jdbc/dbtest2", ref1);
context1.close();
InitialContext context2 = new InitialContext();
Reference ref2 = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory", null);
ref2.add(new StringRefAddr("driverClassName", "oracle.jdbc.driver.OracleDriver"));
ref2.add(new StringRefAddr("url", "jdbc:oracle:thin:@localhost:1521/xe"));
ref2.add(new StringRefAddr("username", "dbtest3"));
ref2.add(new StringRefAddr("password", "root"));
context2.rebind("jdbc/dbtest3", ref2);
context2.close();
}
@Test
public void testAdd() throws Exception {
User user = new User();
Long id = new Long(new Random().nextInt(10000));
user.setId(id);
logger.info("id : {}",id);
user.setName("Tom");
Long taobaoId = id;
user.setTaobaoId(taobaoId);
userService.addUser(user);
}
@Test
public void testGetUserBykey() throws Exception{
User user = new User();
user.setId(7658L);
User user2 = userService.getUserByKey(user);
logger.info(user2.toString());
}
}
| lizwmaster/cobar-client-demo | cobar-client-demo/src/test/java/cobar/client/demo/test/JndiTest.java | Java | apache-2.0 | 3,044 |
/*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]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 com.helger.commons.typeconvert;
import javax.annotation.Nonnull;
import com.helger.commons.state.EContinue;
/**
* A callback interface that is used in several places of the type conversion
* engine.
*
* @author Philip Helger
*/
@FunctionalInterface
public interface ITypeConverterCallback
{
@Nonnull
EContinue call (@Nonnull Class <?> aSrcClass, @Nonnull Class <?> aDstClass, @Nonnull ITypeConverter <?, ?> aConverter);
}
| phax/ph-commons | ph-commons/src/main/java/com/helger/commons/typeconvert/ITypeConverterCallback.java | Java | apache-2.0 | 1,097 |
/*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spring.pubsub.core.health;
import static com.google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView.FULL;
import com.google.cloud.monitoring.v3.MetricServiceClient;
import com.google.monitoring.v3.ListTimeSeriesResponse;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.monitoring.v3.TimeSeries;
import com.google.protobuf.util.Timestamps;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
/**
* Health tracker for a Pub/Sub subscription. The tracker will monitor messages being processed and
* the subscription's message backlog. If backlog message size exceeds the message backlog
* threshold, the tracker will return the number of messages over the threshold.
*
* @since 2.0.6
*/
public class HealthTrackerImpl implements HealthTracker {
private static final int SECOND_IN_MILLIS = 1000;
private static final long NO_MESSAGES_OVER_THRESHOLD = 0L;
private final ProjectSubscriptionName projectSubscriptionName;
private final MetricServiceClient metricServiceClient;
private final String undeliveredFilter;
private final Integer lagThreshold;
private final Integer backlogThreshold;
private final Integer lookUpInternal;
private final AtomicLong processedAt = new AtomicLong(System.currentTimeMillis());
public HealthTrackerImpl(
ProjectSubscriptionName projectSubscriptionName,
MetricServiceClient metricServiceClient,
Integer lagThreshold,
Integer backlogThreshold,
Integer lookUpInterval) {
this.projectSubscriptionName = projectSubscriptionName;
this.metricServiceClient = metricServiceClient;
this.undeliveredFilter = undeliveredFilter(projectSubscriptionName.getSubscription());
this.lagThreshold = lagThreshold;
this.backlogThreshold = backlogThreshold;
this.lookUpInternal = lookUpInterval;
}
@Override
public void processedMessage() {
long newValue = System.currentTimeMillis();
long oldValue = processedAt.longValue();
while (oldValue < newValue) {
if (processedAt.compareAndSet(oldValue, newValue)) {
return;
} else {
oldValue = processedAt.longValue();
}
}
}
@Override
public ProjectSubscriptionName subscription() {
return projectSubscriptionName;
}
@Override
public long messagesOverThreshold() {
long currentMillis = System.currentTimeMillis();
if (hasNotExceedTimeThreshold(currentMillis)) {
return NO_MESSAGES_OVER_THRESHOLD;
}
Optional<Long> messagesOpt = getBackLogMessages(currentMillis);
if (!messagesOpt.isPresent()) {
return NO_MESSAGES_OVER_THRESHOLD;
}
long messageBackLog = messagesOpt.get();
return messageBackLog - backlogThreshold;
}
private boolean hasNotExceedTimeThreshold(long currentMillis) {
long elapsedMillis = currentMillis - processedAt.longValue();
long elapsedSeconds = elapsedMillis / SECOND_IN_MILLIS;
return elapsedSeconds < lagThreshold;
}
private Optional<Long> getBackLogMessages(long currentMillis) {
TimeInterval timeInterval = timeInterval(currentMillis);
ListTimeSeriesResponse timeSeriesResponse =
metricServiceClient
.listTimeSeries(
ProjectName.of(projectSubscriptionName.getProject()),
undeliveredFilter,
timeInterval,
FULL)
.getPage()
.getResponse();
if (timeSeriesResponse.getTimeSeriesCount() > 0) {
TimeSeries timeSeries = timeSeriesResponse.getTimeSeries(0);
if (timeSeries.getPointsCount() > 0) {
return Optional.of(timeSeries.getPoints(0).getValue().getInt64Value());
}
}
return Optional.empty();
}
private TimeInterval timeInterval(long currentMillis) {
TimeInterval timeInterval;
timeInterval =
TimeInterval.newBuilder()
.setStartTime(Timestamps.fromMillis(currentMillis - lookUpInternal * 60 * 1000))
.setEndTime(Timestamps.fromMillis(currentMillis))
.build();
return timeInterval;
}
}
| GoogleCloudPlatform/spring-cloud-gcp | spring-cloud-gcp-pubsub/src/main/java/com/google/cloud/spring/pubsub/core/health/HealthTrackerImpl.java | Java | apache-2.0 | 4,796 |
package com.me.diankun.firstcode.service;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* IntentService,在onHandleIntent()方法中自动开启一个线程处理耗时操作,操作结束后,自动调用stopSelf()
* <p/>
* 注意:无参的构造函数调用有参的父类构造函数
*/
public class MyIntentService extends IntentService {
private static final String TAG = MyIntentService.class.getSimpleName();
public MyIntentService() {
// 调用父类的有参构造函数
super("com.me.diankun.firstcode.service.MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "MyIntentService ThreadId = " + Thread.currentThread().getId());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
}
| qdiankun/firstcode | firstcode/chapter9_service/src/main/java/com/me/diankun/firstcode/service/MyIntentService.java | Java | apache-2.0 | 1,068 |
class Solution {
public:
int maximumGap(vector<int> &num) {
int size = num.size();
if (size < 2) {
return 0;
}
int maxVal = *max_element(num.begin(), num.end());
int minVal = *min_element(num.begin(), num.end());
int gap = (maxVal - minVal - 1) / (size - 1) + 1; // ceiling function
int bucketSize = (maxVal - minVal) / gap;
vector<int> minBucket(bucketSize, INT_MAX);
vector<int> maxBucket(bucketSize, INT_MIN);
for (int i = 0; i < size; i++) {
if (num[i] == minVal || num[i] == maxVal) {
continue;
}
int idx = (num[i] - minVal) / gap;
minBucket[idx] = min(minBucket[idx], num[i]);
maxBucket[idx] = max(maxBucket[idx], num[i]);
}
int maxGap = INT_MIN;
int prev = minVal;
for (int i = 0; i < bucketSize; i++) {
if (minBucket[i] != INT_MAX) {
maxGap = max(maxGap, minBucket[i] - prev);
prev = maxBucket[i];
}
}
maxGap = max(maxGap, maxVal - prev);
return maxGap;
}
};
| Jiacai/LeetCode | Maximum Gap.cpp | C++ | apache-2.0 | 1,155 |
package com.workshop.rest.error;
import java.util.List;
public interface UserService {
List<User> list();
long create(User user);
User get(long id) throws UserIsInactiveException;
void delete(long id);
}
| adko-pl/rest-workshop | error-handling/src/main/java/com/workshop/rest/error/UserService.java | Java | apache-2.0 | 225 |
jQuery(document).ready(function ($) {
var string_locator_search_active = false;
var add_notice = function( title, message, format ) {
$(".notices").append( '<div class="notice notice-' + format + ' is-dismissible"><p><strong>' + title + '</strong><br />' + message + '</p></div>' );
};
var throw_error = function( title, message ) {
string_locator_search_active = false;
$(".string-locator-feedback").hide();
add_notice( title, message, 'error' );
};
var finalize_string_locator_search = function() {
string_locator_search_active = false;
$("#string-locator-feedback-text").text('');
var search_finalized = {
action : 'string-locator-clean',
nonce : string_locator.search_nonce
};
$.post(
string_locator.ajax_url,
search_finalized,
function( response ) {
$(".string-locator-feedback").hide();
if ( $("tbody", ".tools_page_string-locator").is(":empty") ) {
$("tbody", ".tools_page_string-locator").html( '<tr><td colspan="3">' + string_locator.search_no_results + '</td></tr>' );
}
}
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
};
var clear_string_locator_result_area = function() {
$(".notices").html('');
$("#string-locator-search-progress").removeAttr( 'value' );
$("tbody", ".tools_page_string-locator").html('');
};
var perform_string_locator_single_search = function( maxCount, thisCount ) {
if ( thisCount >= maxCount || ! string_locator_search_active ) {
$("#string-locator-feedback-text").html( string_locator.saving_results_string );
finalize_string_locator_search();
return false;
}
var search_request = {
action : 'string-locator-search',
filenum : thisCount,
nonce : string_locator.search_nonce
};
$.post(
string_locator.ajax_url,
search_request,
function ( response ) {
console.dir( response)
if ( ! response.success ) {
add_notice( string_locator.warning_title, response.data, 'warning' );
}
if ( undefined !== response.data.search ) {
$("#string-locator-search-progress").val( response.data.filenum );
$("#string-locator-feedback-text").html( string_locator.search_current_prefix + response.data.next_file );
string_locator_append_result( response.data.search );
}
var nextCount = response.data.filenum + 1;
perform_string_locator_single_search( maxCount, nextCount );
},
'json'
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
};
var string_locator_append_result = function( total_entries ) {
if ( $(".no-items", ".tools_page_string-locator").is(':visible') ) {
$(".no-items", ".tools_page_string-locator").hide();
}
if ( Array !== total_entries.constructor ) {
return false;
}
total_entries.forEach( function ( entries ) {
if ( entries ) {
for (var i = 0, amount = entries.length; i < amount; i++) {
var entry = entries[i];
if (undefined !== entry.stringresult) {
var builtHTML = '<tr>' +
'<td>' + entry.stringresult + '<div class="row-actions"><span class="edit"><a href="' + entry.editurl + '" aria-label="Edit">Edit</a></span></div></td>' +
'<td>' + entry.filename + '</td>' +
'<td>' + entry.linenum + '</td>' +
'</tr>';
$("tbody", ".tools_page_string-locator").append(builtHTML);
}
}
}
} );
};
$("#string-locator-search-form").on( 'submit', function (e) {
e.preventDefault();
$("#string-locator-feedback-text").text(string_locator.search_preparing );
$(".string-locator-feedback").show();
string_locator_search_active = true;
clear_string_locator_result_area();
var directory_request = {
action : 'string-locator-get-directory-structure',
directory : $("#string-locator-search").val(),
search : $("#string-locator-string").val(),
regex : $("#string-locator-regex").is(':checked'),
nonce : string_locator.search_nonce
};
$("table.tools_page_string-locator").show();
$.post(
string_locator.ajax_url,
directory_request,
function ( response ) {
if ( ! response.success ) {
add_notice( response.data, 'alert' );
return;
}
$("#string-locator-search-progress").attr( 'max', response.data.total ).val( response.data.current );
$("#string-locator-feedback-text").text(string_locator.search_started );
perform_string_locator_single_search( response.data.total, 0 );
},
'json'
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
});
}); | vaughnick/fco | wp-content/plugins/string-locator/resources/js/string-locator-search.js | JavaScript | apache-2.0 | 5,728 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
// 需求:写一个程序,管理一个人的信息。
// 分析:数据-姓名,性别,年龄
// step 1:
var name = "张三";
var gender = "男";
var age = 23;
// step 2:
age += 1;
// step 3:
console.log(age);
</script>
</head>
<body>
</body>
</html> | H5C3JS/hxsd | 1606/三阶/week1/day01/test.html | HTML | apache-2.0 | 450 |
import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle, saveArticle, deleteArticle} from '../../../store/actions/Article.js';
import styles from './Main.less';
@connect(
state=> {
return {state: state.Article}
},
dispatch=>bindActionCreators({selectArticle, saveArticle, deleteArticle}, dispatch)
)
export default class ArticleMain extends Component {
static defaultProps = {};
static propTypes = {};
constructor (props) {
super(props);
};
componentWillMount () {
}
componentDidMount () {
}
shouldComponentUpdate () {
return true;
}
componentWillUpdate () {
}
componentDidUpdate () {
}
componentWillUnmount () {
}
render () {
let children = (() => {
if (this.props.state.selectIdx != -1) {
return <Detail data={this.props.state.select} save={this.props.saveArticle}
delete={this.props.deleteArticle}
saveing={this.props.state.saveing}
/>;
} else {
return <NoMatchImg/>;
}
})();
return (<div className={styles.Main}>
<MiddleArticleList/>
<RightDetail>
{children}
</RightDetail>
</div>);
}
} | yodfz/nblog | PC_client/views/manage/Article/Main.js | JavaScript | apache-2.0 | 1,605 |
#!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 3
# The hex encoded string:
# 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736
# has been XOR'd against a single character. Find the key, decrypt
# the message.
# Some of the 'magic' in this comes from a college crypto course
# That course used Stinson's Cryptography book, 3rd edition
from prob1 import hexToRaw, rawToHexLUT
from prob2 import hex_xor
import string
letterFrequency = {}
letterFrequency['A'] = .082;
letterFrequency['B'] = .015;
letterFrequency['C'] = .028;
letterFrequency['D'] = .043;
letterFrequency['E'] = .127;
letterFrequency['F'] = .022;
letterFrequency['G'] = .020;
letterFrequency['H'] = .061;
letterFrequency['I'] = .070;
letterFrequency['J'] = .002;
letterFrequency['K'] = .008;
letterFrequency['L'] = .040;
letterFrequency['M'] = .024;
letterFrequency['N'] = .067;
letterFrequency['O'] = .075;
letterFrequency['P'] = .019;
letterFrequency['Q'] = .001;
letterFrequency['R'] = .060;
letterFrequency['S'] = .063;
letterFrequency['T'] = .091;
letterFrequency['U'] = .028;
letterFrequency['V'] = .010;
letterFrequency['W'] = .023;
letterFrequency['X'] = .001;
letterFrequency['Y'] = .020;
letterFrequency['Z'] = .001;
letterFrequency[' '] = .200;
# See page 35, Stinson
def calculateMG(plain):
counts = [];
for i in range(256):
counts.append(0);
for i in range(len(plain)):
if (plain[i] < 128):
counts[ord(chr(plain[i]).upper())] += 1;
result = 0.0;
for i in string.ascii_uppercase:
result += letterFrequency[i]*counts[ord(i)];
result += letterFrequency[' '] * counts[ord(' ')];
result /= len(plain);
return result;
def tryKey(cipher, key):
fullkey = key * len(cipher);
fullkey = fullkey[:len(cipher)];
potential_plain = hex_xor(cipher, fullkey);
return calculateMG(hexToRaw(potential_plain)), potential_plain;
def findGoodKeys(cipher):
for i in range(256):
mg, plain = tryKey(cipher, rawToHexLUT[i]);
#print(str(i) + ": " + str(mg));
if (mg > .050):
print("potential key: 0x" + rawToHexLUT[i]);
print("Potential hex(plain): " + str(plain).lstrip("b'").rstrip("'"));
print("potential plaintext: " + str(hexToRaw(str(plain).lstrip("b'").rstrip("'"))).lstrip("b'").rstrip("'"));
if __name__ == "__main__":
cip = b'1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736';
findGoodKeys(cip);
| reschly/cryptopals | prob3.py | Python | apache-2.0 | 2,592 |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Set;
import com.gemstone.gemfire.internal.cache.EntryEventImpl;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.RegionEntry;
import com.gemstone.gemfire.internal.cache.TXStateProxy;
import com.gemstone.gnu.trove.THashMap;
import com.pivotal.gemfirexd.callbacks.Event;
import com.pivotal.gemfirexd.execute.CallbackStatement;
import com.pivotal.gemfirexd.internal.engine.access.index.OpenMemIndex;
import com.pivotal.gemfirexd.internal.engine.distributed.GfxdConnectionWrapper;
import com.pivotal.gemfirexd.internal.engine.distributed.message.StatementExecutorMessage;
import com.pivotal.gemfirexd.internal.engine.distributed.metadata.ComparisonQueryInfo;
import com.pivotal.gemfirexd.internal.engine.distributed.metadata.QueryInfo;
import com.pivotal.gemfirexd.internal.engine.distributed.metadata.SelectQueryInfo;
import com.pivotal.gemfirexd.internal.engine.distributed.metadata.SubQueryInfo;
import com.pivotal.gemfirexd.internal.engine.procedure.ProcedureChunkMessage;
import com.pivotal.gemfirexd.internal.engine.procedure.cohort.ProcedureSender;
import com.pivotal.gemfirexd.internal.engine.sql.conn.GfxdHeapThresholdListener;
import com.pivotal.gemfirexd.internal.engine.sql.execute.AbstractGemFireActivation;
import com.pivotal.gemfirexd.internal.engine.sql.execute.AbstractGemFireResultSet;
import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeIndexKey;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.engine.store.RowFormatter;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.sql.Activation;
import com.pivotal.gemfirexd.internal.iapi.sql.ParameterValueSet;
import com.pivotal.gemfirexd.internal.iapi.sql.ResultSet;
import com.pivotal.gemfirexd.internal.iapi.sql.conn.LanguageConnectionContext;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.TriggerDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.store.access.ColumnOrdering;
import com.pivotal.gemfirexd.internal.iapi.store.access.conglomerate.Conglomerate;
import com.pivotal.gemfirexd.internal.iapi.types.RowLocation;
import com.pivotal.gemfirexd.internal.impl.jdbc.EmbedPreparedStatement;
import com.pivotal.gemfirexd.internal.impl.jdbc.EmbedResultSet;
import com.pivotal.gemfirexd.internal.impl.jdbc.EmbedStatement;
import com.pivotal.gemfirexd.internal.impl.sql.GenericParameterValueSet;
import com.pivotal.gemfirexd.internal.impl.sql.GenericPreparedStatement;
import com.pivotal.gemfirexd.internal.impl.sql.StatementStats;
import com.pivotal.gemfirexd.internal.impl.sql.compile.FromBaseTable;
import com.pivotal.gemfirexd.internal.impl.sql.compile.SelectNode;
import com.pivotal.gemfirexd.internal.impl.sql.compile.StatementNode;
import com.pivotal.gemfirexd.internal.impl.sql.rules.ExecutionEngineRule;
@SuppressWarnings("serial")
public class GemFireXDQueryObserverAdapter implements GemFireXDQueryObserver,
Serializable {
@Override
public void afterQueryParsing(String query, StatementNode qt,
LanguageConnectionContext lcc) {
}
@Override
public void beforeOptimizedParsedTree(String query, StatementNode qt,
LanguageConnectionContext lcc) {
}
@Override
public void afterOptimizedParsedTree(String query, StatementNode qt,
LanguageConnectionContext lcc) {
}
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo,
GenericPreparedStatement gps, LanguageConnectionContext lcc) {
}
@Override
public void queryInfoObjectAfterPreparedStatementCompletion(QueryInfo qInfo,
GenericPreparedStatement gps, LanguageConnectionContext lcc) {
}
@Override
public void subQueryInfoObjectFromOptmizedParsedTree(
List<SubQueryInfo> qInfoList, GenericPreparedStatement gps,
LanguageConnectionContext lcc) {
}
@Override
public void beforeQueryExecution(EmbedStatement stmt, Activation activation)
throws SQLException {
}
@Override
public PreparedStatement afterQueryPrepareFailure(Connection conn,
String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability, int autoGeneratedKeys, int[] columnIndexes,
String[] columnNames, SQLException sqle) throws SQLException {
return null;
}
@Override
public boolean afterQueryExecution(CallbackStatement stmt, SQLException sqle)
throws SQLException {
return false;
}
@Override
public void beforeBatchQueryExecution(EmbedStatement stmt, int batchSize)
throws SQLException {
}
@Override
public void afterBatchQueryExecution(EmbedStatement stmt, int batchSize) {
}
@Override
public void beforeQueryExecution(GenericPreparedStatement stmt,
LanguageConnectionContext lcc) throws StandardException {
}
@Override
public void afterQueryExecution(GenericPreparedStatement stmt,
Activation activation) throws StandardException {
}
@Override
public void afterResultSetOpen(GenericPreparedStatement stmt,
LanguageConnectionContext lcc, ResultSet resultSet) {
}
@Override
public void onEmbedResultSetMovePosition(EmbedResultSet rs, ExecRow newRow,
ResultSet theResults) {
}
@Override
public void beforeGemFireActivationCreate(AbstractGemFireActivation ac) {
}
@Override
public void afterGemFireActivationCreate(AbstractGemFireActivation ac) {
}
@Override
public void beforeGemFireResultSetOpen(AbstractGemFireResultSet rs,
LanguageConnectionContext lcc) throws StandardException {
}
@Override
public void afterGemFireResultSetOpen(AbstractGemFireResultSet rs,
LanguageConnectionContext lcc) {
}
@Override
public void beforeGemFireResultSetExecuteOnActivation(
AbstractGemFireActivation activation) {
}
@Override
public void beforeComputeRoutingObjects(AbstractGemFireActivation activation) {
}
@Override
public void afterComputeRoutingObjects(AbstractGemFireActivation activation) {
}
@Override
public <T extends Serializable> void beforeQueryDistribution(
StatementExecutorMessage<T> executorMessage, boolean streaming) {
}
@Override
public <T extends Serializable> void afterQueryDistribution(
StatementExecutorMessage<T> executorMessage, boolean streaming) {
}
@Override
public void afterGemFireResultSetExecuteOnActivation(
AbstractGemFireActivation activation) {
}
@Override
public void beforeGemFireResultSetClose(AbstractGemFireResultSet rs,
String query) {
}
@Override
public void beforeEmbedResultSetClose(EmbedResultSet rs, String query) {
}
@Override
public void afterGemFireResultSetClose(AbstractGemFireResultSet rs,
String query) {
}
@Override
public void beforeResultHolderExecution(GfxdConnectionWrapper wrapper,
EmbedStatement es) {
}
@Override
public void beforeResultHolderIteration(GfxdConnectionWrapper wrapper,
EmbedStatement es) {
}
@Override
public void afterResultHolderIteration(GfxdConnectionWrapper wrapper,
EmbedStatement es) {
}
@Override
public void beforeResultHolderSerialization(GfxdConnectionWrapper wrapper,
EmbedStatement es) {
}
@Override
public void afterResultHolderSerialization(GfxdConnectionWrapper wrapper,
EmbedStatement es) {
}
@Override
public void afterResultHolderExecution(GfxdConnectionWrapper wrapper,
EmbedStatement es, String query) {
}
@Override
public void beforeResultSetHolderRowRead(RowFormatter rf, Activation act) {
}
@Override
public void afterResultSetHolderRowRead(RowFormatter rf, ExecRow row,
Activation act) {
}
@Override
public void beforeQueryExecutionByStatementQueryExecutor(
GfxdConnectionWrapper wrapper, EmbedStatement stmt, String query) {
}
@Override
public void afterQueryExecutionByStatementQueryExecutor(
GfxdConnectionWrapper wrapper, EmbedStatement stmt, String query) {
}
@Override
public void beforeQueryExecutionByPrepStatementQueryExecutor(
GfxdConnectionWrapper wrapper, EmbedPreparedStatement pstmt, String query) {
}
@Override
public void afterQueryExecutionByPrepStatementQueryExecutor(
GfxdConnectionWrapper wrapper, EmbedPreparedStatement pstmt, String query) {
}
@Override
public void beforeQueryReprepare(GenericPreparedStatement gpst,
LanguageConnectionContext lcc) throws StandardException {
}
@Override
public void createdGemFireXDResultSet(ResultSet rs) {
}
@Override
public void beforeIndexUpdatesAtRegionLevel(LocalRegion owner,
EntryEventImpl event, RegionEntry entry) {
}
@Override
public void beforeForeignKeyConstraintCheckAtRegionLevel() {
}
@Override
public void beforeUniqueConstraintCheckAtRegionLevel() {
}
@Override
public void beforeGlobalIndexLookup(LanguageConnectionContext lcc,
PartitionedRegion indexRegion, Serializable indexKey) {
}
@Override
public void afterGlobalIndexLookup(LanguageConnectionContext lcc,
PartitionedRegion indexRegion, Serializable indexKey, Object result) {
}
@Override
public void scanControllerOpened(Object sc, Conglomerate conglom) {
}
@Override
public void beforeConnectionCloseByExecutorFunction(long[] connectionIDs) {
}
@Override
public void afterConnectionCloseByExecutorFunction(long[] connectionIDs) {
}
@Override
public void afterConnectionClose(Connection conn) {
}
@Override
public void beforeORM(Activation activation, AbstractGemFireResultSet rs) {
}
@Override
public void afterORM(Activation activation, AbstractGemFireResultSet rs) {
}
@Override
public double overrideDerbyOptimizerIndexUsageCostForHash1IndexScan(
OpenMemIndex memIndex, double optimzerEvalutatedCost) {
return optimzerEvalutatedCost;
}
@Override
public double overrideDerbyOptimizerCostForMemHeapScan(
GemFireContainer gfContainer, double optimzerEvalutatedCost) {
return optimzerEvalutatedCost;
}
@Override
public double overrideDerbyOptimizerIndexUsageCostForSortedIndexScan(
OpenMemIndex memIndex, double optimzerEvalutatedCost) {
return optimzerEvalutatedCost;
}
@Override
public void criticalUpMemoryEvent(GfxdHeapThresholdListener listener) {
}
@Override
public void criticalDownMemoryEvent(GfxdHeapThresholdListener listener) {
}
@Override
public void estimatingMemoryUsage(String stmtText, Object resultSet) {
}
@Override
public long estimatedMemoryUsage(String stmtText, long memused) {
return memused;
}
@Override
public void putAllCalledWithMapSize(int size) {
}
@Override
public void afterBulkOpDBSynchExecution(Event.Type type, int numRowsModified,
Statement ps, String dml) {
}
@Override
public void afterPKBasedDBSynchExecution(Event.Type type,
int numRowsModified, Statement ps) {
}
@Override
public void afterCommitDBSynchExecution(List<Event> batchProcessed) {
}
@Override
public void afterCommit(Connection conn) {
}
@Override
public void afterRollback(Connection conn) {
}
@Override
public void afterClosingWrapperPreparedStatement(long wrapperPrepStatementID,
long wrapperConnectionID) {
}
@Override
public void updatingColocationCriteria(ComparisonQueryInfo cqi) {
}
@Override
public void statementStatsBeforeExecutingStatement(StatementStats stats) {
}
@Override
public void reset() {
}
@Override
public void close() {
}
@Override
public void subqueryNodeProcessedData(SelectQueryInfo qInfo,
GenericPreparedStatement gps, String subquery,
List<Integer> paramPositions) {
}
@Override
public void insertMultipleRowsBeingInvoked(int numElements) {
}
@Override
public void keyAndContainerAfterLocalIndexInsert(Object key,
Object rowLocation, GemFireContainer container) {
}
@Override
public void keyAndContainerAfterLocalIndexDelete(Object key,
Object rowLocation, GemFireContainer container) {
}
@Override
public void keyAndContainerBeforeLocalIndexDelete(Object key,
Object rowLocation, GemFireContainer container) {
}
@Override
public void getAllInvoked(int numKeys) {
}
@Override
public void getAllGlobalIndexInvoked(int numKeys) {
}
@Override
public void getAllLocalIndexInvoked(int numKeys) {
}
@Override
public void getAllLocalIndexExecuted() {
}
@Override
public void ncjPullResultSetOpenCoreInvoked() {
}
@Override
public void getStatementIDs(long stID, long rootID, int stLevel) {
}
@Override
public void ncjPullResultSetVerifyBatchSize(int value) {
}
@Override
public void ncjPullResultSetVerifyCacheSize(int value) {
}
@Override
public void ncjPullResultSetVerifyVarInList(boolean value) {
}
@Override
public void independentSubqueryResultsetFetched(Activation activation,
ResultSet results) {
}
@Override
public void beforeInvokingContainerGetTxRowLocation(RowLocation regionEntry) {
}
@Override
public void afterGetRoutingObject(Object routingObject) {
}
@Override
public long overrideUniqueID(long actualUniqueID, boolean forRegionKey) {
return actualUniqueID;
}
@Override
public boolean beforeProcedureResultSetSend(ProcedureSender sender,
EmbedResultSet rs) {
return true;
}
@Override
public boolean beforeProcedureOutParamsSend(ProcedureSender sender,
ParameterValueSet pvs) {
return true;
}
@Override
public void beforeProcedureChunkMessageSend(ProcedureChunkMessage message) {
}
@Override
public void lockingRowForTX(TXStateProxy tx, GemFireContainer container,
RegionEntry entry, boolean writeLock) {
}
@Override
public void attachingKeyInfoForUpdate(GemFireContainer container,
RegionEntry entry) {
}
@Override
public int overrideSortBufferSize(ColumnOrdering[] columnOrdering,
int sortBufferMax) {
return sortBufferMax;
}
@Override
public boolean avoidMergeRuns() {
return true;
}
@Override
public void callAtOldValueSameAsNewValueCheckInSM2IIOp() {
}
@Override
public void onGetNextRowCore(ResultSet resultSet) {
}
@Override
public void onGetNextRowCoreOfBulkTableScan(ResultSet resultSet) {
}
@Override
public void onGetNextRowCoreOfGfxdSubQueryResultSet(ResultSet resultSet) {
}
@Override
public void onDeleteResultSetOpen(ResultSet resultSet) {
}
@Override
public void onSortResultSetOpen(ResultSet resultSet) {
}
@Override
public void onGroupedAggregateResultSetOpen(ResultSet resultSet) {
}
@Override
public void onDeleteResultSetOpenBeforeRefChecks(ResultSet resultSet) {
}
@Override
public void onDeleteResultSetOpenAfterRefChecks(ResultSet resultSet) {
}
@Override
public void setRoutingObjectsBeforeExecution(
final Set<Object> routingKeysToExecute) {
}
@Override
public void beforeDropGatewayReceiver() {
}
@Override
public void beforeDropDiskStore() {
}
@Override
public void memberConnectionAuthenticationSkipped(boolean skipped) {
}
@Override
public void userConnectionAuthenticationSkipped(boolean skipped) {
}
@Override
public void regionSizeOptimizationTriggered(FromBaseTable fbt,
SelectNode selectNode) {
}
@Override
public void regionSizeOptimizationTriggered2(SelectNode selectNode) {
}
@Override
public void beforeFlushBatch(ResultSet rs, LanguageConnectionContext lcc)
throws StandardException {
}
@Override
public void afterFlushBatch(ResultSet rs, LanguageConnectionContext lcc)
throws StandardException {
}
@Override
public void invokeCacheCloseAtMultipleInsert() {
}
public boolean isCacheClosedForTesting() {
return false;
}
@Override
public void afterGlobalIndexInsert(boolean possDup) {
}
@Override
public boolean needIndexRecoveryAccounting() {
return false;
}
@Override
public void setIndexRecoveryAccountingMap(THashMap map) {
}
@Override
public boolean throwPutAllPartialException() {
return false;
}
@Override
public void afterIndexRowRequalification(Boolean success,
CompactCompositeIndexKey ccKey, ExecRow row, Activation activation) {
}
@Override
public void beforeRowTrigger(LanguageConnectionContext lcc, ExecRow execRow,
ExecRow newRow) {
}
@Override
public void afterRowTrigger(TriggerDescriptor trigD,
GenericParameterValueSet gpvs) {
}
@Override
public void beforeGlobalIndexDelete() {
}
@Override
public void onUpdateResultSetOpen(ResultSet resultSet) {
}
@Override
public void beforeDeferredUpdate() {
}
@Override
public void beforeDeferredDelete() {
}
@Override
public void onUpdateResultSetDoneUpdate(ResultSet resultSet) {
}
@Override
public void bucketIdcalculated(int bid) {
}
@Override
public void afterPuttingInCached(Serializable globalIndexKey, Object result) {
}
@Override
public void beforeReturningCachedVal(Serializable globalIndexKey,
Object cachedVal) {
}
@Override
public void afterSingleRowInsert(Object routingObj) {
}
@Override
public void afterQueryPlanGeneration() {
}
@Override
public void afterLockingTableDuringImport() {
}
@Override
public boolean testIndexRecreate() {
return false;
}
@Override
public void testExecutionEngineDecision(QueryInfo queryInfo,
ExecutionEngineRule.ExecutionEngine engine, String queryText) {
}
public void regionPreInitialized(GemFireContainer container) {
}
}
| SnappyDataInc/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/engine/GemFireXDQueryObserverAdapter.java | Java | apache-2.0 | 18,602 |
package com.apsolete.machinery.common;
public interface OnResultListener<T> extends OnProgressListener
{
void onResult(T result);
void onCompleted(int count);
}
| apsolete/Machinery | app/src/main/java/com/apsolete/machinery/common/OnResultListener.java | Java | apache-2.0 | 170 |
#! /bin/sh
tinyproxy start
# do nothing, just wait
while true; do sleep 1000; done
| newnius/Dockerfiles | tinyproxy/bootstrap.sh | Shell | apache-2.0 | 86 |
<?php
function sanitizestring($var)
{
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
function sanitizemySQL($connection, $var)
{
$var = $connection->real_escape_string($var);
$var = sanitizeString($var);
return $var;
}
?> | Robengelbert/Prework | sanitize.php | PHP | apache-2.0 | 276 |
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sprintapi.api.http.header.adapter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.sprintapi.api.http.header.adapter.accept.HttpAcceptAdapter;
import org.sprintapi.api.http.lang.HttpLexScanner;
import org.sprintapi.api.meta.type.Accept;
import org.sprintapi.api.meta.type.MediaType;
public class HttpAcceptHeaderAdapterTest {
@Test
public void testRead1() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("audio/*; q=0.2, audio/basic"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(2, a.getItems().length);
assertNotNull(a.getItems()[0]);
assertNotNull(a.getItems()[0].getRange());
assertEquals("audio", a.getItems()[0].getRange().getType());
assertEquals("basic", a.getItems()[0].getRange().getSubtype());
assertNull(a.getItems()[1].getRange().getParameters());
assertEquals(1f, a.getItems()[0].getQualityFactor(), 0);
assertNotNull(a.getItems()[1]);
assertNotNull(a.getItems()[1].getRange());
assertEquals("audio", a.getItems()[1].getRange().getType());
assertEquals("*", a.getItems()[1].getRange().getSubtype());
assertNull(a.getItems()[1].getRange().getParameters());
assertEquals(0.2f, a.getItems()[1].getQualityFactor(), 0);
}
@Test
public void testRead2() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(4, a.getItems().length);
assertNotNull(a.getItems()[0]);
assertNotNull(a.getItems()[0].getRange());
assertEquals("text", a.getItems()[0].getRange().getType());
assertEquals("html", a.getItems()[0].getRange().getSubtype());
assertNull(a.getItems()[0].getRange().getParameters());
assertEquals(1f, a.getItems()[0].getQualityFactor(), 0);
assertNotNull(a.getItems()[1]);
assertNotNull(a.getItems()[1].getRange());
assertEquals("text", a.getItems()[1].getRange().getType());
assertEquals("x-c", a.getItems()[1].getRange().getSubtype());
assertNull(a.getItems()[1].getRange().getParameters());
assertEquals(1f, a.getItems()[1].getQualityFactor(), 0);
assertNotNull(a.getItems()[2]);
assertNotNull(a.getItems()[2].getRange());
assertEquals("text", a.getItems()[2].getRange().getType());
assertEquals("x-dvi", a.getItems()[2].getRange().getSubtype());
assertNull(a.getItems()[2].getRange().getParameters());
assertEquals(0.8f, a.getItems()[2].getQualityFactor(), 0);
assertNotNull(a.getItems()[3]);
assertNotNull(a.getItems()[3].getRange());
assertEquals("text", a.getItems()[3].getRange().getType());
assertEquals("plain", a.getItems()[3].getRange().getSubtype());
assertNull(a.getItems()[3].getRange().getParameters());
assertEquals(0.5f, a.getItems()[3].getQualityFactor(), 0);
}
@Test
public void testRead3() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/*, text/html, text/html;level=1, */*"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(4, a.getItems().length);
}
@Test
public void testRead4() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(5, a.getItems().length);
}
@Test
public void testRead5() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(4, a.getItems().length);
}
@Test
public void testRead6() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("application/xml,application/xhtml+xml,text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(6, a.getItems().length);
}
@Test
public void testRead7() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("image/jpeg, application/x-ms-application, image/gif,application/xaml+xml, image/pjpeg, application/x-ms-xbap,application/x-shockwave-flash, application/msword, */*"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(9, a.getItems().length);
}
@Test
public void testRead8() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/x-silverlight-2-b2, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(10, a.getItems().length);
}
@Test
public void testRead9() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/plain"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(1, a.getItems().length);
}
@Test
public void testRead10() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("application/json, application/xml"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(2, a.getItems().length);
}
@Test
public void testAccept() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("application/vnd.x+json, application/xml; q=0.5, application/json"), null);
assertNotNull(a);
assertEquals(3, a.accept(new MediaType("application", "vnd.x+json")));
assertEquals(2, a.accept(new MediaType("application", "json")));
assertEquals(1, a.accept(new MediaType("application", "xml")));
assertEquals(0, a.accept(new MediaType("text", "html")));
}
@Test
public void testReadHuge() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner(
"text/plain ; q = 0\n"
+ " .1\n"
+ " ,,,,\n"
+ " ,,\n"
+ " ,,, ,,,\n"
+ " ,,, ,,,\n"
+ " ,,,,,,,,\n"
+ " ,,,,\n"
+ " ,,\n"
+ " text/* ; q =\n"
+ " 1 . 00"
), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(2, a.getItems().length);
assertNotNull(a.getItems()[0]);
assertNotNull(a.getItems()[0].getRange());
assertEquals("text", a.getItems()[0].getRange().getType());
assertEquals("*", a.getItems()[0].getRange().getSubtype());
assertNull(a.getItems()[0].getRange().getParameters());
assertEquals(1f, a.getItems()[0].getQualityFactor(), 0);
assertNotNull(a.getItems()[1]);
assertNotNull(a.getItems()[1].getRange());
assertEquals("text", a.getItems()[1].getRange().getType());
assertEquals("plain", a.getItems()[1].getRange().getSubtype());
assertNull(a.getItems()[1].getRange().getParameters());
assertEquals(0.1f, a.getItems()[1].getQualityFactor(), 0);
}
@Test
public void testEmptyList() {
Accept a = HttpAcceptAdapter.read(new HttpLexScanner("text/plain,,,,image/*"), null);
assertNotNull(a);
assertNotNull(a.getItems());
assertEquals(2, a.getItems().length);
assertNotNull(a.getItems()[0]);
assertNotNull(a.getItems()[0].getRange());
assertEquals("text", a.getItems()[0].getRange().getType());
assertEquals("plain", a.getItems()[0].getRange().getSubtype());
assertNull(a.getItems()[0].getRange().getParameters());
assertEquals(1f, a.getItems()[0].getQualityFactor(), 0);
assertNotNull(a.getItems()[1]);
assertNotNull(a.getItems()[1].getRange());
assertEquals("image", a.getItems()[1].getRange().getType());
assertEquals("*", a.getItems()[1].getRange().getSubtype());
assertNull(a.getItems()[1].getRange().getParameters());
assertEquals(1f, a.getItems()[1].getQualityFactor(), 0);
}
}
| filip26/api-machine | src/test/java/org/sprintapi/api/http/header/adapter/HttpAcceptHeaderAdapterTest.java | Java | apache-2.0 | 8,377 |
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using Microsoft.Xaml.Behaviors;
namespace Cube.Xui.Behaviors
{
/* --------------------------------------------------------------------- */
///
/// WindowsFormsBehavior
///
/// <summary>
/// Provides functionality to apply behaviors to WinForms components.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class WindowsFormsBehavior<TControl> : Behavior<WindowsFormsHost>
where TControl : Control
{
#region Properties
/* ----------------------------------------------------------------- */
///
/// Source
///
/// <summary>
/// Gets the source control.
/// </summary>
///
/* ----------------------------------------------------------------- */
public TControl Source => AssociatedObject?.Child as TControl;
/* ----------------------------------------------------------------- */
///
/// Parent
///
/// <summary>
/// Gets the parecont control of the source.
/// </summary>
///
/* ----------------------------------------------------------------- */
public WindowsFormsHost Parent => AssociatedObject;
#endregion
}
}
| cube-soft/Cube.Core | Libraries/Xui/Sources/Behaviors/WindowsFormsBehavior.cs | C# | apache-2.0 | 2,131 |
/*
* Copyright 2017-2022 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.kinesisvideo.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kinesisvideo.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UntagStreamResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UntagStreamResultJsonUnmarshaller implements Unmarshaller<UntagStreamResult, JsonUnmarshallerContext> {
public UntagStreamResult unmarshall(JsonUnmarshallerContext context) throws Exception {
UntagStreamResult untagStreamResult = new UntagStreamResult();
return untagStreamResult;
}
private static UntagStreamResultJsonUnmarshaller instance;
public static UntagStreamResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UntagStreamResultJsonUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/transform/UntagStreamResultJsonUnmarshaller.java | Java | apache-2.0 | 1,589 |
project_path: /web/tools/chrome-devtools/_project.yaml
book_path: /web/tools/chrome-devtools/_book.yaml
description:Chrome DevTools でコードを一時停止するために使用できるすべての方法を説明します。
{# wf_updated_on: 2020-07-10 #}
{# wf_published_on: 2017-02-03 #}
{# wf_blink_components: Platform>DevTools #}
{% include "web/tools/chrome-devtools/_shared/styles.html" %}
# ブレークポイントでコードを一時停止する {: .page-title }
{% include "web/_shared/contributors/kaycebasques.html" %}
JavaScript コードを一時停止するにはブレークポイントを使用します。 このガイドでは、DevTools で使用可能なブレークポイントの種類と、それらを使用するタイミングおよび設定する方法について説明します。
デバッグ プロセスのハンズオン チュートリアルは、[Chrome DevTools で JavaScript をデバッグする](/web/tools/chrome-devtools/javascript/)をご覧ください。
## 各種ブレークポイントを使用するタイミングの概要 {: #overview }
最もよく知られているブレークポイントはコード行(line-of-code)のブレークポイントです。 しかし、バグの場所が厳密にはわからない場合や作業するコードベースが非常に大きい場合は特に、コード行ブレークポイントを効率的に設定できないこともあります。
そのような場合、他の種類のブレークポイントをいつどのように使えばよいかを知っていれば、自分が行うデバッグ作業の時間を節約できます。
<table>
<tr><th>ブレークポイントの種類</th><th>使用に適した一時停止の対象...</th></tr>
<tr>
<td><a href="#loc">コード行</a></td>
<td>
厳密なコード部分。
</td>
</tr>
<tr>
<td><a href="#conditional-loc">条件付きコード行</a></td>
<td>
厳密なコード部分、ただし他の何らかの条件が真であるときに限る。
</td>
</tr>
<tr>
<td><a href="#dom">DOM</a></td>
<td>
特定の DOM ノードまたはその子を変更または削除するコード。
</td>
</tr>
<tr>
<td><a href="#xhr">XHR</a></td>
<td>
指定する文字列パターンが XHR URL に含まれる場合。
</td>
</tr>
<tr>
<td><a href="#event-listeners">イベント リスナー</a></td>
<td>
<code>click</code> などのイベントが発生した後に実行されるコード。
</td>
</tr>
<tr>
<td><a href="#exceptions">例外</a></td>
<td>
捕捉された例外または捕捉されていない例外をスローするコード行。
</td>
</tr>
<tr>
<td><a href="#function">関数</a></td>
<td>
特定の関数が呼び出されるあらゆる場合。
</td>
</tr>
</table>
## コード行ブレークポイント {: #loc }
コード行ブレークポイントは、調査が必要な厳密なコード部分がわかっている場合に使用します。
DevTools はこのコード行が実行される前に*必ず*一時停止します。
DevTools でコード行ブレークポイントを設定する手順は、次のとおりです。
1. **[Sources]** タブをクリックします。
1. ブレークポイントを配置する対象のコード行を含むファイルを開きます。
1. 対象のコード行に移動します。
1. コード行の左側に行番号列があります。 その列をクリックします。 行番号列の上に青いアイコンが表示されます。
<figure>
<img src="imgs/loc-breakpoint.png"
alt="コード行ブレークポイント。"
<figcaption>
<b>図 1</b>: 行 <b>29</b> に設定したコード行ブレークポイント
</figcaption>
</figure>
### コード内のコード行ブレークポイント {: #debugger }
コードから `debugger` が呼び出されて、ブレークポイントが配置された行で一時停止します。 これは[コード行ブレークポイント](#loc)と同等ですが、ブレークポイントが DevTools UI 内ではなくコード内に設定されている点が異なります。
console.log('a');
console.log('b');
debugger;
console.log('c');
### 条件付きコード行ブレークポイント {: #conditional-loc }
条件付きコード行ブレークポイントは、調査が必要な厳密なコード部分はわかっているが、他の一定の条件が真である場合にのみ一時停止するという場合に使用します。
条件付きコード行ブレークポイントを設定する手順は、次のとおりです。
1. **[Sources]** タブをクリックします。
1. ブレークポイントを配置する対象のコード行を含むファイルを開きます。
1. 対象のコード行に移動します。
1. コード行の左側に行番号列があります。 その列を右クリックします。
1. **[Add conditional breakpoint]** を選択します。 コード行の下にダイアログが表示されます。
1. ダイアログに条件を入力します。
1. <kbd>Enter</kbd> を押してブレークポイントをアクティベートします。 行番号列の上にオレンジ色のアイコンが表示されます。
<figure>
<img src="imgs/conditional-loc-breakpoint.png"
alt=" 条件付きコード行ブレークポイント。"
<figcaption>
<b>図 2</b>: 行
<b>32</b> に設定した条件付きコード行ブレークポイント
</figcaption>
</figure>
### コード行ブレークポイントの管理 {: #manage-loc }
1 つの場所のコード行ブレークポイントを無効化または削除する場合は、**[Breakpoints]** ペインを使用します。
<figure>
<img src="imgs/breakpoints-pane.png"
alt="[Breakpoints] ペイン。"
<figcaption>
<b>図 3</b>: 2 つのコード行ブレークポイントが表示された <b>[Breakpoints]</b> ペイン。<code>get-started.js</code> の 15 行目と 32 行目にブレークポイントが配置されている
</figcaption>
</figure>
* 無効にするブレークポイントのエントリーの横にあるチェックボックスにチェックを入れます。
* そのブレークポイントを削除する場合は、エントリー上で右クリックします。
* すべてのブレークポイントを非アクティベートする、すべてのブレークポイントを無効にする、またはすべてのブレークポイントを削除する場合は、**[Breakpoints]** ペインの任意の場所で右クリックします。
すべてのブレークポイントを無効にすることは、ブレークポイントのチェックを一つ一つすべて解除することに相当します。
すべてのブレークポイントを非アクティベートすると、すべてのコード行ブレークポイントを無視し、それらのブレークポイントが有効である状態は維持するよう DevTools に指示するため、再アクティベートしたときには以前と同じ状態が復元されます。
<figure>
<img src="imgs/deactivated-breakpoints.png"
alt="[Breakpoints] ペインで非アクティベートされたブレークポイント。"
<figcaption>
<b>図 4</b>: <b>[Breakpoints]</b> ペインで非アクティベートされたブレークポイントは無効になっており、半透明で表示されている
</figcaption>
</figure>
## DOM 変更ブレークポイント {: #dom }
DOM ノードまたはその子を変更するコードで一時停止するときは、DOM 変更ブレークポイントを使用します。
DOM 変更ブレークポイントを設定する手順は、次のとおりです。
1. **[Elements]** タブをクリックします。
1. ブレークポイントを設定する要素に移動します。
1. その要素を右クリックします。
1. **[Break on]** の上にマウスポインターを移動し、**[Subtree modifications]**、**[Attribute modifications]**、または **[Node removal]** を選択します。
<figure>
<img src="imgs/dom-change-breakpoint.png"
alt="DOM 変更ブレークポイントの作成時に表示されるコンテキスト メニュー。"
<figcaption>
<b>図 5</b>: DOM 変更ブレークポイントの作成時に表示されるコンテキスト メニュー
</figcaption>
</figure>
### DOM 変更ブレークポイントの種類 {: #dom-types }
* **[Subtree modifications]**: 現在選択されているノードの子が削除、追加、または子の内容が変更されたときにトリガーされます。
子ノードの属性が変更された場合、または現在選択されているノードが変更された場合はトリガーされません。
* **[Attributes modifications]**:現在選択されているノードに対して属性が追加または削除された場合、あるいは属性値が変更された場合にトリガーされます。
* **[Node Removal]**:現在選択されているノードが削除された場合にトリガーされます。
## XHR/Fetch ブレークポイント {: #xhr }
XHR ブレークポイントは、指定された文字列が XHR のリクエスト URL に含まれているときに一時停止する場合に使用します。
DevTools は、XHR が `send()` を呼び出す箇所でコード行を一時停止します。
注: この機能は [Fetch][Fetch] リクエストとも連携します。
この連携が便利な例は、ページがリクエストしている URL が間違っていて、間違ったリクエストの原因となっている AJAX または Fetch ソースコードをその場で確認したいという場合です。
XHR ブレークポイントを設定する手順は、次のとおりです。
1. **[Sources]** タブをクリックします。
1. **[XHR Breakpoints]** ペインを展開します。
1. **[Add breakpoint]** をクリックします。
1. 出現時に一時停止する文字列を入力します。 DevTools は、この文字列が XHR のリクエスト URL に出現するすべての箇所で一時停止します。
1. <kbd>Enter</kbd> を押して確認します。
<figure>
<img src="imgs/xhr-breakpoint.png"
alt="XHR ブレークポイントの作成。"
<figcaption>
<b>図 6</b>: <b>[XHR Breakpoints]</b> での
URL に <code>org</code> を含むすべてのリクエストに対する XHR ブレークポイントの作成
</figcaption>
</figure>
[Fetch]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
## イベント リスナー ブレークポイント {: #event-listeners }
イベント リスナー ブレークポイントは、イベントが発生した後で実行されるイベント リスナーコードで一時停止する場合に使用します。
特定のイベント(`click` など)またイベントのカテゴリ(すべてのマウスイベントなど)を選択することができます。
1. **[Sources]** タブをクリックします。
1. **[Event Listener Breakpoints]** ペインを展開します。 DevTools に **[Animation]** といったイベント カテゴリのリストが表示されます。
1. 発生したら一時停止するイベントのカテゴリにチェックを入れるか、またはカテゴリを展開して特定のイベントにチェックを入れるかします。
<figure>
<img src="imgs/event-listener-breakpoint.png"
alt="イベント リスナー ブレークポイントの作成。"
<figcaption>
<b>図 7</b>: <code>deviceorientation</code> のイベント リスナー ブレークポイントの作成
</figcaption>
</figure>
## 例外ブレークポイント {: #exceptions }
例外ブレークポイントは、捕捉された例外または捕捉されていない例外をスローしているコード行で一時停止する場合に使用します。
1. **[Sources]** タブをクリックします。
1. **[Pause on exceptions]**  をクリックします{:.devtools-inline}。 有効になると青色に変わります。
1. (オプション) 捕捉されていないで例外に加えて捕捉された例外でも一時停止する場合は、**[Pause On Caught Exceptions]** チェックボックスにチェックを入れます。
<figure>
<img src="imgs/uncaught-exception.png"
alt="捕捉されていない例外で一時停止した状態。"
<figcaption>
<b>図 7</b>: 捕捉されていない例外で一時停止した状態
</figcaption>
</figure>
## 関数ブレークポイント {: #function }
特定の関数が呼び出されたあらゆる場合に一時停止するときに、`debug(functionName)` を呼び出します(`functionName` はデバッグする関数)。
`debug()` をコード内に挿入するか(`console.log()` ステートメントのように)または DevTools コンソールから呼び出すことができます。
`debug()` は、関数の最初の行に
[コード行ブレークポイント](#loc)を設定した場合に相当します。
function sum(a, b) {
let result = a + b; // DevTools pauses on this line.
return result;
}
debug(sum); // Pass the function object, not a string.
sum();
### 対象の関数がスコープ内にあるようにする {: #scope }
DevTools は、デバッグする関数がスコープ内にないと `ReferenceError` をスローします。
(function () {
function hey() {
console.log('hey');
}
function yo() {
console.log('yo');
}
debug(yo); // This works.
yo();
})();
debug(hey); // This doesn't work. hey() is out of scope.
`debug()` を DevTools コンソールから呼び出している場合、対象の関数がスコープ内にあるようにするには少しの手間が必要となります。
次のような方法をとることもできます。
1. その関数がスコープ内にある場所に[コード行ブレークポイント](#loc)を設定します。
1. ブレークポイントをトリガーします。
1. コートがコード行ブレークポイントで一時停止している間に、DevTools コンソールで `debug()` を呼び出します。
## フィードバック {: #feedback }
{% include "web/_shared/helpful.html" %}
| myakura/WebFundamentals | src/content/ja/tools/chrome-devtools/javascript/breakpoints.md | Markdown | apache-2.0 | 14,655 |
<?php
/*
* 3 Column River Acitivity
*
* @package ElggRiverDash
* Full Creadit goes to ELGG Core Team for creating a beautiful social networking script
*
* Modified by Satheesh PM, BARC, Mumbai, India..
* http://satheesh.anushaktinagar.net
*
* @author ColdTrick IT Solutions
* @copyright Coldtrick IT Solutions 2009
* @link http://www.coldtrick.com/
* @version 1.0
*
*/
$title = elgg_echo('river_activity_3C:horoscope');
$box_view = elgg_get_plugin_setting('view_riverbox', 'river_activity_3C');
$river_body = '<marquee direction="left" scrollamount="2" onmouseover="stop()" onmouseout="start()" style="overflow:hidden;"><iframe src="http://www.eastrolog.com/webmaster-new/daily-horoscope/webmaster-horoscope-1.php" name="Daily_Horoscopes_720x85" width="720" height="85" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" title="Daily Horoscopes 720x85"></iframe></marquee>';
echo elgg_view_module($box_view, $title, $river_body);
?> | Grupo15HxH/HxH | elgg/mod/river_activity_3C/views/default/page/elements/horoscope.php | PHP | apache-2.0 | 1,018 |
# Urochloa xantholeuca (Schinz) H.Scholz SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Brachiaria/Brachiaria xantholeuca/ Syn. Urochloa xantholeuca/README.md | Markdown | apache-2.0 | 195 |
# Cassia venatoria H.S.Irwin & Barneby SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Chamaecrista/Chamaecrista venatoria/ Syn. Cassia venatoria/README.md | Markdown | apache-2.0 | 193 |
# Werauhia acuminata (Mez & Wercklé) J.R.Grant SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Vriesea/Vriesea acuminata/ Syn. Werauhia acuminata/README.md | Markdown | apache-2.0 | 202 |
# Deutzia oaxacana Zaikonn. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Cornales/Hydrangeaceae/Deutzia/Deutzia oaxacana/README.md | Markdown | apache-2.0 | 175 |
# Colysis leveillei f. angusta (C. Chr.) Ching FORM
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Colysis/Colysis leveillei/ Syn. Colysis leveillei angusta/README.md | Markdown | apache-2.0 | 198 |
# Utricularia obtusa Sw. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lentibulariaceae/Utricularia/Utricularia gibba/ Syn. Utricularia obtusa/README.md | Markdown | apache-2.0 | 179 |
package org.awesky.attack.test;
/**
* Created by vme on 2017/8/29.
*/
public class AttackTest {
}
| Awesky/awe-awesomesky | awe-awesomesky-attack/src/test/java/org/awesky/attack/test/AttackTest.java | Java | apache-2.0 | 101 |
# Serratula indivisa Poir. ex DC. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Serratula/Serratula indivisa/README.md | Markdown | apache-2.0 | 181 |
# Castanopsis microcarpa Hu SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Castanopsis/Castanopsis fleuryi/ Syn. Castanopsis microcarpa/README.md | Markdown | apache-2.0 | 182 |
# Cassia afrofistula var. afrofistula VARIETY
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Cassia/Cassia afrofistula/Cassia afrofistula afrofistula/README.md | Markdown | apache-2.0 | 177 |
# Ophrestia upembae (Hauman) Verdc. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Ophrestia/Ophrestia upembae/README.md | Markdown | apache-2.0 | 191 |
# Marasmius cepistipes Henn. & E. Nyman SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Marasmius cepistipes Henn. & E. Nyman
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Marasmiaceae/Marasmius/Marasmius cepistipes/README.md | Markdown | apache-2.0 | 203 |
# Asperula nitida subsp. mytilinica SUBSPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Asperula/Asperula nitida/Asperula nitida mytilinica/README.md | Markdown | apache-2.0 | 194 |
# Fusulites D.O. Hemer & P.W. Nygreen, 1967 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Acritarcha/Fusulites/README.md | Markdown | apache-2.0 | 205 |
package com.twitter.inject.tests
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.inject.InMemoryStatsReceiverUtility
import com.twitter.inject.Test
import com.twitter.conversions.DurationOps._
import com.twitter.util.FuturePool
import org.scalatest.exceptions.TestFailedDueToTimeoutException
class InMemoryStatsReceiverUtilityTest extends Test {
test("InMemoryStatsReceiverUtility#waitFor will fail if the metric is the incorrect value") {
val inMemoryStatsReceiver = new InMemoryStatsReceiver
val statUtils = new InMemoryStatsReceiverUtility(inMemoryStatsReceiver)
// A short timeout is set because the metric will never reach the expected value
val timeout = 10.millis
inMemoryStatsReceiver.counter("counter").incr()
intercept[TestFailedDueToTimeoutException] {
statUtils.counters.waitFor("counter", 2, timeout)
}
inMemoryStatsReceiver.stats(Seq("stats")) = Seq(1.0f, 2.0f, 3.0f)
intercept[TestFailedDueToTimeoutException] {
statUtils.stats.waitFor("stats", Seq(1.0f), timeout)
}
inMemoryStatsReceiver.addGauge("gauge") { 1.0f }
intercept[TestFailedDueToTimeoutException] {
statUtils.gauges.waitFor("gauge", 2.0f, timeout)
}
}
test("InMemoryStatsReceiverUtility#waitFor will fail if metric does not have a declared value") {
val inMemoryStatsReceiver = new InMemoryStatsReceiver
val statUtils = new InMemoryStatsReceiverUtility(inMemoryStatsReceiver)
// A short timeout is set because the metric does not have a declared value
val timeout = 20.millis
inMemoryStatsReceiver.stats(Seq("stats")) = Seq()
intercept[TestFailedDueToTimeoutException] {
statUtils.stats.waitFor("stats", Seq(1.0f), timeout)
}
}
test(
"InMemoryStatsReceiverUtility#waitFor will accept metrics that are already the expected value") {
val inMemoryStatsReceiver = new InMemoryStatsReceiver
val statUtils = new InMemoryStatsReceiverUtility(inMemoryStatsReceiver)
val timeout = 20.millis
inMemoryStatsReceiver.counter("counter").incr(2)
statUtils.counters.waitFor("counter", 2, timeout)
inMemoryStatsReceiver.stats(Seq("stat")) = Seq(1.0f, 2.0f, 3.0f)
statUtils.stats.waitFor("stat", Seq(1.0f, 2.0f, 3.0f), timeout)
inMemoryStatsReceiver.addGauge("gauge") { 2.0f }
statUtils.gauges.waitFor("gauge", 2.0f, timeout)
}
test(
"InMemoryStatsReceiverUtility#waitFor will succeed when metric changes to the expected value within the timeout window") {
val inMemoryStatsReceiver = new InMemoryStatsReceiver
val sr = new InMemoryStatsReceiverUtility(inMemoryStatsReceiver)
val timeout = 100.millis
val counter = inMemoryStatsReceiver.counter("counter")
val stat = inMemoryStatsReceiver.stat("stat")
var gaugeValue: Float = 0.0f
val gauge = inMemoryStatsReceiver.addGauge("gauge") { gaugeValue }
val counterWait = FuturePool.unboundedPool { sr.counters.waitFor("counter", 1L, timeout) }
// Change metrics every 20 millis
FuturePool.unboundedPool {
for (_ <- 0 to 2) {
Thread.sleep(20)
// counter values: 0L, 1L, 2L, 3L
counter.incr()
}
}
await(counterWait)
val statsWait = FuturePool.unboundedPool { sr.stats.waitFor("stat", Seq(0.0f, 1.0f), timeout) }
FuturePool.unboundedPool {
for (s <- 0 to 2) {
Thread.sleep(20)
// histogram values: Seq(0.0f, 1.0f, 2.0f)
stat.add(s)
}
}
await(statsWait)
val gaugeWait = FuturePool.unboundedPool { sr.gauges.waitFor("gauge", 1.0f, timeout) }
FuturePool.unboundedPool {
for (g <- 0 to 2) {
Thread.sleep(20)
// gauge values: 0.0f, 1.0f, 2.0f
gaugeValue = g
}
}
await(gaugeWait)
}
}
| twitter/finatra | inject/inject-core/src/test/scala/com/twitter/inject/tests/InMemoryStatsReceiverUtilityTest.scala | Scala | apache-2.0 | 3,773 |
# Penicillium indicum D.K. Sandhu & R.S. Sandhu, 1963 SPECIES
#### Status
SYNONYM
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Sclerotiniaceae/Botrytis/Penicillium chermesinum/ Syn. Penicillium indicum/README.md | Markdown | apache-2.0 | 216 |
/*
* Copyright (c) 2015 David Venable.
*
* 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.venable.amazonaws.dynamo.table.builder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import io.venable.amazonaws.dynamo.table.HashRequiredException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
public class PrimaryKeyBuilderImplTest
{
private TableBuilder tableBuilder;
private String hashName;
private String rangeName;
@Before
public void setUp()
{
tableBuilder = mock(TableBuilder.class);
hashName = UUID.randomUUID().toString();
rangeName = UUID.randomUUID().toString();
}
private PrimaryKeyBuilderImpl createObjectUnderTest()
{
return new PrimaryKeyBuilderImpl(tableBuilder);
}
@Test
public void hash_should_return_non_null_value()
{
assertThat(createObjectUnderTest().hash(), notNullValue());
}
@Test
public void hash_should_return_same_instance()
{
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
assertThat(objectUnderTest.hash(), sameInstance(objectUnderTest.hash()));
}
@Test
public void hash_type_should_return_objectUnderTest()
{
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
assertThat(objectUnderTest.hash().type(ScalarAttributeType.S), is((PrimaryKeyBuilder) objectUnderTest));
}
@Test
public void range_should_return_non_null_value()
{
assertThat(createObjectUnderTest().range(), notNullValue());
}
@Test
public void range_should_return_same_instance()
{
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
assertThat(objectUnderTest.range(), sameInstance(objectUnderTest.range()));
}
@Test
public void range_type_should_return_objectUnderTest()
{
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
assertThat(objectUnderTest.range().type(ScalarAttributeType.S), is((PrimaryKeyBuilder) objectUnderTest));
}
@Test
public void and_should_return_TableBuilder()
{
assertThat(createObjectUnderTest().and(), is(tableBuilder));
}
@Test(expected = HashRequiredException.class)
public void buildPrimaryKey_should_throw_HashRequiredException_if_hash_is_not_present()
{
List<KeySchemaElement> keySchemaElementCollection = new ArrayList<>();
Collection<AttributeDefinition> attributeDefinitionCollection = new ArrayList<>();
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
objectUnderTest.range().name(rangeName).type(ScalarAttributeType.S);
objectUnderTest.buildPrimaryKey(keySchemaElementCollection, attributeDefinitionCollection);
}
@Test
public void buildPrimaryKey_should_add_two_KeySchemaElement_objects_when_range_is_present()
{
List<KeySchemaElement> keySchemaElementCollection = new ArrayList<>();
Collection<AttributeDefinition> attributeDefinitionCollection = new ArrayList<>();
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
objectUnderTest.hash().name(hashName).type(ScalarAttributeType.S);
objectUnderTest.range().name(rangeName).type(ScalarAttributeType.S);
objectUnderTest.buildPrimaryKey(keySchemaElementCollection, attributeDefinitionCollection);
assertThat(keySchemaElementCollection.size(), is(2));
}
@Test
public void buildPrimaryKey_should_add_one_KeySchemaElement_objects_when_range_is_not_present()
{
List<KeySchemaElement> keySchemaElementCollection = new ArrayList<>();
Collection<AttributeDefinition> attributeDefinitionCollection = new ArrayList<>();
PrimaryKeyBuilderImpl objectUnderTest = createObjectUnderTest();
objectUnderTest.hash().name(hashName).type(ScalarAttributeType.S);
objectUnderTest.buildPrimaryKey(keySchemaElementCollection, attributeDefinitionCollection);
assertThat(keySchemaElementCollection.size(), is(1));
}
} | dlvenable/dynamic-dynamo | src/test/java/io/venable/amazonaws/dynamo/table/builder/PrimaryKeyBuilderImplTest.java | Java | apache-2.0 | 4,953 |
package cn.evilcoder.algorithm;
import java.util.Arrays;
/**
* 素数
* Created by huangshanqi on 2016/7/10.
* See more at <a href = "http://www.evilcoder.cn">www.evilcoder.cn</a>
*/
public class Prime {
/**
* 判断num是否是素数
* @param num
* @return
*/
public static boolean isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
/**
* 埃拉托斯特尼筛法数组法判断是否是素数
* @param num
* @return
*/
public static boolean isPrimeWithSieveOfEratosthenes(int num) {
boolean[] prime = sieveOfEratosthenes(num);
return prime[num];
}
/**
* 埃拉托斯特尼筛法
* @param max
* @return
*/
private static boolean[] sieveOfEratosthenes(int max) {
boolean[] prime = new boolean[max + 1];
Arrays.fill(prime, true);
prime[0] = false;
prime[1] = false;
int nextPrime = 2;
while (nextPrime <= max) {
setPrimeMutiple(prime, nextPrime);
nextPrime = getNextPrime(prime, nextPrime);
if (nextPrime > prime.length) {
break;
}
}
return prime;
}
private static int getNextPrime(boolean[] prime, int nextPrime) {
nextPrime += 1;
while (nextPrime < prime.length && !prime[nextPrime]) {
nextPrime++;
}
return nextPrime;
}
/**
* 将nextPrime 的倍数肯定 不是素数
* @param prime
* @param nextPrime
*/
private static void setPrimeMutiple(boolean[] prime, int nextPrime) {
for (int i = nextPrime * nextPrime; i < prime.length; i += nextPrime) {
prime[i] = false;
}
}
}
| huangshanqi/algorithom-tutorial | src/cn/evilcoder/algorithm/Prime.java | Java | apache-2.0 | 1,925 |
#pragma once
#include "VectorCommon.h"
#include "../Interfaces/ITransformer.h"
#include "Vector2D.h"
namespace SupergodCore { namespace Math
{
struct Vector4D;
/// <summary>
/// Represents a 3-component mathematical vector.
/// </summary>
struct SUPERGOD_API_CLASS Vector3D final : public VectorBase<Vector3D>
{
#pragma region Presets for common vectors.
/// <summary>
/// Gets a 3D vector with all of its components set to 0.
/// </summary>
DEFINE_STRUCT_VALUE_PRESET(Vector3D, Zero, (0, 0, 0))
/// <summary>
/// Gets a 3D vector with all of its components set to 1.
/// </summary>
DEFINE_STRUCT_VALUE_PRESET(Vector3D, One, (1, 1, 1))
/// <summary>
/// Gets the 2D vector (1, 0, 0).
/// </summary>
DEFINE_STRUCT_VALUE_PRESET(Vector3D, UnitX, (1, 0, 0))
/// <summary>
/// Gets the 2D vector (0, 1, 0).
/// </summary>
DEFINE_STRUCT_VALUE_PRESET(Vector3D, UnitY, (0, 1, 0))
/// <summary>
/// Gets the 2D vector (0, 0, 1).
/// </summary>
DEFINE_STRUCT_VALUE_PRESET(Vector3D, UnitZ, (0, 0, 1))
#pragma endregion
union
{
struct { float x, y, z; };
float components[3];
};
/// <summary>Creates a new 3D vector and initializes all of its components to 0.</summary>
Vector3D();
/// <summary>Creates a new 3D vector and initializes its components to x, y and z.</summary>
Vector3D(float x, float y, float z);
/// <summary>Creates a new 3D vector and initializes its x and y components to xy and its z component to z.</summary>
Vector3D(const Vector2D& xy, float z);
/// <summary>Creates a new 3D vector and initializes its x component x and its y and z components to yz.</summary>
Vector3D(float x, const Vector2D& yz);
/// <summary>
/// Gets a reference to a component at the index of index.
/// </summary>
/// <param name="index">The index of the component (0, 1 or 2).</param>
inline float& operator[](int index)
{
return components[index];
}
/// <summary>
/// Gets a reference to a component at the index of index.
/// </summary>
/// <param name="index">The index of the component (0, 1 or 2).</param>
inline const float& operator[](int index) const
{
return components[index];
}
/// <summary>
/// Creates a new Vector2D with x and y as its components.
/// </summary>
explicit operator Vector2D() const;
/// <summary>
/// Creates a new Vector4D with x, y, z and 0 as its components.
/// </summary>
/// <returns></returns>
operator Vector4D() const;
/// /// <summary>
/// Transform this vector by transformer.
/// </summary>
/// <returns>The transformed vector.</returns>
template<class TTransformer>
inline Vector3D Transform(const TTransformer& transformer) const
{
return transformer.TransformVector(*this);
}
#pragma region Axis Combinations.
/// <summary>A Vector2D with the x and y components of this vector.</summary>
inline Vector2D XY() const { return Vector2D(x, y); }
/// <summary>A Vector2D with the y and x components of this vector.</summary>
inline Vector2D YX() const { return Vector2D(y, x); }
/// <summary>A Vector2D with the x and z components of this vector.</summary>
inline Vector2D XZ() const { return Vector2D(x, z); }
/// <summary>A Vector2D with the z and x components of this vector.</summary>
inline Vector2D ZX() const { return Vector2D(z, x); }
/// <summary>A Vector2D with the y and z components of this vector.</summary>
inline Vector2D YZ() const { return Vector2D(y, z); }
/// <summary>A Vector2D with the z and y components of this vector.</summary>
inline Vector2D ZY() const { return Vector2D(z, y); }
#pragma endregion
#pragma region Comparison methods (Equals, ContainsComponent and CloseEnough).
/// <summary>
/// Is every component of this same as its corresponding component in other?
/// </summary>
bool Equals(const Vector3D& other) const;
/// <summary>
/// Is every component of this close enough to its corresponding component in other with the threshold of threshold?<para/>
/// See SupergodEngine::Math::Smath::CloseEnough.
/// </summary>
/// <param name="threshold">The threshold for each component to be considered close enough.</param>
bool CloseEnough(const Vector3D& other, float threshold = Constants::CLOSE_ENOUGH_DEFAULT_THRESHOLD) const;
/// <summary>
/// Does any component pass test?
/// </summary>
/// <param name="test">The test to run for each component.</param>
bool ContainsComponent(const std::function<bool(float)>& test) const;
#pragma endregion
#pragma region Addition, subtraction and negation.
/// <summary>
/// Adds every component of this with its corresponding component in other.
/// </summary>
Vector3D Add(const Vector3D& other) const;
/// <summary>
/// Subtracts every component of other from its corresponding component in this.
/// </summary>
Vector3D Subtract(const Vector3D& other) const;
/// <summary>
/// Negates every component of this.
/// </summary>
Vector3D Negated() const;
#pragma endregion
#pragma region Multiplication (Dot, Multiply and Cross).
/// <summary>
/// Gets the dot product of this and other.
/// </summary>
float Dot(const Vector3D& other) const;
/// <summary>
/// Multiplies this and other component-wise.
/// </summary>
Vector3D Multiply(const Vector3D& other) const;
/// <summary>
/// Multiplies every component of this by scalar.
/// </summary>
Vector3D Multiply(float scalar) const;
/// <summary>
/// Gets the cross product of this and other.
/// </summary>
Vector3D Cross(const Vector3D& other) const;
/// <summary>
/// Gets the cross product of a and b.
/// </summary>
inline static Vector3D Cross(const Vector3D& a, const Vector3D& b)
{
return a.Cross(b);
}
#pragma endregion
#pragma region Division.
/// <summary>
/// Divides every component of this by scalar.
/// </summary>
Vector3D Divide(float scalar) const;
/// <summary>
/// Divides every component of this by its corresponding component in scalar.
/// </summary>
Vector3D Divide(const Vector3D& other) const;
#pragma endregion
#pragma region BiggestComponent/BiggestComponent.
/// <summary>
/// Gets a reference to the biggest component in the vector.
/// </summary>
float& BiggestComponent();
/// <summary>
/// Gets a reference to the smallest component in the vector.
/// </summary>
float& SmallestComponent();
/// <summary>
/// Gets a reference to the biggest component in the vector.
/// </summary>
const float& BiggestComponent() const;
/// <summary>
/// Gets a reference to the smallest component in the vector.
/// </summary>
const float& SmallestComponent() const;
#pragma endregion
#pragma region Clamping methods.
/// <summary>
/// Gets a vector where all of its components are the absolute value of their corresponding component in this.
/// </summary>
/// <returns></returns>
Vector3D Abs() const;
/// <summary>
/// Clamps every component of this so it's never smaller than its corresponding component in min and never bigger than its corresponding component in max.
/// </summary>
Vector3D Clamp(const Vector3D& min, const Vector3D& max) const;
/// <summary>
/// Clamps every component of this so it's never smaller than min and never bigger than max.
/// </summary>
Vector3D ClampComponents(float min, float max) const;
#pragma endregion
};
} } | OrAviram/Supergod-Engine | SupergodCore/Math/Vectors/Vector3D.h | C | apache-2.0 | 7,492 |
package com.github.shredder121.gh_event_api.handler.issues;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import com.github.shredder121.gh_event_api.GHEventApiServer;
import com.github.shredder121.gh_event_api.handler.AbstractHandlerTest;
@SpringApplicationConfiguration(classes = {IssuesHandlerTest.class, GHEventApiServer.class})
public class IssuesHandlerTest extends AbstractHandlerTest {
public IssuesHandlerTest() {
super("issues");
}
@Bean
public TestHandler handlerBean() {
return new TestHandler();
}
}
| Shredder121/gh-event-api | src/test/java/com/github/shredder121/gh_event_api/handler/issues/IssuesHandlerTest.java | Java | apache-2.0 | 628 |
import * as Preact from '#preact';
import {
Alignment,
Axis,
findOverlappingIndex,
getPercentageOffsetFromAlignment,
scrollContainerToElement,
} from './dimensions';
import {WithBentoLightboxGallery} from '../../amp-lightbox-gallery/1.0/component';
import {debounce} from '#core/types/function';
import {forwardRef} from '#preact/compat';
import {mod} from '#core/math';
import {setStyle} from '#core/dom/style';
import {toWin} from '#core/window';
import {
useCallback,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
} from '#preact';
import {useStyles} from './component.jss';
/**
* How long to wait prior to resetting the scrolling position after the last
* scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to interrupt a scroll with a
* render, it cannot be too small. 200ms seems to be around the lower limit for
* this value on Android / iOS.
*/
const RESET_SCROLL_REFERENCE_POINT_WAIT_MS = 200;
/**
* @param {!BaseCarouselDef.ScrollerProps} props
* @param {{current: ?T}} ref
* @return {PreactDef.Renderable}
* @template T
*/
function ScrollerWithRef(
{
_thumbnails,
advanceCount,
alignment,
axis,
children,
lightboxGroup,
loop,
mixedLength,
onClick,
restingIndex,
setRestingIndex,
snap,
snapBy = 1,
visibleCount,
},
ref
) {
// We still need our own ref that we can always rely on to be there.
const containerRef = useRef(null);
/**
* The number of slides we want to place before the reference or resting index.
* Normalized to == restingIndex if loop=false.
*/
const pivotIndex = loop ? Math.floor(children.length / 2) : restingIndex;
/**
* Whether to early exit from the scroll handler.
* This is useful on each render where the container is scrolled to the active
* slide at a non-integer pixel position. This is likely to happen
* with responsive containers or non-integer `visibleCount`.
*/
const ignoreProgrammaticScrollRef = useRef(false);
const advance = useCallback(
(by) => {
const container = containerRef.current;
if (!container) {
return;
}
// Smooth scrolling is preferred to `setRestingIndex` whenever possible.
// Note: `setRestingIndex` will still be called on debounce by scroll handler.
currentIndex.current = mod(currentIndex.current + by, children.length);
scrollOffset.current = 0;
const didScroll = scrollContainerToElement(
axis,
alignment,
container,
container.children[mod(pivotIndex + by, container.children.length)],
scrollOffset.current
);
if (!didScroll) {
setRestingIndex(currentIndex.current);
}
},
[alignment, axis, children.length, pivotIndex, setRestingIndex]
);
useImperativeHandle(
ref,
() => ({
advance,
next: () => advance(advanceCount),
prev: () => advance(-advanceCount),
get node() {
return containerRef.current;
},
}),
[advance, advanceCount]
);
const classes = useStyles();
/**
* The dynamic position that the slide at the resting index
* is with respect to its scrolling order. Only needed if loop=true.
*/
const offsetRef = useRef(restingIndex);
/**
* The partial scroll position as a percentage of the current visible slide.
* Only modified if snap=false.
*/
const scrollOffset = useRef(0);
const slides = renderSlides(
{
alignment,
children,
loop,
mixedLength,
offsetRef,
lightboxGroup,
pivotIndex,
restingIndex,
snap,
snapBy,
visibleCount,
_thumbnails,
},
classes
);
const currentIndex = useRef(restingIndex);
const scrollToActiveSlide = useCallback(() => {
if (!containerRef.current || !containerRef.current.children.length) {
return;
}
const container = containerRef.current;
setStyle(container, 'scrollBehavior', 'auto');
ignoreProgrammaticScrollRef.current = true;
scrollContainerToElement(
axis,
alignment,
container,
container.children[pivotIndex],
scrollOffset.current
);
setStyle(container, 'scrollBehavior', 'smooth');
}, [alignment, axis, pivotIndex]);
// useLayoutEffect to avoid FOUC while scrolling for looping layouts.
useLayoutEffect(() => {
if (!containerRef.current || !loop) {
return;
}
const container = containerRef.current;
if (!container.children.length) {
return;
}
scrollToActiveSlide();
}, [loop, restingIndex, scrollToActiveSlide]);
// Adjust slide position when container size changes.
useLayoutEffect(() => {
if (!containerRef.current) {
return;
}
const node = containerRef.current;
if (!node) {
return;
}
// Use local window.
const win = toWin(node.ownerDocument.defaultView);
if (!win) {
return undefined;
}
const observer = new win.ResizeObserver(scrollToActiveSlide);
observer.observe(node);
return () => observer.disconnect();
}, [scrollToActiveSlide]);
// Trigger render by setting the resting index to the current scroll state.
const debouncedResetScrollReferencePoint = useMemo(() => {
// Use local window if possible.
const win = containerRef.current
? toWin(containerRef.current.ownerDocument.defaultView)
: window;
return debounce(
win,
() => {
// Check if the resting index we are centered around is the same as where
// we stopped scrolling. If so, we do not need to move anything.
if (
currentIndex.current === null ||
currentIndex.current === restingIndex
) {
return;
}
setRestingIndex(currentIndex.current);
},
RESET_SCROLL_REFERENCE_POINT_WAIT_MS
);
}, [restingIndex, setRestingIndex]);
// Track current slide without forcing render.
// This is necessary for smooth scrolling because
// intermediary renders will interupt scroll and cause jank.
const updateCurrentIndex = () => {
const container = containerRef.current;
if (!container) {
return;
}
const overlappingIndex = findOverlappingIndex(
axis,
alignment,
container,
container.children,
pivotIndex
);
if (!snap) {
scrollOffset.current = getPercentageOffsetFromAlignment(
axis,
alignment,
container,
container.children[overlappingIndex]
);
}
currentIndex.current = mod(
overlappingIndex - offsetRef.current,
children.length
);
};
const handleScroll = () => {
if (ignoreProgrammaticScrollRef.current) {
ignoreProgrammaticScrollRef.current = false;
return;
}
updateCurrentIndex();
debouncedResetScrollReferencePoint();
};
return (
<div
ref={containerRef}
onClick={onClick}
onScroll={handleScroll}
class={`${classes.scrollContainer} ${classes.hideScrollbar} ${
axis === Axis.X ? classes.horizontalScroll : classes.verticalScroll
}`}
tabIndex={0}
>
{slides}
</div>
);
}
const Scroller = forwardRef(ScrollerWithRef);
Scroller.displayName = 'Scroller'; // Make findable for tests.
export {Scroller};
/**
* How the slides are ordered when looping:
*
* We want to make sure that the user can scroll all the way to the opposite
* end (either forwards or backwards) of the carousel, but no further (no
* looping back past where you started). We render elements dynamically
* for a desirable scrolling order to allow the browser to scroll as well as
* providing targets for the browser to snap on. This is important as these
* targets need to be present before the scroll starts for things to work
* correctly.
*
* The elements are ordered depending on the reference point, called
* the restingIndex to allow full movement forwards and backwards. You can
* imagine the DOM structure looks like the following if you have 5 slides:
*
* [1][2][3][4][5]
*
* When the restingIndex is the first index, we should translate slides as follows:
*
* [4][5][1][2][3]
*
* This ensures that if you move left or right, there is a slide to show.
*
* When the user stops scrolling, we update the restingIndex and show/hide the
* appropriate spacers. For example, if the user started at slide '1' and moved
* left to slide '4', the UI would eventually stop because there is
* nothing more to the left of slide '4'.
*
* [4][5][1][2][3]
*
* Once scrolling stops, however, the reference point would be reset and this would
* update to the following with the next render:
*
* [2][3][4][5][1]
*
* Ordering slides:
*
* Slides are ordered to be before or after the current slide and do not rearrange
* dynamically as the user scrolls. Only once the scrolling has ended do they rearrange.
* Currently, half the slides are ordered before and half the slides are ordered after.
* This could be a bit smarter and only place as many as are necessary on either side of
* the reference point to have a sufficient amount of buffer.
*
* Initial index:
*
* The initial index can be specified, which will make the carousel scroll to
* the desired index when it first renders.
*
* @param {!BaseCarouselDef.SlideProps} props
* @param {!Object} classes
* @return {PreactDef.Renderable}
*/
function renderSlides(
{
_thumbnails,
alignment,
children,
lightboxGroup,
loop,
mixedLength,
offsetRef,
pivotIndex,
restingIndex,
snap,
snapBy,
visibleCount,
},
classes
) {
const {length} = children;
const Comp = lightboxGroup ? WithBentoLightboxGallery : 'div';
const slides = children.map((child, index) => {
const key = `slide-${child.key || index}`;
return (
<Comp
caption={child.props.caption}
key={key}
data-slide={index}
class={`${classes.slideSizing} ${classes.slideElement} ${
snap && mod(index, snapBy) === 0
? classes.enableSnap
: classes.disableSnap
} ${
alignment === Alignment.CENTER
? classes.centerAlign
: classes.startAlign
} ${_thumbnails ? classes.thumbnails : ''} `}
// lightboxGroup is a string when defined, and `false` otherwise. In the case
// of the latter, we do not want to pass group={false} into the DOM.
group={lightboxGroup || undefined}
part="slide"
style={{
flex: mixedLength ? '0 0 auto' : `0 0 ${100 / visibleCount}%`,
}}
>
{child}
</Comp>
);
});
if (!loop) {
return slides;
}
const before = [];
const after = [];
const shift = mod(length - restingIndex + pivotIndex, length);
if (restingIndex <= pivotIndex) {
for (let i = 0; i < shift; i++) {
before.unshift(slides.pop());
}
} else {
for (let i = 0; i < length - shift; i++) {
after.push(slides.shift());
}
}
offsetRef.current = before.length ? before.length : -after.length;
return (
<>
{before}
{slides}
{after}
</>
);
}
| smartadserver/amphtml | extensions/amp-base-carousel/1.0/scroller.js | JavaScript | apache-2.0 | 11,287 |
/**
* @author eamonn
*
*/
package com.srcdevbin.buildbot.activity.movement; | elmodaddyb/buildbot | buildbot-activity/src/com/srcdevbin/buildbot/activity/movement/package-info.java | Java | apache-2.0 | 78 |
unsigned char keyboard_map[]={
129,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,
130,130,130,131,0,0,0,0,0,0,0,0,0,0,0,0,
132,34,39,94,96,126,92,65,66,67,68,69,70,71,60,55,
56,57,43,133,0,0,0,0,0,0,0,0,0,0,0,0,
132,33,63,58,59,44,95,72,73,74,75,76,77,78,62,52,
53,54,45,133,0,0,0,0,0,0,0,0,0,0,0,0,
132,40,41,91,93,123,125,79,80,81,82,83,84,85,0,49,
50,51,42,133,0,0,0,0,0,0,0,0,0,0,0,0,
132,35,36,37,38,64,124,86,87,88,89,90,32,32,0,48,
61,46,47,133,0,0,0,0,0,0,0,0,0,0,0,0,
134,135,135,135,135,135,135,135,135,135,135,135,135,135,135,135,
135,135,135,136,0,0,0,0,0,0,0,0,0,0,0,0
};
| haroldo-ok/really-old-stuff | gameboy/gbv8_100/SOURCE/KEYBMAP.H | C++ | apache-2.0 | 599 |
FROM centos
MAINTAINER Lothar Wieske <lothar.wieske@gmail.com>
RUN yum update -y && \
curl --insecure --junk-session-cookies --location --remote-name --silent --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u45-b14/server-jre-8u45-linux-x64.tar.gz && \
mkdir -p /usr/java && \
gunzip server-jre-8u45-linux-x64.tar.gz && \
tar xf server-jre-8u45-linux-x64.tar -C /usr/java && \
alternatives --install /usr/bin/java java /usr/java/jdk1.8.0_45/bin/java 1 && \
alternatives --install /usr/bin/jar jar /usr/java/jdk1.8.0_45/bin/jar 1 && \
rm server-jre-8u45-linux-x64.tar && \
yum clean all
ENV JAVA_HOME=/usr/java/jdk1.8.0_45/ \
LANG=en_US.UTF-8 \
LC_ALL=en_US.UTF-8
| lwieske/dockerfiles-java-8 | 8u45/server-jre/Dockerfile | Dockerfile | apache-2.0 | 767 |
# Meliola manca Ellis & G. Martin SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Am. Nat. 17: 1284 (1883)
#### Original name
Meliola manca Ellis & G. Martin
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Dothideomycetes/Meliolales/Meliolaceae/Meliola/Meliola manca/README.md | Markdown | apache-2.0 | 211 |
/*
* 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.accumulo.test.functional;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.hadoop.io.Text;
public class ScanSessionTimeOutTest extends FunctionalTest {
@Override
public void cleanup() throws Exception {}
@Override
public Map<String,String> getInitialConfig() {
HashMap<String,String> config = new HashMap<String,String>();
// set the session idle time 3 seconds
config.put(Property.TSERV_SESSION_MAXIDLE.getKey(), "3");
return config;
}
@Override
public List<TableSetup> getTablesToCreate() {
return Collections.singletonList(new TableSetup("abc"));
}
@Override
public void run() throws Exception {
BatchWriter bw = getConnector().createBatchWriter("abc", new BatchWriterConfig());
for (int i = 0; i < 100000; i++) {
Mutation m = new Mutation(new Text(String.format("%08d", i)));
for (int j = 0; j < 3; j++)
m.put(new Text("cf1"), new Text("cq" + j), new Value(("" + i + "_" + j).getBytes()));
bw.addMutation(m);
}
bw.close();
Scanner scanner = getConnector().createScanner("abc", new Authorizations());
scanner.setBatchSize(1000);
Iterator<Entry<Key,Value>> iter = scanner.iterator();
verify(iter, 0, 200);
// sleep three times the session timeout
UtilWaitThread.sleep(9000);
verify(iter, 200, 100000);
}
private void verify(Iterator<Entry<Key,Value>> iter, int start, int stop) throws Exception {
for (int i = start; i < stop; i++) {
Text er = new Text(String.format("%08d", i));
for (int j = 0; j < 3; j++) {
Entry<Key,Value> entry = iter.next();
if (!entry.getKey().getRow().equals(er)) {
throw new Exception("row " + entry.getKey().getRow() + " != " + er);
}
if (!entry.getKey().getColumnFamily().equals(new Text("cf1"))) {
throw new Exception("cf " + entry.getKey().getColumnFamily() + " != cf1");
}
if (!entry.getKey().getColumnQualifier().equals(new Text("cq" + j))) {
throw new Exception("cq " + entry.getKey().getColumnQualifier() + " != cq" + j);
}
if (!entry.getValue().toString().equals("" + i + "_" + j)) {
throw new Exception("value " + entry.getValue() + " != " + i + "_" + j);
}
}
}
}
}
| wjsl/jaredcumulo | test/src/main/java/org/apache/accumulo/test/functional/ScanSessionTimeOutTest.java | Java | apache-2.0 | 3,784 |
<?php
namespace Google\Service\Compute;
/*
* Copyright 2010 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.
*/
class HealthStatus extends \Google\Model
{
public $healthState;
public $instance;
public $ipAddress;
public function setHealthState($healthState)
{
$this->healthState = $healthState;
}
public function getHealthState()
{
return $this->healthState;
}
public function setInstance($instance)
{
$this->instance = $instance;
}
public function getInstance()
{
return $this->instance;
}
public function setIpAddress($ipAddress)
{
$this->ipAddress = $ipAddress;
}
public function getIpAddress()
{
return $this->ipAddress;
}
}
| xevious99/google-api-php-client | src/Google/Service/Compute/HealthStatus.php | PHP | apache-2.0 | 1,223 |
package light
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"github.com/tendermint/tendermint/light/provider"
"github.com/tendermint/tendermint/types"
)
// The detector component of the light client detects and handles attacks on the light client.
// More info here:
// tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
// detectDivergence is a second wall of defense for the light client.
//
// It takes the target verified header and compares it with the headers of a set of
// witness providers that the light client is connected to. If a conflicting header
// is returned it verifies and examines the conflicting header against the verified
// trace that was produced from the primary. If successful, it produces two sets of evidence
// and sends them to the opposite provider before halting.
//
// If there are no conflictinge headers, the light client deems the verified target header
// trusted and saves it to the trusted store.
func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.LightBlock, now time.Time) error {
c.providerMutex.Lock()
defer c.providerMutex.Unlock()
if len(c.witnesses) < 1 {
return nil
}
if primaryTrace == nil || len(primaryTrace) < 2 {
return errors.New("nil or single block primary trace")
}
var (
headerMatched bool
lastVerifiedHeader = primaryTrace[len(primaryTrace)-1].SignedHeader
witnessesToRemove = make([]int, 0)
)
c.logger.Debug("running detector against trace", "finalizeBlockHeight", lastVerifiedHeader.Height,
"finalizeBlockHash", lastVerifiedHeader.Hash, "length", len(primaryTrace))
// launch one goroutine per witness to retrieve the light block of the target height
// and compare it with the header from the primary
errc := make(chan error, len(c.witnesses))
for i, witness := range c.witnesses {
go c.compareNewHeaderWithWitness(ctx, errc, lastVerifiedHeader, witness, i)
}
// handle errors from the header comparisons as they come in
for i := 0; i < cap(errc); i++ {
err := <-errc
switch e := err.(type) {
case nil: // at least one header matched
headerMatched = true
case errConflictingHeaders:
// We have conflicting headers. This could possibly imply an attack on the light client.
// First we need to verify the witness's header using the same skipping verification and then we
// need to find the point that the headers diverge and examine this for any evidence of an attack.
//
// We combine these actions together, verifying the witnesses headers and outputting the trace
// which captures the bifurcation point and if successful provides the information to create valid evidence.
err := c.handleConflictingHeaders(ctx, primaryTrace, e.Block, e.WitnessIndex, now)
if err != nil {
// return information of the attack
return err
}
// if attempt to generate conflicting headers failed then remove witness
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
case errBadWitness:
c.logger.Info("witness returned an error during header comparison, removing...",
"witness", c.witnesses[e.WitnessIndex], "err", err)
witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
default:
if errors.Is(e, context.Canceled) || errors.Is(e, context.DeadlineExceeded) {
return e
}
c.logger.Info("error in light block request to witness", "err", err)
}
}
// remove witnesses that have misbehaved
if err := c.removeWitnesses(witnessesToRemove); err != nil {
return err
}
// 1. If we had at least one witness that returned the same header then we
// conclude that we can trust the header
if headerMatched {
return nil
}
// 2. Else all witnesses have either not responded, don't have the block or sent invalid blocks.
return ErrFailedHeaderCrossReferencing
}
// compareNewHeaderWithWitness takes the verified header from the primary and compares it with a
// header from a specified witness. The function can return one of three errors:
//
// 1: errConflictingHeaders -> there may have been an attack on this light client
// 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
// Note: In the case of an invalid header we remove the witness
// 3: nil -> the hashes of the two headers match
func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
witness provider.Provider, witnessIndex int) {
lightBlock, err := c.getLightBlock(ctx, witness, h.Height)
switch err {
// no error means we move on to checking the hash of the two headers
case nil:
break
// the witness hasn't been helpful in comparing headers, we mark the response and continue
// comparing with the rest of the witnesses
case provider.ErrNoResponse, provider.ErrLightBlockNotFound, context.DeadlineExceeded, context.Canceled:
errc <- err
return
// the witness' head of the blockchain is lower than the height of the primary. This could be one of
// two things:
// 1) The witness is lagging behind
// 2) The primary may be performing a lunatic attack with a height and time in the future
case provider.ErrHeightTooHigh:
// The light client now asks for the latest header that the witness has
var isTargetHeight bool
isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
if err != nil {
if c.providerShouldBeRemoved(err) {
errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
} else {
errc <- err
}
return
}
// if the witness caught up and has returned a block of the target height then we can
// break from this switch case and continue to verify the hashes
if isTargetHeight {
break
}
// witness' last header is below the primary's header. We check the times to see if the blocks
// have conflicting times
if !lightBlock.Time.Before(h.Time) {
errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
return
}
// the witness is behind. We wait for a period WAITING = 2 * DRIFT + LAG.
// This should give the witness ample time if it is a participating member
// of consensus to produce a block that has a time that is after the primary's
// block time. If not the witness is too far behind and the light client removes it
time.Sleep(2*c.maxClockDrift + c.maxBlockLag)
isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
if err != nil {
if c.providerShouldBeRemoved(err) {
errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
} else {
errc <- err
}
return
}
if isTargetHeight {
break
}
// the witness still doesn't have a block at the height of the primary.
// Check if there is a conflicting time
if !lightBlock.Time.Before(h.Time) {
errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
return
}
// Following this request response procedure, the witness has been unable to produce a block
// that can somehow conflict with the primary's block. We thus conclude that the witness
// is too far behind and thus we return a no response error.
//
// NOTE: If the clock drift / lag has been miscalibrated it is feasible that the light client has
// drifted too far ahead for any witness to be able provide a comparable block and thus may allow
// for a malicious primary to attack it
errc <- provider.ErrNoResponse
return
default:
// all other errors (i.e. invalid block, closed connection or unreliable provider) we mark the
// witness as bad and remove it
errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
return
}
if !bytes.Equal(h.Header.Hash(), lightBlock.Header.Hash()) {
errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
}
c.logger.Debug("matching header received by witness", "height", h.Height, "witness", witnessIndex)
errc <- nil
}
// sendEvidence sends evidence to a provider on a best effort basis.
func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) {
err := receiver.ReportEvidence(ctx, ev)
if err != nil {
c.logger.Error("failed to report evidence to provider", "ev", ev, "provider", receiver)
}
}
// handleConflictingHeaders handles the primary style of attack, which is where a primary and witness have
// two headers of the same height but with different hashes
func (c *Client) handleConflictingHeaders(
ctx context.Context,
primaryTrace []*types.LightBlock,
challendingBlock *types.LightBlock,
witnessIndex int,
now time.Time,
) error {
supportingWitness := c.witnesses[witnessIndex]
witnessTrace, primaryBlock, err := c.examineConflictingHeaderAgainstTrace(
ctx,
primaryTrace,
challendingBlock,
supportingWitness,
now,
)
if err != nil {
c.logger.Info("error validating witness's divergent header", "witness", supportingWitness, "err", err)
return nil
}
// We are suspecting that the primary is faulty, hence we hold the witness as the source of truth
// and generate evidence against the primary that we can send to the witness
commonBlock, trustedBlock := witnessTrace[0], witnessTrace[len(witnessTrace)-1]
evidenceAgainstPrimary := newLightClientAttackEvidence(primaryBlock, trustedBlock, commonBlock)
c.logger.Error("ATTEMPTED ATTACK DETECTED. Sending evidence againt primary by witness", "ev", evidenceAgainstPrimary,
"primary", c.primary, "witness", supportingWitness)
c.sendEvidence(ctx, evidenceAgainstPrimary, supportingWitness)
if primaryBlock.Commit.Round != witnessTrace[len(witnessTrace)-1].Commit.Round {
c.logger.Info("The light client has detected, and prevented, an attempted amnesia attack." +
" We think this attack is pretty unlikely, so if you see it, that's interesting to us." +
" Can you let us know by opening an issue through https://github.com/tendermint/tendermint/issues/new?")
}
// This may not be valid because the witness itself is at fault. So now we reverse it, examining the
// trace provided by the witness and holding the primary as the source of truth. Note: primary may not
// respond but this is okay as we will halt anyway.
primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace(
ctx,
witnessTrace,
primaryBlock,
c.primary,
now,
)
if err != nil {
c.logger.Info("error validating primary's divergent header", "primary", c.primary, "err", err)
return ErrLightClientAttack
}
// We now use the primary trace to create evidence against the witness and send it to the primary
commonBlock, trustedBlock = primaryTrace[0], primaryTrace[len(primaryTrace)-1]
evidenceAgainstWitness := newLightClientAttackEvidence(witnessBlock, trustedBlock, commonBlock)
c.logger.Error("Sending evidence against witness by primary", "ev", evidenceAgainstWitness,
"primary", c.primary, "witness", supportingWitness)
c.sendEvidence(ctx, evidenceAgainstWitness, c.primary)
// We return the error and don't process anymore witnesses
return ErrLightClientAttack
}
// examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that
// it has received from another and preforms verifySkipping at the heights of each of the intermediate
// headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
//
// 1. The light client verifies a header that is different to the intermediate header in the trace. This
// is the bifurcation point and the light client can create evidence from it
// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
// return the error and remove the witness
//
// CONTRACT:
// 1. Trace can not be empty len(trace) > 0
// 2. The last block in the trace can not be of a lower height than the target block
// trace[len(trace)-1].Height >= targetBlock.Height
// 3. The
func (c *Client) examineConflictingHeaderAgainstTrace(
ctx context.Context,
trace []*types.LightBlock,
targetBlock *types.LightBlock,
source provider.Provider, now time.Time,
) ([]*types.LightBlock, *types.LightBlock, error) {
var (
previouslyVerifiedBlock, sourceBlock *types.LightBlock
sourceTrace []*types.LightBlock
err error
)
if targetBlock.Height < trace[0].Height {
return nil, nil, fmt.Errorf("target block has a height lower than the trusted height (%d < %d)",
targetBlock.Height, trace[0].Height)
}
for idx, traceBlock := range trace {
// this case only happens in a forward lunatic attack. We treat the block with the
// height directly after the targetBlock as the divergent block
if traceBlock.Height > targetBlock.Height {
// sanity check that the time of the traceBlock is indeed less than that of the targetBlock. If the trace
// was correctly verified we should expect monotonically increasing time. This means that if the block at
// the end of the trace has a lesser time than the target block then all blocks in the trace should have a
// lesser time
if traceBlock.Time.After(targetBlock.Time) {
return nil, nil,
errors.New("sanity check failed: expected traceblock to have a lesser time than the target block")
}
// before sending back the divergent block and trace we need to ensure we have verified
// the final gap between the previouslyVerifiedBlock and the targetBlock
if previouslyVerifiedBlock.Height != targetBlock.Height {
sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, targetBlock, now)
if err != nil {
return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
}
}
return sourceTrace, traceBlock, nil
}
// get the corresponding block from the source to verify and match up against the traceBlock
if traceBlock.Height == targetBlock.Height {
sourceBlock = targetBlock
} else {
sourceBlock, err = c.getLightBlock(ctx, source, traceBlock.Height)
if err != nil {
return nil, nil, fmt.Errorf("failed to examine trace: %w", err)
}
}
// The first block in the trace MUST be the same to the light block that the source produces
// else we cannot continue with verification.
if idx == 0 {
if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)",
thash, shash)
}
previouslyVerifiedBlock = sourceBlock
continue
}
// we check that the source provider can verify a block at the same height of the
// intermediate height
sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now)
if err != nil {
return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
}
// check if the headers verified by the source has diverged from the trace
if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
// Bifurcation point found!
return sourceTrace, traceBlock, nil
}
// headers are still the same. update the previouslyVerifiedBlock
previouslyVerifiedBlock = sourceBlock
}
// We have reached the end of the trace. This should never happen. This can only happen if one of the stated
// prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height
// or that trace[i].Hash() != targetBlock.Hash()
return nil, nil, errNoDivergence
}
// getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries
// the target heght else it returns the latest. returns true if it successfully managed to acquire the target
// height.
func (c *Client) getTargetBlockOrLatest(
ctx context.Context,
height int64,
witness provider.Provider,
) (bool, *types.LightBlock, error) {
lightBlock, err := c.getLightBlock(ctx, witness, 0)
if err != nil {
return false, nil, err
}
if lightBlock.Height == height {
// the witness has caught up to the height of the provider's signed header. We
// can resume with checking the hashes.
return true, lightBlock, nil
}
if lightBlock.Height > height {
// the witness has caught up. We recursively call the function again. However in order
// to avoud a wild goose chase where the witness sends us one header below and one header
// above the height we set a timeout to the context
lightBlock, err := c.getLightBlock(ctx, witness, height)
return true, lightBlock, err
}
return false, lightBlock, nil
}
// newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out
// all the fields such that it is ready to be sent to a full node.
func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence {
ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted}
// We use the common height to indicate the form of the attack.
// if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we
// return the height of the conflicting block as the common height. If instead it is a lunatic
// attack and the validator sets are not the same then we send the height of the common header.
if ev.ConflictingHeaderIsInvalid(trusted.Header) {
ev.CommonHeight = common.Height
ev.Timestamp = common.Time
ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
} else {
ev.CommonHeight = trusted.Height
ev.Timestamp = trusted.Time
ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower()
}
ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
return ev
}
| tendermint/tendermint | light/detector.go | GO | apache-2.0 | 17,660 |
/*
==================================================================
Author: Karthik Venkataramana Pemmaraju.
Compilation: g++ IntList.cpp -c
Description: Implements data structure of sequence of ints.
Compiled and tested on 09/17/2017
==================================================================
*/
#include "IntList.h"
#include "IntStack.h"
#include "random.cpp"
using namespace std;
namespace iProlog{
IntList::IntList(int h){ // Our head is initialized to h.
head = h;
tail = NULL;
}
IntList::IntList(int X, IntList *Xs) {
head = X;
tail = Xs;
}
bool IntList::isempty(IntList *Xs){ // C++ grammar defines static to be declared only once inside class.
if(Xs == NULL) return true;
return false;
}
int IntList::getHead( IntList *Xs){
if(Xs != NULL)
return Xs -> head;
return 0;
}
IntList* IntList::getTail( IntList *Xs) {
if(Xs == NULL)
{
return NULL;
}
else if( Xs -> tail == NULL)
{
return NULL;
}
IntList* Ys = &(*Xs -> tail);
return Ys;
}
IntList* IntList::cons( int X, IntList *Xs) {
return new IntList(X, Xs); // creating a new IntList.
}
IntList* IntList::app(vector<int> xs, IntList *Ys) {
IntList *Zs = Ys;
for (int i = xs.size() - 1; i >= 0; i--){
Zs = cons(xs[i], Zs);
}
return Zs;
}
int IntList::len(IntList* Xs) {
return toInts(Xs) -> size();
}
IntStack* IntList::toInts(IntList* Xs){
IntStack* is = new IntStack();
while (!isempty(Xs)) {
is -> push(getHead(Xs));
if(getTail(Xs) == NULL) break;
Xs = getTail(Xs);
if(Xs -> tail == NULL)
is -> push(getHead(Xs));
}
return is;
}
string IntList::toString(){
return IntList::toInts(this) -> toString();
}
IntList::IntList(IntList &other){ // Copy constructor (deep copy)
head = other.head;
*tail = *(other.tail);
*empty = *(other.empty);
}
IntList& IntList::operator=(const IntList&other){
if( this == &other) return *this;
else{
head = other.head;
*tail = *(other.tail);
*empty = *(other.empty);
}
}
IntList::~IntList(){
delete tail;
delete empty;
}
}
/*
Driver functions to test IntList.h (09/18/2017)
***********************************************
*/
// int main(int argc, char *argv[]) {
// int n = 23456, n1 , n2 , n3;
// n = iProlog::random(n);
// iProlog::IntList* s = NULL;
// iProlog::IntList *headEle = new iProlog::IntList(n);
// n = iProlog::random(n);
// iProlog::IntList *curList = new iProlog::IntList(n, headEle);
// cout << "Element in list are: "<< curList -> toString() << endl;
// cout << " IS EMPTY ? " << iProlog::IntList::isempty(s) << endl;
// cout << "Head Element in list: "<< iProlog::IntList::getHead(curList) << endl;
// cout << "Tail Element in list: "<< iProlog::IntList::getTail(headEle)<< endl;
// cout << "Length of list: "<< iProlog::IntList::len(curList)<< endl;
// n = iProlog::random(n);
// cout << "New List after adding one element using cons(): " << iProlog::IntList::cons(n, curList) -> toString() << endl;
// n1 = iProlog::random(n);
// n2 = iProlog::random(n1);
// n3 = iProlog::random(n2);
// cout << "New List after adding array of elements: " << iProlog::IntList::app(vector<int> {n1 , n2, n3}, curList) -> toString() << "\n";
// delete s;
// delete headEle;
// return 0;
// }
/*
UNIT TESTING
JAVA OUTPUT:
E:\Software Engineering\Term Project Clone\IP\src\IProlog_Java>javac -d . IntList.java
E:\Software Engineering\Term Project Clone\IP\src\IProlog_Java>java iProlog/IntList
Element in list are: [20, 10]
Head Element in list: 20
Tail Element in list: [10]
Length of list: 2
New List after adding one element using cons(): [30, 20, 10]
New List after adding array of elements: [40, 50, 60, 20, 10]
C++ OUTPUT:
E:\Software Engineering\Term Project Clone\IP\src\iProlog>g++ IntList.cpp Spine.cpp IntStack.cpp -std=c++11
E:\Software Engineering\Term Project Clone\IP\src\iProlog>a.exe
Element in list are: 20,10
Head Element in list: 20
Tail Element in list: 10
Length of list: 2
New List after adding one element using cons(): 30,20,10
New List after adding array of elements: 40,50,60,20,10
*/
/*
RANDOM TESTING OUTPUT (11/29/2017):
C++ OUTPUT:
E:\Software Engineering\Term Project Clone\IP\src\iProlog>g++ IntList.cpp IntStack.cpp -std=c++11
E:\Software Engineering\Term Project Clone\IP\src\iProlog>a.exe
Element in list are: 466228,220028
Head Element in list: 466228
Tail Element in list: 220028
Length of list: 2
New List after adding one element using cons(): -669348,466228,220028
New List after adding array of elements: 540024,-172465,-128109,466228,220028
*/
| Group5SE/PrologVM | IP/src/iProlog/IntList.cpp | C++ | apache-2.0 | 5,275 |
<?php
foreach ($a as $key) {
?>
<div class="row">
<div class="col-lg-12">
<div class="ibox">
<div class="ibox-content">
<h2>
Edite los datos del nuevo empleado.
</h2>
<form id="formeditempleado" action="<?php echo base_url('login/actualizar'); ?>" method="post">
<div class="right">
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Actualizar Empleado</button>
<a href="<?php echo base_url('empleados'); ?>" class="btn btn-success" ><i class="fa fa-ban"></i> Cancelar</a>
</div>
<h1>Datos Personales</h1>
<fieldset>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<input type="hidden" name="id" value="<?php echo $key->idEmpleados; ?>">
<label class="control-label">Nombres *</label>
<input name="nombre" type="text" class="form-control" value="<?php echo $key->Nombres;?>">
</div>
<div class="form-group">
<label class="control-label">Apellidos *</label>
<input id="apellido" name="apellido" type="text" class="form-control" value="<?php echo $key->Apellidos;?>">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">DNI *</label>
<input id="dni" name="dni" type="number" class="form-control" value="<?php echo $key->Dni;?>" >
</div>
<div class="form-group">
<label class="control-label">Sexo *</label>
<select class="form-control m-b" name="account" required>
<option value="" >-- Seleccione --</option>
<?php
if ($key->Sexo == "M") {
?>
<option value="M" selected>Masculino</option>
<option value="F">Femenino</option>
<?php } else {?>
<option value="M" >Masculino</option>
<option value="F" selected>Femenino</option>
<?php } ?>
</select>
</div>
</div>
</div>
</fieldset>
<h1>Información Complementaria</h1>
<fieldset>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Dirección *</label>
<input id="direccion" name="direccion" type="text" class="form-control" value="<?php echo $key->Direccion;?>">
</div>
<div class="form-group">
<label class="control-label">Fecha Nacimiento *</label>
<div class="input-group date" id="fec_nac">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" value="<?php echo date("d-m-Y",strtotime($key->Fecha_Nacimiento)); ?>" name="fec_nac">
</div>
<!--<input id="fec_nac" name="fec_nac" type="text" class="form-control" data-mask="99/99/9999" value="<?php echo date("d-m-Y",strtotime($key->Fecha_Nacimiento));?>">-->
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Celular *</label>
<input id="celular" name="celular" type="text" class="form-control" value="<?php echo $key->Celular;?>">
</div>
</div>
</div>
</fieldset>
<h1>Cuenta</h1>
<fieldset>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Usuario *</label>
<input id="usuario" name="usuario" type="text" class="form-control" value="<?php echo $key->Usuario;?>" required>
</div>
<div class="form-group">
<label class="control-label">Email *</label>
<input id="email" name="email" type="text" class="form-control" value="<?php echo $key->Correo_Electronico;?>" required="required">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Password *</label>
<input id="password" name="password" type="password" class="form-control" value="<?php echo desencriptar($key->Contrasena);?>">
</div>
<div class="form-group">
<label class="control-label">Confirmar Password *</label>
<input id="confirm" name="confirm" type="password" class="form-control" value="<?php echo desencriptar($key->Contrasena);?>" required>
</div>
</div>
</div>
</fieldset>
<h1>Información Administrativa</h1>
<fieldset>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Cargo *</label>
<select class="form-control" name="cargo">
<option value="" >-- Seleccione --</option>
<?php
if ($key->TipoEmpleado_idTipoEmpleado=="1") {
?>
<option value="1" selected>Administrador</option>
<option value="2">Cajero</option>
<option value="3">Cocina</option>
<option value="4">Repartidor</option>
<?php
}
elseif($key->TipoEmpleado_idTipoEmpleado=="2") {
?>
<option value="1">Administrador</option>
<option value="2" selected>Cajero</option>
<option value="3">Cocina</option>
<option value="4">Repartidor</option>
<?php
}
elseif($key->TipoEmpleado_idTipoEmpleado=="3") {
?>
<option value="1">Administrador</option>
<option value="2">Cajero</option>
<option value="3" selected>Cocina</option>
<option value="4">Repartidor</option>
<?php
}
elseif($key->TipoEmpleado_idTipoEmpleado=="4") {
?>
<option value="1">Administrador</option>
<option value="2">Cajero</option>
<option value="3">Cocina</option>
<option value="4" selected>Repartidor</option>
<?php
}else{
?>
<option value="1">Administrador</option>
<option value="2">Cajero</option>
<option value="3">Cocina</option>
<option value="4" selected>Repartidor</option>
<?php
}
?>
}
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label">Fecha Registro *</label>
<div class="input-group date" id="fec_in">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" value="<?php echo date("d-m-Y",strtotime($key->Fecha_Registro)); ?>" name="fec_in">
</div>
<!--<input id="fec_in" name="fec_in" type="text" data-mask="99/99/9999" class="form-control required" value="<?php echo date("d/m/Y",strtotime($key->Fecha_Registro));?>">-->
</div>
<div class="form-group">
<label class="control-label">Estado *</label>
<select name="estado" class="form-control">
<option value="" >-- Seleccione --</option>
<?php
if ($key->Estado == "A") {
?>
<option value="A" selected="">Habilitado</option>
<option value="X">Deshabilitado</option>
<?php
} else {
?>
<option value="A">Habilitado</option>
<option value="X" selected="">Deshabilitado</option>
<?php
}
?>
</select>
</div>
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<?php
}
?>
| animedy/UTP_APLICACION | UTP_Aplicacion/2. Construccion/2.3. Codigo Fuente/Restaurant/application/views/admin/_editar_empleado.php | PHP | apache-2.0 | 14,696 |
package org.cam.core.domain;
import org.cam.core.cache.Copyable;
import java.io.Serializable;
/**
* Authorization entity.
*/
public interface User extends Serializable,Copyable{
public String getId();
public String getName();
}
| yaohuiwu/CAM | cam-core/src/main/java/org/cam/core/domain/User.java | Java | apache-2.0 | 244 |
/*
* Copyright 2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.neon.activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Filter;
import im.neon.R;
import im.neon.adapters.CountryAdapter;
import im.neon.util.CountryPhoneData;
import im.neon.util.PhoneNumberUtils;
public class CountryPickerActivity extends AppCompatActivity implements CountryAdapter.OnSelectCountryListener, SearchView.OnQueryTextListener {
public static final String EXTRA_IN_WITH_INDICATOR = "EXTRA_IN_WITH_INDICATOR";
public static final String EXTRA_OUT_COUNTRY_NAME = "EXTRA_OUT_COUNTRY_NAME";
public static final String EXTRA_OUT_COUNTRY_CODE = "EXTRA_OUT_COUNTRY_CODE";
public static final String EXTRA_OUT_CALLING_CODE = "EXTRA_OUT_CALLING_CODE";
private RecyclerView mCountryRecyclerView;
private View mCountryEmptyView;
private CountryAdapter mCountryAdapter;
private SearchView mSearchView;
private boolean mWithIndicator;
/*
* *********************************************************************************************
* Static methods
* *********************************************************************************************
*/
public static Intent getIntent(final Context context, final boolean withIndicator) {
final Intent intent = new Intent(context, CountryPickerActivity.class);
intent.putExtra(EXTRA_IN_WITH_INDICATOR, withIndicator);
return intent;
}
/*
* *********************************************************************************************
* Activity lifecycle
* *********************************************************************************************
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_picker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
final Intent intent = getIntent();
mWithIndicator = intent.getBooleanExtra(EXTRA_IN_WITH_INDICATOR, false);
initViews();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_country_picker, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
if (searchItem != null) {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
mSearchView.setMaxWidth(Integer.MAX_VALUE);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.search_hint));
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setOnQueryTextListener(this);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
setResult(RESULT_CANCELED);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mSearchView != null) {
mSearchView.setOnQueryTextListener(null);
}
}
/*
* *********************************************************************************************
* UI
* *********************************************************************************************
*/
private void initViews() {
mCountryEmptyView = findViewById(R.id.country_empty_view);
mCountryRecyclerView = (RecyclerView) findViewById(R.id.country_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mCountryRecyclerView.setLayoutManager(layoutManager);
mCountryAdapter = new CountryAdapter(PhoneNumberUtils.getCountriesWithIndicator(), mWithIndicator, this);
mCountryRecyclerView.setAdapter(mCountryAdapter);
}
private void filterCountries(final String pattern) {
mCountryAdapter.getFilter().filter(pattern, new Filter.FilterListener() {
@Override
public void onFilterComplete(int count) {
mCountryEmptyView.setVisibility(count > 0 ? View.GONE : View.VISIBLE);
}
});
}
/*
* *********************************************************************************************
* Listener
* *********************************************************************************************
*/
@Override
public void onSelectCountry(CountryPhoneData country) {
Intent intent = new Intent();
intent.putExtra(EXTRA_OUT_COUNTRY_NAME, country.getCountryName());
intent.putExtra(EXTRA_OUT_COUNTRY_CODE, country.getCountryCode());
intent.putExtra(EXTRA_OUT_CALLING_CODE, country.getCallingCode());
setResult(RESULT_OK, intent);
finish();
}
@Override
public boolean onQueryTextChange(String newText) {
filterCountries(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
} | noepitome/neon-android | neon/src/main/java/im/neon/activity/CountryPickerActivity.java | Java | apache-2.0 | 6,624 |
/* Copyright 2017 Bennett Dong. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package club.cookbean.sparrow.writer.impl;
import club.cookbean.sparrow.config.WriteBehindConfiguration;
import club.cookbean.sparrow.exception.BulkCacheWritingException;
import club.cookbean.sparrow.redis.Cacheable;
import club.cookbean.sparrow.service.ExecutionService;
import club.cookbean.sparrow.writer.CacheWriter;
import club.cookbean.sparrow.writer.WriteBehind;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class StripedWriteBehind implements WriteBehind {
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
private final List<WriteBehind> stripes = new ArrayList<>();
public StripedWriteBehind(ExecutionService executionService,
String defaultThreadPool,
WriteBehindConfiguration config,
CacheWriter cacheWriter) {
int writeBehindConcurrency = config.getConcurrency();
for (int i = 0; i < writeBehindConcurrency; i++) {
if (config.getBatchingConfiguration() == null) {
this.stripes.add(new NonBatchingWriteBehindQueue(executionService, defaultThreadPool, config, cacheWriter));
} else {
this.stripes.add(new BatchingWriteBehindQueue(executionService, defaultThreadPool, config, cacheWriter));
}
}
}
private WriteBehind getStripe(final Object key) {
return stripes.get(Math.abs(key.hashCode() % stripes.size()));
}
@Override
public void start() {
writeLock.lock();
try {
for (WriteBehind queue : stripes) {
queue.start();
}
} finally {
writeLock.unlock();
}
}
@Override
public void stop() {
writeLock.lock();
try {
for (WriteBehind queue : stripes) {
queue.stop();
}
} finally {
writeLock.unlock();
}
}
@Override
public long getQueueSize() {
int size = 0;
readLock.lock();
try {
for (WriteBehind stripe : stripes) {
size += stripe.getQueueSize();
}
} finally {
readLock.unlock();
}
return size;
}
@Override
public void write(String key, Cacheable value) throws Exception {
readLock.lock();
try {
getStripe(key).write(key, value);
} finally {
readLock.unlock();
}
}
@Override
public void writeAll(Iterable<? extends Entry<String, Cacheable>> entries) throws BulkCacheWritingException, Exception {
for (Entry<String, ? extends Cacheable> entry : entries) {
write(entry.getKey(), entry.getValue());
}
}
@Override
public void delete(String key) throws Exception {
readLock.lock();
try {
getStripe(key).delete(key);
} finally {
readLock.unlock();
}
}
@Override
public void deleteAll(Iterable<String> keys) throws BulkCacheWritingException, Exception {
for (String k : keys) {
delete(k);
}
}
}
| FlyingDuck/sparrow | src/main/java/club/cookbean/sparrow/writer/impl/StripedWriteBehind.java | Java | apache-2.0 | 3,711 |
# Polygonum pyramidatum Loisel. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Polygonaceae/Polygonum/Polygonum pyramidatum/README.md | Markdown | apache-2.0 | 179 |
# 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.
if [ "x$CASSANDRA_HOME" = "x" ]; then
CASSANDRA_HOME="`dirname "$0"`/.."
fi
# The directory where Cassandra's configs live (required)
if [ "x$CASSANDRA_CONF" = "x" ]; then
CASSANDRA_CONF="$CASSANDRA_HOME/conf2"
fi
# This can be the path to a jar file, or a directory containing the
# compiled classes. NOTE: This isn't needed by the startup script,
# it's just used here in constructing the classpath.
cassandra_bin="$CASSANDRA_HOME/build/classes/main"
cassandra_bin="$cassandra_bin:$CASSANDRA_HOME/build/classes/thrift"
#cassandra_bin="$cassandra_home/build/cassandra.jar"
# JAVA_HOME can optionally be set here
#JAVA_HOME=/usr/local/jdk6
# The java classpath (required)
CLASSPATH="$CASSANDRA_CONF:$cassandra_bin"
for jar in "$CASSANDRA_HOME"/lib/*.jar; do
CLASSPATH="$CLASSPATH:$jar"
done
| DavidHerzogTU-Berlin/cassandraToRun | bin/cassandra2.in.sh | Shell | apache-2.0 | 1,594 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (1.8.0_20) on Tue Jan 20 23:37:44 CET 2015 -->
<title>Uses of Package exceptions</title>
<meta name="date" content="2015-01-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package exceptions";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.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?exceptions/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package exceptions" class="title">Uses of Package<br>exceptions</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../exceptions/package-summary.html">exceptions</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="#core">core</a></td>
<td class="colLast">
<div class="block">Contains all the operations done by corporatique</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="core">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../exceptions/package-summary.html">exceptions</a> used by <a href="../core/package-summary.html">core</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../exceptions/class-use/IsNotJarException.html#core">IsNotJarException</a>
<div class="block">Will be triggered if the given path of the plugin during the installation isn't a jar file.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../exceptions/class-use/PluginDependenciesNotPresentException.html#core">PluginDependenciesNotPresentException</a>
<div class="block">Will be triggered if the plugin dependencies are not present.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../exceptions/class-use/PluginNotFoundException.html#core">PluginNotFoundException</a>
<div class="block">Will be triggered if the given plugin isn't installed.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.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?exceptions/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Corporatique-dev/Corporatique | doc/exceptions/package-use.html | HTML | apache-2.0 | 5,662 |
package org.hibernate.validator.test.valid;
import org.hibernate.validator.Valid;
/**
* @author Emmanuel Bernard
*/
public class Form {
private Member member;
@Valid
public Member getMember() {
return member;
}
public void setMember(Member m) {
this.member = m;
}
}
| emmanuelbernard/hibernate-validator | hibernate-validator-legacy/src/test/java/org/hibernate/validator/test/valid/Form.java | Java | apache-2.0 | 303 |
package com.xubin.starclass.utils;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xubin.starclass.R;
import com.xubin.starclass.https.XUtils;
import java.lang.reflect.Type;
/**
* Created by Xubin on 2015/9/2.
*/
public class JsonUtil<T> {
private Type mType;
private TypeReference<T> mReference;
public JsonUtil(Type mType) {
this.mType = mType;
}
public JsonUtil(TypeReference<T> mReference) {
this.mReference = mReference;
}
public T parse(String json){
T t=null;
if (!TextUtils.isEmpty(json)){
if (json.matches("^\\{.*\\}$")) {
if (null != mType) {
t= JSON.parseObject(json, mType);
}else if (null != mReference) {
t=JSON.parseObject(json,mReference);
}
return t;
}else if (json.matches("^\\[\\{.*\\}\\]$")) {
t=JSON.parseObject(json,mReference);
return t;
}else{
XUtils.showToast("json格式不匹配");
}
}else{
XUtils.showToast("json为null或''");
}
return t;
}
}
| hnxylc8818/StarClass | src/main/java/com/xubin/starclass/utils/JsonUtil.java | Java | apache-2.0 | 1,252 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.