code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static int cudnnCreatePersistentRNNPlan(
cudnnRNNDescriptor rnnDesc,
int minibatch,
int dataType,
cudnnPersistentRNNPlan plan)
{
return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan));
} | Expensive. Creates the plan for the specific settings. |
public static int cudnnGetRNNWorkspaceSize(
cudnnHandle handle,
cudnnRNNDescriptor rnnDesc,
int seqLength,
cudnnTensorDescriptor[] xDesc,
long[] sizeInBytes)
{
return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes));
} | dataType in weight descriptors and input descriptors is used to describe storage |
public static int cudnnCTCLoss(
cudnnHandle handle,
cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the
mini batch size, A is the alphabet size) */
Pointer probs, /** probabilities after softmax, in GPU memory */
int[] labels, /** labels, in CPU memory */
int[] labelLengths, /** the length of each label, in CPU memory */
int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */
Pointer costs, /** the returned costs of CTC, in GPU memory */
cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */
Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */
int algo, /** algorithm selected, supported now 0 and 1 */
cudnnCTCLossDescriptor ctcLossDesc,
Pointer workspace, /** pointer to the workspace, in GPU memory */
long workSpaceSizeInBytes)/** the workspace size needed */
{
return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));
} | return the ctc costs and gradients, given the probabilities and labels |
public static int cudnnGetCTCLossWorkspaceSize(
cudnnHandle handle,
cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the
timing steps, N is the mini batch size, A is the alphabet size) */
cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the
dimensions are T,N,A. To compute costs
only, set it to NULL */
int[] labels, /** labels, in CPU memory */
int[] labelLengths, /** the length of each label, in CPU memory */
int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */
int algo, /** algorithm selected, supported now 0 and 1 */
cudnnCTCLossDescriptor ctcLossDesc,
long[] sizeInBytes)/** pointer to the returned workspace size */
{
return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));
} | return the workspace size needed for ctc |
public static int cudnnGetRNNDataDescriptor(
cudnnRNNDataDescriptor RNNDataDesc,
int[] dataType,
int[] layout,
int[] maxSeqLength,
int[] batchSize,
int[] vectorSize,
int arrayLengthRequested,
int[] seqLengthArray,
Pointer paddingFill)
{
return checkResult(cudnnGetRNNDataDescriptorNative(RNNDataDesc, dataType, layout, maxSeqLength, batchSize, vectorSize, arrayLengthRequested, seqLengthArray, paddingFill));
} | symbol for filling padding position in output |
public static int cudnnSetRNNDescriptor_v6(
cudnnHandle handle,
cudnnRNNDescriptor rnnDesc,
int hiddenSize,
int numLayers,
cudnnDropoutDescriptor dropoutDesc,
int inputMode,
int direction,
int mode,
int algo,
int dataType)
{
return checkResult(cudnnSetRNNDescriptor_v6Native(handle, rnnDesc, hiddenSize, numLayers, dropoutDesc, inputMode, direction, mode, algo, dataType));
} | <pre>
DEPRECATED routines to be removed next release :
User should use the non-suffixed version (which has the API and functionality of _v6 version)
Routines with _v5 suffix has the functionality of the non-suffixed routines in the CUDNN V6
</pre> |
public static <T> OptionalValue<T> ofNullable(T value) {
return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);
} | Returns new instance of OptionalValue with given value
@param value wrapped object
@param <T> type of the wrapped object
@return given object wrapped in OptionalValue |
public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) {
return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value);
} | Returns new instance of OptionalValue with given key and value
@param key resource key of the created value
@param value wrapped object
@param <T> type of the wrapped object
@return given object wrapped in OptionalValue with given key |
public static <T extends CObject> T get(Object obj, String path) {
T result = find(obj, RmPath.valueOf(path).segments());
if (result == null) {
throw new AmObjectNotFoundException("Object " + obj + " has no child on path " + path);
}
return result;
} | Gets the object on a path {@code path} relative to {@code obj}
If not found throws {@link IllegalStateException}.
The method returns first object found, and does not check if there are more than one matches.
@param obj Root object from which to search, Must be either an Archetype or CComplexObject
@param path path identifying the object to return.
@param <T> type to remove required casting
@return The object matching the path relative to obj
@throws IllegalStateException if no object is found |
@Nullable
public static <T extends CObject> T find(Object obj, String path) {
return find(obj, RmPath.valueOf(path).segments());
} | Gets the object on a path {@code path} relative to {@code obj}
If not found returns null.
The method returns first object found, and does not check if there are more than one matches.
@param obj Root object from which to search, Must be either an Archetype or CComplexObject
@param path path identifying the object to return.
@param <T> type to remove required casting
@return The object matching the path relative to obj, or null if not found |
public static String stringFor(int n)
{
switch (n)
{
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_0: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_0";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_1: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_1";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED";
case CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT: return "CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT";
}
return "INVALID cudnnConvolutionBwdDataAlgo: "+n;
} | Returns a string representation of the given constant
@return A string representation of the given constant |
protected static SecurityContext createSC(String user, String... roles) {
final Subject subject = new Subject();
final Principal principal = new SimplePrincipal(user);
subject.getPrincipals().add(principal);
if (roles != null) {
for (final String role : roles) {
subject.getPrincipals().add(new SimplePrincipal(role));
}
}
return new DefaultSecurityContext(principal, subject);
} | Create a {@link SecurityContext} to return to the provider
@param user the user principal
@param roles the roles of the user
@return the {@link SecurityContext} |
public static void startDaemon(final String _daemonName, final IDaemonLifecycleListener _lifecycleListener) {
// Run de.taimos.daemon async
Executors.newSingleThreadExecutor().execute(() -> DaemonStarter.doStartDaemon(_daemonName, _lifecycleListener));
} | Starts the daemon and provides feedback through the life-cycle listener<br>
<br>
@param _daemonName the name of this daemon
@param _lifecycleListener the {@link IDaemonLifecycleListener} to use for phase call-backs |
public static void stopService() {
DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING);
final CountDownLatch cdl = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(() -> {
DaemonStarter.getLifecycleListener().stopping();
DaemonStarter.daemon.stop();
cdl.countDown();
});
try {
int timeout = DaemonStarter.lifecycleListener.get().getShutdownTimeoutSeconds();
if (!cdl.await(timeout, TimeUnit.SECONDS)) {
DaemonStarter.rlog.error("Failed to stop gracefully");
DaemonStarter.abortSystem();
}
} catch (InterruptedException e) {
DaemonStarter.rlog.error("Failure awaiting stop", e);
Thread.currentThread().interrupt();
}
} | Stop the service and end the program |
private static void handleSignals() {
if (DaemonStarter.isRunMode()) {
try {
// handle SIGHUP to prevent process to get killed when exiting the tty
Signal.handle(new Signal("HUP"), arg0 -> {
// Nothing to do here
System.out.println("SIG INT");
});
} catch (IllegalArgumentException e) {
System.err.println("Signal HUP not supported");
}
try {
// handle SIGTERM to notify the program to stop
Signal.handle(new Signal("TERM"), arg0 -> {
System.out.println("SIG TERM");
DaemonStarter.stopService();
});
} catch (IllegalArgumentException e) {
System.err.println("Signal TERM not supported");
}
try {
// handle SIGINT to notify the program to stop
Signal.handle(new Signal("INT"), arg0 -> {
System.out.println("SIG INT");
DaemonStarter.stopService();
});
} catch (IllegalArgumentException e) {
System.err.println("Signal INT not supported");
}
try {
// handle SIGUSR2 to notify the life-cycle listener
Signal.handle(new Signal("USR2"), arg0 -> {
System.out.println("SIG USR2");
DaemonStarter.getLifecycleListener().signalUSR2();
});
} catch (IllegalArgumentException e) {
System.err.println("Signal USR2 not supported");
}
}
} | I KNOW WHAT I AM DOING |
public static void abortSystem(final Throwable error) {
DaemonStarter.currentPhase.set(LifecyclePhase.ABORTING);
try {
DaemonStarter.getLifecycleListener().aborting();
} catch (Exception e) {
DaemonStarter.rlog.error("Custom abort failed", e);
}
if (error != null) {
DaemonStarter.rlog.error("Unrecoverable error encountered --> Exiting : {}", error.getMessage());
DaemonStarter.getLifecycleListener().exception(LifecyclePhase.ABORTING, error);
} else {
DaemonStarter.rlog.error("Unrecoverable error encountered --> Exiting");
}
// Exit system with failure return code
System.exit(1);
} | Abort the daemon
@param error the error causing the abortion |
@PostConstruct
public void initDatabase() {
MongoDBInit.LOGGER.info("initializing MongoDB");
String dbName = System.getProperty("mongodb.name");
if (dbName == null) {
throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
}
MongoDatabase db = this.mongo.getDatabase(dbName);
try {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
MongoDBInit.LOGGER.info("Scanning for collection data");
for (Resource res : resources) {
String filename = res.getFilename();
String collection = filename.substring(0, filename.length() - 7);
MongoDBInit.LOGGER.info("Found collection file: {}", collection);
MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
int lines = 0;
while (scan.hasNextLine()) {
String json = scan.nextLine();
Object parse = JSON.parse(json);
if (parse instanceof DBObject) {
DBObject dbObject = (DBObject) parse;
dbCollection.insertOne(dbObject);
} else {
MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
throw new RuntimeException("Invalid object");
}
lines++;
}
MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
}
}
} catch (IOException e) {
throw new RuntimeException("Error importing objects", e);
}
} | init database with demo data |
public static String stringFor(int n)
{
switch (n)
{
case CUDNN_OP_TENSOR_ADD: return "CUDNN_OP_TENSOR_ADD";
case CUDNN_OP_TENSOR_MUL: return "CUDNN_OP_TENSOR_MUL";
case CUDNN_OP_TENSOR_MIN: return "CUDNN_OP_TENSOR_MIN";
case CUDNN_OP_TENSOR_MAX: return "CUDNN_OP_TENSOR_MAX";
case CUDNN_OP_TENSOR_SQRT: return "CUDNN_OP_TENSOR_SQRT";
case CUDNN_OP_TENSOR_NOT: return "CUDNN_OP_TENSOR_NOT";
}
return "INVALID cudnnOpTensorOp: "+n;
} | Returns a string representation of the given constant
@return A string representation of the given constant |
public static ResourceResolutionComponent[] resolve(Object... resolutionParams) {
ResourceResolutionComponent[] components = new ResourceResolutionComponent[resolutionParams.length];
for (int i = 0; i < resolutionParams.length; i++) {
if (resolutionParams[i] == null) {
components[i] = new StringResolutionComponent("");
} else if (resolutionParams[i] instanceof ResourceResolutionComponent) {
components[i] = (ResourceResolutionComponent) resolutionParams[i];
} else if (resolutionParams[i] instanceof Locale) {
components[i] = new LocaleResolutionComponent((Locale) resolutionParams[i]);
} else if (resolutionParams[i] instanceof String) {
components[i] = new StringResolutionComponent((String) resolutionParams[i]);
} else if (resolutionParams[i] instanceof String[]) {
components[i] = new StringResolutionComponent((String[]) resolutionParams[i]);
} else {
components[i] = new StringResolutionComponent(String.valueOf(resolutionParams[i]));
}
}
return components;
} | Helper method to wrap varags into array with {@link #context(ResourceResolutionComponent[],Map)}
@param resolutionParams
@since 3.1
@return |
public static Map<String, Object> with(Object... params) {
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < params.length; i++) {
map.put(String.valueOf(i), params[i]);
}
return map;
} | Convenience wrapper for message parameters
@param params
@return |
public static ResourceResolutionContext context(ResourceResolutionComponent[] components,
Map<String, Object> messageParams) {
return new ResourceResolutionContext(components, messageParams);
} | Build resolution context in which message will be discovered and built
@param components resolution components, used to identify message bundle
@param messageParams message parameters will be substituted in message and used in pattern matching
@since 3.1
@return immutable resolution context instance for given parameters |
public static @NotNull ImmutableValueMap of(@NotNull String k1, @NotNull Object v1) {
return new ImmutableValueMap(ImmutableMap.<String, Object>of(k1, v1));
} | Returns an immutable map containing a single entry. This map behaves and
performs comparably to {@link Collections#singletonMap} but will not accept
a null key or value. It is preferable mainly for consistency and
maintainability of your code.
@param k1 Key 1
@param v1 Value 1
@return ImmutableValueMap |
public static @NotNull ImmutableValueMap of(
@NotNull String k1, @NotNull Object v1,
@NotNull String k2, @NotNull Object v2,
@NotNull String k3, @NotNull Object v3) {
return new ImmutableValueMap(ImmutableMap.<String, Object>of(k1, v1, k2, v2, k3, v3));
} | Returns an immutable map containing the given entries, in order.
@param k1 Key 1
@param v1 Value 1
@param k2 Key 2
@param v2 Value 2
@param k3 Key 3
@param v3 Value 3
@return ImmutableValueMap
@throws IllegalArgumentException if duplicate keys are provided |
public static @NotNull ImmutableValueMap copyOf(@NotNull Map<String, Object> map) {
if (map instanceof ValueMap) {
return new ImmutableValueMap((ValueMap)map);
}
else {
return new ImmutableValueMap(map);
}
} | Returns an immutable map containing the same entries as {@code map}. If {@code map} somehow contains entries with
duplicate keys (for example, if
it is a {@code SortedMap} whose comparator is not <i>consistent with
equals</i>), the results of this method are undefined.
<p>
Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The
exact circumstances under which a copy will or will not be performed are undocumented and subject to change.
@param map Map
@return ImmutableValueMap
@throws NullPointerException if any key or value in {@code map} is null |
public final <R> Iterable<R> mapReduce(String name, final MapReduceResultHandler<R> conv) {
return this.mapReduce(name, null, null, null, conv);
} | runs a map-reduce-job on the collection. same as {@link #mapReduce(String, DBObject, DBObject, Map, MapReduceResultHandler)
mapReduce(name, null, null, null, conv)}
@param <R> the type of the result class
@param name the name of the map-reduce functions
@param conv the converter to convert the result
@return an {@link Iterable} with the result entries |
public final <R> Iterable<R> mapReduce(String name, DBObject query, DBObject sort, Map<String, Object> scope, final MapReduceResultHandler<R> conv) {
String map = this.getMRFunction(name, "map");
String reduce = this.getMRFunction(name, "reduce");
MapReduceCommand mrc = new MapReduceCommand(this.collection.getDBCollection(), map, reduce, null, MapReduceCommand.OutputType.INLINE, query);
String finalizeFunction = this.getMRFunction(name, "finalize");
if(finalizeFunction != null) {
mrc.setFinalize(finalizeFunction);
}
if(sort != null) {
mrc.setSort(sort);
}
if(scope != null) {
mrc.setScope(scope);
}
MapReduceOutput mr = this.collection.getDBCollection().mapReduce(mrc);
return new ConverterIterable<R>(mr.results().iterator(), conv);
} | runs a map-reduce-job on the collection. The functions are read from the classpath in the folder mongodb. The systems reads them from
files called <name>.map.js, <name>.reduce.js and optionally <name>.finalize.js. After this the result is converted
using the given {@link MapReduceResultHandler}
@param <R> the type of the result class
@param name the name of the map-reduce functions
@param query the query to filter the elements used for the map-reduce
@param sort sort query to sort elements before running map-reduce
@param scope the global scope for the JavaScript run
@param conv the converter to convert the result
@return an {@link Iterable} with the result entries
@throws RuntimeException if resources cannot be read |
public final <P> List<P> convertIterable(Iterable<P> as) {
List<P> objects = new ArrayList<>();
for(P mp : as) {
objects.add(mp);
}
return objects;
} | converts the given {@link Iterable} to a {@link List}
@param <P> the element type
@param as the {@link Iterable}
@return the converted {@link List} |
public final List<T> findByQuery(String query, Object... params) {
return this.findSortedByQuery(query, null, params);
} | finds all elements matching the given query
@param query the query to search for
@param params the parameters to replace # symbols
@return the list of elements found |
public final List<T> findSortedByQuery(String query, String sort, Object... params) {
return this.findSortedByQuery(query, sort, (Integer) null, (Integer) null, params);
} | finds all elements matching the given query and sorts them accordingly
@param query the query to search for
@param sort the sort query to apply
@param params the parameters to replace # symbols
@return the list of elements found |
public final List<T> findSortedByQuery(String query, String sort, Integer skip, Integer limit, Object... params) {
return this.findSortedByQuery(query, sort, skip, limit, null, this.entityClass, params);
} | finds all elements matching the given query and sorts them accordingly
@param query the query to search for
@param sort the sort query to apply
@param skip the number of elements to skip
@param limit the number of elements to fetch
@param params the parameters to replace # symbols
@return the list of elements found |
public final <P> List<P> findSortedByQuery(String query, String sort, Integer skip, Integer limit, String projection, Class<P> as, Object... params) {
Find find = this.createFind(query, sort, skip, limit, projection, params);
return this.convertIterable(find.as(as));
} | finds all elements matching the given query and sorts them accordingly. With this method it is possible to specify a projection to
rename or filter fields in the result elements. Instead of returning objects it returns objects of type
<code>as</code>
@param query the query to search for
@param sort the sort query to apply
@param skip the number of elements to skip
@param limit the number of elements to fetch
@param projection the projection of fields to use
@param as the target to convert result elements to
@param params the parameters to replace # symbols
@param <P> the element type
@return the list of elements found |
public final <P> List<P> findSortedByQuery(String query, String sort, Integer skip, Integer limit, String projection, ResultHandler<P> handler, Object... params) {
Find find = this.createFind(query, sort, skip, limit, projection, params);
return this.convertIterable(find.map(handler));
} | finds all elements matching the given query and sorts them accordingly. With this method it is possible to specify a projection to
rename or filter fields in the result elements. Instead of returning objects it returns objects converted
by the given {@link ResultHandler}
@param query the query to search for
@param sort the sort query to apply
@param skip the number of elements to skip
@param limit the number of elements to fetch
@param projection the projection of fields to use
@param handler the handler to convert result elements with
@param params the parameters to replace # symbols
@param <P> the element type
@return the list of elements found |
public final List<T> searchSorted(String searchString, String sort) {
return this.findSortedByQuery(FULLTEXT_QUERY, sort, searchString);
} | finds all elements containing the given searchString in any text field and sorts them accordingly.
@param searchString the searchString to search for
@param sort the sort query to apply
@return the list of elements found |
public final Optional<T> findFirstByQuery(String query, String sort, Object... params) {
Find find = this.collection.find(query, params);
if((sort != null) && !sort.isEmpty()) {
find.sort(sort);
}
Iterable<T> as = find.limit(1).as(this.entityClass);
Iterator<T> iterator = as.iterator();
if(iterator.hasNext()) {
return Optional.of(iterator.next());
}
return Optional.empty();
} | queries with the given string, sorts the result and returns the first element. <code>null</code> is returned if no element is found.
@param query the query string
@param sort the sort string
@param params the parameters to replace # symbols
@return the first element found or <code>null</code> if none is found |
static ValueMatch<Predicate<Number>> andCondition(Cursor cursor) {
return cursor.expect(LDML::relation, LDML::and);
} | and_condition = relation ('and' relation)* |
public void signalReady(String stackName, String resourceName) {
Preconditions.checkArgument(stackName != null && !stackName.isEmpty());
Preconditions.checkArgument(resourceName != null && !resourceName.isEmpty());
SignalResourceRequest req = new SignalResourceRequest();
req.setLogicalResourceId(resourceName);
req.setStackName(stackName);
req.setStatus(ResourceSignalStatus.SUCCESS);
req.setUniqueId(this.ec2Context.getInstanceId());
this.cloudFormationClient.signalResource(req);
} | signal success to the given CloudFormation stack.<br>
<br>
Needed AWS actions:
<ul>
<li>cloudformation:SignalResource</li>
</ul> |
public void signalReady(String resourceName) {
Preconditions.checkArgument(resourceName != null && !resourceName.isEmpty());
Map<String, String> hostTags = this.ec2Context.getInstanceTags();
this.signalReady(hostTags.get(TAG_CLOUDFORMATION_STACK_NAME), resourceName);
} | signal success to the current CloudFormation stack.<br>
<br>
Needed AWS actions:
<ul>
<li>ec2:DescribeInstances</li>
<li>cloudformation:SignalResource</li>
</ul>
@param resourceName the resource to signal |
public void signalReady() {
Map<String, String> hostTags = this.ec2Context.getInstanceTags();
this.signalReady(hostTags.get(TAG_CLOUDFORMATION_STACK_NAME), hostTags.get(TAG_CLOUDFORMATION_LOGICAL_ID));
} | signal success to the current CloudFormation stack.<br>
The resource is derived from the instance tags
<br>
Needed AWS actions:
<ul>
<li>ec2:DescribeInstances</li>
<li>cloudformation:SignalResource</li>
</ul> |
@Inject("struts.json.action.fileProtocols")
public void setFileProtocols(String fileProtocols) {
if (StringUtils.isNotBlank(fileProtocols)) {
this.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols);
}
} | File URLs whose protocol are in these list will be processed as jars
containing classes
@param fileProtocols
Comma separated list of file protocols that will be considered
as jar files and scanned |
protected Map<String, List<Json>> getActionAnnotations(Class<?> actionClass) {
Method[] methods = actionClass.getMethods();
Map<String, List<Json>> map = new HashMap<String, List<Json>>();
for (Method method : methods) {
Json ann = method.getAnnotation(Json.class);
if (ann != null) {
map.put(method.getName(), Arrays.asList(ann));
}
}
return map;
} | Locates all of the {@link Json} annotations on methods within the Action
class and its parent classes.
@param actionClass
The action class.
@return The list of annotations or an empty list if there are none. |
protected boolean cannotInstantiate(Class<?> actionClass) {
return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()
|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();
} | Interfaces, enums, annotations, and abstract classes cannot be
instantiated.
@param actionClass
class to check
@return returns true if the class cannot be instantiated or should be
ignored |
protected boolean includeClassNameInActionScan(String className) {
String classPackageName = StringUtils.substringBeforeLast(className, ".");
return (checkActionPackages(classPackageName) || checkPackageLocators(classPackageName))
&& checkExcludePackages(classPackageName);
} | Note that we can't include the test for {@link #actionSuffix} here
because a class is included if its name ends in {@link #actionSuffix} OR
it implements {@link com.opensymphony.xwork2.Action}. Since the whole
goal is to avoid loading the class if we don't have to, the (actionSuffix
|| implements Action) test will have to remain until later. See
{@link #getActionClassTest()} for the test performed on the loaded
{@link ClassInfo} structure.
@param className
the name of the class to test
@return true if the specified class should be included in the
package-based action scan |
protected boolean checkExcludePackages(String classPackageName) {
if (excludePackages != null && excludePackages.length > 0) {
WildcardHelper wildcardHelper = new WildcardHelper();
// we really don't care about the results, just the boolean
Map<String, String> matchMap = new HashMap<String, String>();
for (String packageExclude : excludePackages) {
int[] packagePattern = wildcardHelper.compilePattern(packageExclude);
if (wildcardHelper.match(matchMap, classPackageName, packagePattern)) {
return false;
}
}
}
return true;
} | Checks if provided class package is on the exclude list
@param classPackageName
name of class package
@return false if class package is on the {@link #excludePackages} list |
protected boolean checkActionPackages(String classPackageName) {
if (actionPackages != null) {
for (String packageName : actionPackages) {
String strictPackageName = packageName + ".";
if (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName))
return true;
}
}
return false;
} | Checks if class package match provided list of action packages
@param classPackageName
name of class package
@return true if class package is on the {@link #actionPackages} list |
protected boolean checkPackageLocators(String classPackageName) {
if (packageLocators != null && !disablePackageLocatorsScanning && classPackageName.length() > 0
&& (packageLocatorsBasePackage == null || classPackageName.startsWith(packageLocatorsBasePackage))) {
for (String packageLocator : packageLocators) {
String[] splitted = classPackageName.split("\\.");
if (es.cenobit.struts2.json.util.StringUtils.contains(splitted, packageLocator, false))
return true;
}
}
return false;
} | Checks if class package match provided list of package locators
@param classPackageName
name of class package
@return true if class package is on the {@link #packageLocators} list |
private static List<Segment> parseSegments(String origPathStr) {
String pathStr = origPathStr;
if (!pathStr.startsWith("/")) {
pathStr = pathStr + "/";
}
List<Segment> result = new ArrayList<>();
for (String segmentStr : PATH_SPLITTER.split(pathStr)) {
Matcher m = SEGMENT_PATTERN.matcher(segmentStr);
if (!m.matches()) {
throw new IllegalArgumentException("Bad aql path: " + origPathStr);
}
Segment segment = new Segment();
segment.attribute = m.group(1);
segment.nodeId = m.groupCount() >= 3 ? m.group(3) : null;
result.add(segment);
}
return result;
} | currently does not support paths with name constrains |
public void serializeBean(Object obj, Set<String> attributesToIgnore) {
builder.newIndentedline();
try {
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
List<NameValue> values = new ArrayList<>();
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
if (pd.getName().equals("class")) continue;
Object value = pd.getReadMethod().invoke(obj);
if (value == null) continue;
if (value instanceof List && ((List) value).isEmpty()) continue;
String attribute = getAttributeForField(pd.getName());
if (!attributesToIgnore.contains(attribute)) {
values.add(new NameValue(attribute, value, value instanceof List && isPlainType(((List) value).get(0))));
}
}
for (int i = 0; i < values.size(); i++) {
NameValue value = values.get(i);
builder.append(value.name).append(" = ");
if (value.plain) {
serializePlain(value.value);
} else {
serialize(value.value);
}
if (i < values.size() - 1) {
builder.newline();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
builder.unindent().newline();
} | Serializes bean, without wrapping it with </>
@param obj bean to serialize
@param attributesToIgnore attributes that are not written to dadl |
public static String stringFor(int n)
{
switch (n)
{
case CUDNN_DATA_FLOAT: return "CUDNN_DATA_FLOAT";
case CUDNN_DATA_DOUBLE: return "CUDNN_DATA_DOUBLE";
case CUDNN_DATA_HALF: return "CUDNN_DATA_HALF";
case CUDNN_DATA_INT8: return "CUDNN_DATA_INT8";
case CUDNN_DATA_INT32: return "CUDNN_DATA_INT32";
case CUDNN_DATA_INT8x4: return "CUDNN_DATA_INT8x4";
case CUDNN_DATA_UINT8: return "CUDNN_DATA_UINT8";
case CUDNN_DATA_UINT8x4: return "CUDNN_DATA_UINT8x4";
}
return "INVALID cudnnDataType: "+n;
} | Returns a string representation of the given constant
@return A string representation of the given constant |
okhttp3.Response get(String url, Map<String, Object> params)
throws RequestException, LocalOperationException {
String fullUrl = getFullUrl(url);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(addUrlParams(fullUrl, toPayload(params)))
.addHeader("Transloadit-Client", version)
.build();
try {
return httpClient.newCall(request).execute();
} catch (IOException e) {
throw new RequestException(e);
}
} | Makes http GET request.
@param url url to makes request to
@param params data to add to params field
@return {@link okhttp3.Response}
@throws RequestException
@throws LocalOperationException |
okhttp3.Response post(String url, Map<String, Object> params,
@Nullable Map<String, String> extraData,
@Nullable Map<String, File> files, @Nullable Map<String, InputStream> fileStreams)
throws RequestException, LocalOperationException {
Map<String, String> payload = toPayload(params);
if (extraData != null) {
payload.putAll(extraData);
}
okhttp3.Request request = new okhttp3.Request.Builder().url(getFullUrl(url))
.post(getBody(payload, files, fileStreams))
.addHeader("Transloadit-Client", version)
.build();
try {
return httpClient.newCall(request).execute();
} catch (IOException e) {
throw new RequestException(e);
}
} | Makes http POST request
@param url url to makes request to
@param params data to add to params field
@param extraData data to send along with request body, outside of params field.
@param files files to be uploaded along with the request.
@return {@link okhttp3.Response}
@throws RequestException
@throws LocalOperationException |
okhttp3.Response delete(String url, Map<String, Object> params)
throws RequestException, LocalOperationException {
okhttp3.Request request = new okhttp3.Request.Builder()
.url(getFullUrl(url))
.delete(getBody(toPayload(params), null))
.addHeader("Transloadit-Client", version)
.build();
try {
return httpClient.newCall(request).execute();
} catch (IOException e) {
throw new RequestException(e);
}
} | Makes http DELETE request
@param url url to makes request to
@param params data to add to params field
@return {@link okhttp3.Response}
@throws RequestException
@throws LocalOperationException |
private String getFullUrl(String url) {
return url.startsWith("https://") || url.startsWith("http://") ? url : transloadit.getHostUrl() + url;
} | Converts url path to the Transloadit full url.
Returns the url passed if it is already full.
@param url
@return String |
private RequestBody getBody(Map<String, String> data, @Nullable Map<String, File> files, @Nullable Map<String,
InputStream> fileStreams) throws LocalOperationException {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (files != null) {
for (Map.Entry<String, File> entry : files.entrySet()) {
File file = entry.getValue();
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
builder.addFormDataPart(entry.getKey(), file.getName(),
RequestBody.create(MediaType.parse(mimeType), file));
}
}
if (fileStreams != null) {
for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {
byte[] bytes;
InputStream stream = entry.getValue();
try {
bytes = new byte[stream.available()];
stream.read(bytes);
} catch (IOException e) {
throw new LocalOperationException(e);
}
builder.addFormDataPart(entry.getKey(), null,
RequestBody.create(MediaType.parse("application/octet-stream"), bytes));
}
}
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.addFormDataPart(entry.getKey(), entry.getValue());
}
return builder.build();
} | Builds okhttp3 compatible request body with the data passed.
@param data data to add to request body
@param files files to upload
@return {@link RequestBody} |
private Map<String, String> toPayload(Map<String, Object> data) throws LocalOperationException {
Map<String, Object> dataClone = new HashMap<String, Object>(data);
dataClone.put("auth", getAuthData());
Map<String, String> payload = new HashMap<String, String>();
payload.put("params", jsonifyData(dataClone));
if (transloadit.shouldSignRequest) {
payload.put("signature", getSignature(jsonifyData(dataClone)));
}
return payload;
} | Returns data tree structured as Transloadit expects it.
@param data
@return {@link Map}
@throws LocalOperationException |
private String jsonifyData(Map<String, ? extends Object> data) {
JSONObject jsonData = new JSONObject(data);
return jsonData.toString();
} | converts Map of data to json string
@param data map data to converted to json
@return {@link String} |
public static int getAbsoluteLevel(@NotNull String path) {
if (StringUtils.isEmpty(path) || StringUtils.equals(path, "/")) {
return -1;
}
return StringUtils.countMatches(path, "/") - 1;
} | Gets level from parent use same logic (but reverse) as {@link com.day.text.Text#getAbsoluteParent(String, int)}.
@param path Path
@return level >= 0 if path is value, -1 if path is invalid |
public static @Nullable String get(@NotNull ServletRequest request, @NotNull String param) {
return get(request, param, null);
} | Returns a request parameter.<br>
In addition the method fixes problems with incorrect UTF-8 characters returned by the servlet engine.
All character data is converted from ISO-8859-1 to UTF-8 if not '_charset_' parameter is provided.
@param request Request.
@param param Parameter name.
@return Parameter value or null if it is not set. |
public static @Nullable String get(@NotNull ServletRequest request, @NotNull String param, @Nullable String defaultValue) {
String value = request.getParameter(param);
if (value != null) {
// convert encoding to UTF-8 if not form encoding parameter is set
if (!hasFormEncodingParam(request)) {
value = convertISO88591toUTF8(value);
}
return value;
}
else {
return defaultValue;
}
} | Returns a request parameter.<br>
In addition the method fixes problems with incorrect UTF-8 characters returned by the servlet engine.
All character data is converted from ISO-8859-1 to UTF-8 if not '_charset_' parameter is provided.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or the default value if it is not set. |
public static String @Nullable [] getMultiple(@NotNull ServletRequest request, @NotNull String param) {
String[] values = request.getParameterValues(param);
if (values == null) {
return null;
}
// convert encoding to UTF-8 if not form encoding parameter is set
if (!hasFormEncodingParam(request)) {
String[] convertedValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
convertedValues[i] = convertISO88591toUTF8(values[i]);
}
}
return convertedValues;
}
else {
return values;
}
} | Returns a request parameter array.<br>
The method fixes problems with incorrect UTF-8 characters returned by the servlet engine.
All character data is converted from ISO-8859-1 to UTF-8.
@param request Request.
@param param Parameter name.
@return Parameter value array value or null if it is not set. |
public static @Nullable String get(@NotNull Map<String, String[]> requestMap, @NotNull String param) {
String value = null;
String[] valueArray = requestMap.get(param);
if (valueArray != null && valueArray.length > 0) {
value = valueArray[0];
}
// convert encoding to UTF-8 if not form encoding parameter is set
if (value != null && !hasFormEncodingParam(requestMap)) {
value = convertISO88591toUTF8(value);
}
return value;
} | Returns a request parameter.<br>
In addition the method fixes problems with incorrect UTF-8 characters returned by the servlet engine.
All character data is converted from ISO-8859-1 to UTF-8.
@param requestMap Request Parameter map.
@param param Parameter name.
@return Parameter value or null if it is not set. |
public static int getInt(@NotNull ServletRequest request, @NotNull String param) {
return getInt(request, param, 0);
} | Returns a request parameter as integer.
@param request Request.
@param param Parameter name.
@return Parameter value or 0 if it does not exist or is not a number. |
public static int getInt(@NotNull ServletRequest request, @NotNull String param, int defaultValue) {
String value = request.getParameter(param);
return NumberUtils.toInt(value, defaultValue);
} | Returns a request parameter as integer.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or default value if it does not exist or is not a number. |
public static long getLong(@NotNull ServletRequest request, @NotNull String param) {
return getLong(request, param, 0L);
} | Returns a request parameter as long.
@param request Request.
@param param Parameter name.
@return Parameter value or 0 if it does not exist or is not a number. |
public static long getLong(@NotNull ServletRequest request, @NotNull String param, long defaultValue) {
String value = request.getParameter(param);
return NumberUtils.toLong(value, defaultValue);
} | Returns a request parameter as long.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or default value if it does not exist or is not a number. |
public static float getFloat(@NotNull ServletRequest request, @NotNull String param) {
return getFloat(request, param, 0f);
} | Returns a request parameter as float.
@param request Request.
@param param Parameter name.
@return Parameter value or 0 if it does not exist or is not a number. |
public static float getFloat(@NotNull ServletRequest request, @NotNull String param, float defaultValue) {
String value = request.getParameter(param);
return NumberUtils.toFloat(value, defaultValue);
} | Returns a request parameter as float.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or default value if it does not exist or is not a number. |
public static double getDouble(@NotNull ServletRequest request, @NotNull String param) {
return getDouble(request, param, 0d);
} | Returns a request parameter as double.
@param request Request.
@param param Parameter name.
@return Parameter value or 0 if it does not exist or is not a number. |
public static double getDouble(@NotNull ServletRequest request, @NotNull String param, double defaultValue) {
String value = request.getParameter(param);
return NumberUtils.toDouble(value, defaultValue);
} | Returns a request parameter as double.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or default value if it does not exist or is not a number. |
public static boolean getBoolean(@NotNull ServletRequest request, @NotNull String param) {
return getBoolean(request, param, false);
} | Returns a request parameter as boolean.
@param request Request.
@param param Parameter name.
@return Parameter value or <code>false</code> if it does not exist or cannot be interpreted as boolean. |
public static boolean getBoolean(@NotNull ServletRequest request, @NotNull String param, boolean defaultValue) {
String value = request.getParameter(param);
return BooleanUtils.toBoolean(value);
} | Returns a request parameter as boolean.
@param request Request.
@param param Parameter name.
@param defaultValue Default value.
@return Parameter value or default value if it does not exist or <code>false</code> if it cannot be interpreted as
boolean. |
public static <T extends Enum> @Nullable T getEnum(@NotNull ServletRequest request, @NotNull String param, @NotNull Class<T> enumClass) {
return getEnum(request, param, enumClass, null);
} | Returns a request parameter as enum value.
@param <T> Enum type
@param request Request.
@param param Parameter name.
@param enumClass Enum class
@return Parameter value or null if it is not set or an invalid enum value. |
@SuppressWarnings("unchecked")
public static <T extends Enum> @Nullable T getEnum(@NotNull ServletRequest request, @NotNull String param, @NotNull Class<T> enumClass,
@Nullable T defaultValue) {
String value = RequestParam.get(request, param);
if (StringUtils.isNotEmpty(value)) {
try {
return (T)Enum.valueOf(enumClass, value);
}
catch (IllegalArgumentException ex) {
// ignore, return default
}
}
return defaultValue;
} | Returns a request parameter as enum value.
@param <T> Enum type
@param request Request.
@param param Parameter name.
@param enumClass Enum class
@param defaultValue Default value.
@return Parameter value or the default value if it is not set or an invalid enum value. |
private static String convertISO88591toUTF8(String value) {
try {
return new String(value.getBytes(CharEncoding.ISO_8859_1), CharEncoding.UTF_8);
}
catch (UnsupportedEncodingException ex) {
// ignore and fallback to original encoding
return value;
}
} | Converts a string from ISO-8559-1 encoding to UTF-8.
@param value ISO-8559-1 value
@return UTF-8 value |
@Override
public Result getResult() throws Exception {
Result returnResult = result;
// If we've chained to other Actions, we need to find the last result
while (returnResult instanceof ActionChainResult) {
ActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();
if (aProxy != null) {
Result proxyResult = aProxy.getInvocation().getResult();
if ((proxyResult != null) && (aProxy.getExecuteResult())) {
returnResult = proxyResult;
} else {
break;
}
} else {
break;
}
}
return returnResult;
} | If the DefaultActionInvocation has been executed before and the Result is
an instance of ActionChainResult, this method will walk down the chain of
ActionChainResults until it finds a non-chain result, which will be
returned. If the DefaultActionInvocation's result has not been executed
before, the Result instance will be created and populated with the result
params.
@return a Result instance
@throws Exception |
private void executeResult() throws Exception {
result = createResult();
String timerKey = "executeResult: " + getResultCode();
try {
UtilTimerStack.push(timerKey);
if (result != null) {
result.execute(this);
} else if (resultCode != null && !Action.NONE.equals(resultCode)) {
throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()
+ " and result " + getResultCode(), proxy.getConfig());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No result returned for action " + getAction().getClass().getName() + " at "
+ proxy.getConfig().getLocation());
}
}
} finally {
UtilTimerStack.pop(timerKey);
}
} | Uses getResult to get the final Result and executes it
@throws ConfigurationException
If not result can be found with the returned code |
@Override
public ActionInvocation deserialize(ActionContext actionContext) {
JsonActionInvocation that = this;
that.container = actionContext.getContainer();
return that;
} | Restoring Container
@param actionContext
current {@link ActionContext}
@return instance which can be used to invoke action |
protected <C> C convert(Object object, Class<C> targetClass) {
return this.mapper.convertValue(object, targetClass);
} | convert object into another class using the JSON mapper
@param <C> the generic target type
@param object the object to convert
@param targetClass the class of the target object
@return the converted object
@throws IllegalArgumentException if conversion fails |
protected final void sendObjectToSocket(final Object objectToSend) {
this.sendObjectToSocket(objectToSend, new WriteCallback() {
@Override
public void writeSuccess() {
ServerJSONWebSocketAdapter.LOGGER.debug("Send data to socket: {}", objectToSend);
}
@Override
public void writeFailed(Throwable x) {
ServerJSONWebSocketAdapter.LOGGER.error("Error sending message to socket", x);
}
});
} | send object to client and serialize it using JSON<br>
uses a generic callback that prints errors to the log
@param objectToSend the object to send |
protected final void sendObjectToSocket(Object objectToSend, WriteCallback cb) {
Session sess = this.getSession();
if (sess != null) {
String json;
try {
json = this.mapper.writeValueAsString(objectToSend);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize object", e);
}
sess.getRemote().sendString(json, cb);
}
} | send object to client and serialize it using JSON
@param objectToSend the object to send
@param cb the callback after sending the message |
public List<String> deviceTypes() {
Integer count = json().size(DEVICE_FAMILIES);
List<String> deviceTypes = new ArrayList<String>(count);
for(int i = 0 ; i < count ; i++) {
String familyNumber = json().stringValue(DEVICE_FAMILIES, i);
if(familyNumber.equals("1")) deviceTypes.add("iPhone");
if(familyNumber.equals("2")) deviceTypes.add("iPad");
}
return deviceTypes;
} | The list of device types on which this application can run. |
public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {
return !searchForAnnotation(method, annotation).isEmpty();
} | Checks if there is an annotation of the given type on this method or on type level for all interfaces and superclasses
@param method the method to scan
@param annotation the annotation to search for
@return <i>true</i> if the given annotation is present on method or type level annotations in the type hierarchy |
public static <T extends Annotation> List<T> searchForAnnotation(Method method, Class<T> annotation) {
if (method == null) {
return Lists.newArrayList();
}
return searchClasses(method, annotation, method.getDeclaringClass());
} | Searches for all annotations of the given type on this method or on type level for all interfaces and superclasses
@param method the method to scan
@param annotation the annotation to search for
@param <T> the type of the annotation
@return the list of all method or type level annotations in the type hierarchy |
public void addStep(String name, String robot, Map<String, Object> options){
steps.addStep(name, robot, options);
} | Adds a step to the steps.
@param name {@link String} name of the step
@param robot {@link String} name of the robot used by the step.
@param options {@link Map} extra options required for the step. |
void merge(Archetype flatParent, Archetype specialized) {
expandAttributeNodes(specialized.getDefinition());
flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());
mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());
if (flatParent.getAnnotations() != null) {
if (specialized.getAnnotations() == null) {
specialized.setAnnotations(new ResourceAnnotations());
}
annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());
}
} | Merges a specialized archetype with its parent. Merge will be done in-place on the specialized parameter.
@param flatParent Flat parent archetype
@param specialized Specialized archetype |
private void expandAttributeNodes(CComplexObject sourceObject) {
List<CAttribute> differentialAttributes = Lists.newArrayList();
for (CAttribute cAttribute : sourceObject.getAttributes()) {
if (cAttribute.getDifferentialPath() != null) {
differentialAttributes.add(cAttribute);
}
}
for (CAttribute specializedAttribute : differentialAttributes) {
expandAttribute(sourceObject, specializedAttribute);
sourceObject.getAttributes().remove(specializedAttribute);
}
for (CAttribute cAttribute : sourceObject.getAttributes()) {
for (CObject cObject : cAttribute.getChildren()) {
if (cObject instanceof CComplexObject) {
expandAttributeNodes((CComplexObject) cObject);
}
}
}
} | /* expands differential paths into actual nodes |
private List<Pair<CObject>> getChildPairs(RmPath path, CAttribute parent, CAttribute specialized) {
List<Pair<CObject>> result = new ArrayList<>();
for (CObject parentChild : parent.getChildren()) {
result.add(new Pair<>(parentChild, findSpecializedConstraintOfParentNode(specialized, parentChild)));
}
for (CObject specializedChild : specialized.getChildren()) {
CObject parentChild = findParentConstraintOfSpecializedNode(parent, specializedChild.getNodeId());
if (parentChild == null) {
int index = getOrderIndex(path, result, specializedChild);
if (index >= 0) {
result.add(index, new Pair<>(parentChild, specializedChild));
} else {
result.add(new Pair<>(parentChild, specializedChild));
}
}
}
return result;
} | /* Returns matching (parent,specialized) pairs of children of an attribute, in the order they should be present in
the flattened model. One of the element may be null in case of no specialization or extension. |
public static void addTTLIndex(DBCollection collection, String field, int ttl) {
if (ttl <= 0) {
throw new IllegalArgumentException("TTL must be positive");
}
collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject("expireAfterSeconds", ttl));
} | adds a TTL index to the given collection. The TTL must be a positive integer.
@param collection the collection to use for the TTL index
@param field the field to use for the TTL index
@param ttl the TTL to set on the given field
@throws IllegalArgumentException if the TTL is less or equal 0 |
public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {
int dir = (asc) ? 1 : -1;
collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject("background", background));
} | Add an index on the given collection and field
@param collection the collection to use for the index
@param field the field to use for the index
@param asc the sorting direction. <code>true</code> to sort ascending; <code>false</code> to sort descending
@param background iff <code>true</code> the index is created in the background |
void checkRmModelConformance() {
final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor());
ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext());
} | Check if information model entity referenced by archetype
has right name or type |
public static final ResourceKey plain(String key) {
int idx = key.lastIndexOf(BUNDLE_ID_SEPARATOR);
if (idx < 0) {
return new ResourceKey(null, key);
}
String bundle = idx > 0 ? key.substring(0, idx) : null;
String id = idx < key.length() - 1 ? key.substring(idx + 1) : null;
return key(bundle, id);
} | Constructs new resource key from plain string according to following rules:<ul>
<li>Last dot in the string separates key bundle from key id.</li>
<li>Strings starting from the dot represent a key with <code>null</code> bundle (default bundle).</li>
<li>Strings ending with a dot represent keys with <code>null</code> id (bundles).</li>
</ul>
This operation is inversion of {@link #toString()} method for identifiers
not containing {@link #ID_COMPONENT_DELIMITER} character:<ul>
<li>string.equals(plain(string).toString())</li>
<li>key.equals(plain(key.toString()))</li>
</ul>
@param key string representation of a key
@return the key corresponding to given string |
public static ResourceKey key(Enum<?> value) {
return new ResourceKey(value.getClass().getName(), value.name());
} | Creates a resource key for given enumeration value. By convention,
resource bundle for enumerations has the name of enumeration class
and value identifier is the same as enumeration value name.
@param value the enumeration value
@return the resource key |
public static ResourceKey key(Class<?> clazz, String id) {
return new ResourceKey(clazz.getName(), id);
} | Creates a resource key with given id for bundle specified by given class.
@param clazz the class owning the bundle.
@param id value identifier
@return the resource key |
public static ResourceKey key(Class<?> clazz, Enum<?> value) {
return new ResourceKey(clazz.getName(), value.name());
} | Creates a resource key with id defined as enumeration value name and bundle specified by given class.
@param clazz the class owning the bundle
@param value enumeration value used to define key id
@return the resource key |
public static ResourceKey key(Enum<?> enumValue, String key) {
return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key);
} | Creates a resource key defined as a child of key defined by enumeration value.
@see #key(Enum)
@see #child(String)
@param enumValue the enumeration value defining the parent key
@param key the child id
@return the resource key |
public ResourceKey child(String childId) {
return new ResourceKey(bundle, id == null ? childId : join(id, childId));
} | Derives new resource key from this key with identifier as defined below:
<pre>
<delimiter> ::= '_'
<id> ::= <this id> <delimiter> <child id>
</pre>
Example:
<pre>
ResourceKey k1 = key("mybundle","value").child("name");
ResourceKey k2 = key("mybundle", "value.name");
k1.equals(k2) == true
</pre>
@param childId child identifier
@return new key with child identifier |
public Archetype flatten(@Nullable Archetype flatParent, Archetype differential) {
checkArgument(flatParent == null || !flatParent.isIsDifferential(), "flatParent: Flat parent must be a flat archetype or null");
checkArgument(differential.isIsDifferential(), "differential: Can only flatten a differential archetype");
Archetype result = createFlatArchetypeClone(differential);
if (differential.getParentArchetypeId() != null) {
if (flatParent == null || !flatParent.getArchetypeId().getValue().startsWith(differential.getParentArchetypeId().getValue())) {
throw new AdlFlattenerException(String.format("Wrong or missing parent archetype: expected %s, got %s",
differential.getParentArchetypeId().getValue(),
flatParent != null ? flatParent.getArchetypeId().getValue() : null));
}
merger.merge(flatParent, result);
}
return result;
} | Flattens a specialized source archetype
@param flatParent Parent archetype. Must already be flattened. Can be null if differentialArchetype is not specialized
@param differential Differential (source) archetype
@return Specialized archetype in flattened form |
public static String stringFor(int n)
{
switch (n)
{
case CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM: return "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM";
case CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM: return "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM";
case CUDNN_CONVOLUTION_FWD_ALGO_GEMM: return "CUDNN_CONVOLUTION_FWD_ALGO_GEMM";
case CUDNN_CONVOLUTION_FWD_ALGO_DIRECT: return "CUDNN_CONVOLUTION_FWD_ALGO_DIRECT";
case CUDNN_CONVOLUTION_FWD_ALGO_FFT: return "CUDNN_CONVOLUTION_FWD_ALGO_FFT";
case CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING: return "CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING";
case CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD: return "CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD";
case CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED: return "CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED";
case CUDNN_CONVOLUTION_FWD_ALGO_COUNT: return "CUDNN_CONVOLUTION_FWD_ALGO_COUNT";
}
return "INVALID cudnnConvolutionFwdAlgo: "+n;
} | Returns a string representation of the given constant
@return A string representation of the given constant |
@Override
public String requestJob(String CorpNum, QueryType queryType, String SDate,
String EDate) throws PopbillException {
return requestJob(CorpNum, queryType, SDate, EDate, null);
} | /*
(non-Javadoc)
@see com.popbill.api.HTCashbillService#requestJob(java.lang.String, com.popbill.api.hometaxcashbill.QueryType, java.lang.String, java.lang.String) |
public String requestJob(String CorpNum, QueryType queryType, String SDate, String EDate, String UserID) throws PopbillException {
if (SDate == null || SDate.isEmpty())
throw new PopbillException(-99999999, "μμμΌμκ° μ
λ ₯λμ§ μμμ΅λλ€.");
if (EDate == null || EDate.isEmpty())
throw new PopbillException(-99999999, "μ’
λ£μΌμκ° μ
λ ₯λμ§ μμμ΅λλ€.");
JobIDResponse response = httppost("/HomeTax/Cashbill/" + queryType.name()
+"?SDate=" + SDate +"&EDate=" + EDate ,CorpNum, null, UserID, JobIDResponse.class);
return response.jobID;
} | /*
(non-Javadoc)
@see com.popbill.api.HTCashbillService#requestJob(java.lang.String, com.popbill.api.hometaxcashbill.QueryType, java.lang.String, java.lang.String, java.lang.String) |
@Override
public HTCashbillJobState getJobState(String CorpNum, String JobID)
throws PopbillException {
return getJobState(CorpNum, JobID, null);
} | /*
(non-Javadoc)
@see com.popbill.api.HTCashbillService#getJobState(java.lang.String, java.lang.String) |
Subsets and Splits