code
stringlengths
73
34.1k
func_name
stringlengths
1
122
private int[] convertBatch(int[] batch) { int[] conv = new int[batch.length]; for (int i=0; i<batch.length; i++) { conv[i] = sample[batch[i]]; } return conv; }
convertBatch
public static boolean containsAtLeastOneNonBlank(List<String> list){ for(String str : list){ if(StringUtils.isNotBlank(str)){ return true; } } return false; }
containsAtLeastOneNonBlank
public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){ List<Integer> intList = new ArrayList<Integer>(); for(String str : strList){ try{ intList.add(Integer.parseInt(str)); } catch(NumberFormatException nfe){ if(failOnException){ return null; } else{ intList.add(null); } } } return intList; }
toIntegerList
public static void add(double[] array1, double[] array2) { assert (array1.length == array2.length); for (int i=0; i<array1.length; i++) { array1[i] += array2[i]; } }
add
public static boolean containsOnlyNull(Object... values){ for(Object o : values){ if(o!= null){ return false; } } return true; }
containsOnlyNull
public static boolean containsOnlyNotNull(Object... values){ for(Object o : values){ if(o== null){ return false; } } return true; }
containsOnlyNotNull
@RequestMapping(value="/soy/compileJs", method=GET) public ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash, @RequestParam(required = true, value = "file") final String[] templateFileNames, @RequestParam(required = false, value = "locale") String locale, @RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors, final HttpServletRequest request) throws IOException { return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale); }
compile
public int[] sampleBatchWithReplacement() { // Sample the indices with replacement. int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { batch[i] = Prng.nextInt(numExamples); } return batch; }
sampleBatchWithReplacement
public int[] sampleBatchWithoutReplacement() { int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { if (cur == indices.length) { cur = 0; } if (cur == 0) { IntArrays.shuffle(indices); } batch[i] = indices[cur++]; } return batch; }
sampleBatchWithoutReplacement
public void adjustGlassSize() { if (isGlassEnabled()) { ResizeHandler handler = getGlassResizer(); if (handler != null) handler.onResize(null); } }
adjustGlassSize
public static Bounds getSymmetricBounds(int dim, double l, double u) { double [] L = new double[dim]; double [] U = new double[dim]; for(int i=0; i<dim; i++) { L[i] = l; U[i] = u; } return new Bounds(L, U); }
getSymmetricBounds
public static Optional<Tag> parse(final String httpTag) { Tag result = null; boolean weak = false; String internal = httpTag; if (internal.startsWith("W/")) { weak = true; internal = internal.substring(2); } if (internal.startsWith("\"") && internal.endsWith("\"")) { result = new Tag( internal.substring(1, internal.length() - 1), weak); } else if (internal.equals("*")) { result = new Tag("*", weak); } return Optional.ofNullable(result); }
parse
public String format() { if (getName().equals("*")) { return "*"; } else { StringBuilder sb = new StringBuilder(); if (isWeak()) { sb.append("W/"); } return sb.append('"').append(getName()).append('"').toString(); } }
format
public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{ InputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream("/"+baseName + "_"+locale.toString()+PROPERTIES_EXT); if(is != null){ return new PropertyResourceBundle(new InputStreamReader(is, "UTF-8")); } return null; }
getBundle
@Override public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) { return minimize(function, point, null); }
minimize
@SuppressWarnings("unchecked") public <T> T convertElement(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { return (T) elementConverter.convert(context, source, destinationType); }
convertElement
public Conditionals addIfMatch(Tag tag) { Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE)); Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH)); List<Tag> match = new ArrayList<>(this.match); if (tag == null) { tag = Tag.ALL; } if (Tag.ALL.equals(tag)) { match.clear(); } if (!match.contains(Tag.ALL)) { if (!match.contains(tag)) { match.add(tag); } } else { throw new IllegalArgumentException("Tag ALL already in the list"); } return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince); }
addIfMatch
public Conditionals ifModifiedSince(LocalDateTime time) { Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH)); Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE)); time = time.withNano(0); return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty()); }
ifModifiedSince
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get())); } if (unModifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get())); } return headers; }
toHeaders
public Collection<QName> getPortComponentQNames() { //TODO:Check if there is just one QName that drives all portcomponents //or each port component can have a distinct QName (namespace/prefix) //Maintain uniqueness of the QName Map<String, QName> map = new HashMap<String, QName>(); for (PortComponentMetaData pcm : portComponents) { QName qname = pcm.getWsdlPort(); map.put(qname.getPrefix(), qname); } return map.values(); }
getPortComponentQNames
public PortComponentMetaData getPortComponentByWsdlPort(String name) { ArrayList<String> pcNames = new ArrayList<String>(); for (PortComponentMetaData pc : portComponents) { String wsdlPortName = pc.getWsdlPort().getLocalPart(); if (wsdlPortName.equals(name)) return pc; pcNames.add(wsdlPortName); } Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames); return null; }
getPortComponentByWsdlPort
public static final void setBounds(UIObject o, Rect bounds) { setPosition(o, bounds); setSize(o, bounds); }
setBounds
public static final void setPosition(UIObject o, Rect pos) { Style style = o.getElement().getStyle(); style.setPropertyPx("left", pos.x); style.setPropertyPx("top", pos.y); }
setPosition
public static final void setSize(UIObject o, Rect size) { o.setPixelSize(size.w, size.h); }
setSize
public static final boolean isInside(int x, int y, Rect box) { return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h); }
isInside
public static final boolean isMouseInside(NativeEvent event, Element element) { return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element)); }
isMouseInside
public static final Rect getViewportBounds() { return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight()); }
getViewportBounds
public static final Date utc2date(Long time) { // don't accept negative values if (time == null || time < 0) return null; // add the timezone offset time += timezoneOffsetMillis(new Date(time)); return new Date(time); }
utc2date
public static final Long date2utc(Date date) { // use null for a null date if (date == null) return null; long time = date.getTime(); // remove the timezone offset time -= timezoneOffsetMillis(date); return time; }
date2utc
public static FullTypeSignature getTypeSignature(String typeSignatureString, boolean useInternalFormFullyQualifiedName) { String key; if (!useInternalFormFullyQualifiedName) { key = typeSignatureString.replace('.', '/') .replace('$', '.'); } else { key = typeSignatureString; } // we always use the internal form as a key for cache FullTypeSignature typeSignature = typeSignatureCache .get(key); if (typeSignature == null) { ClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser( typeSignatureString); typeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName); typeSignature = typeSignatureParser.parseTypeSignature(); typeSignatureCache.put(typeSignatureString, typeSignature); } return typeSignature; }
getTypeSignature
public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) { ClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature .getTypeSignature(clazz); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length]; for (int i = 0; i < typeArgs.length; i++) { typeArgSignatures[i] = new TypeArgSignature( TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) javaTypeToTypeSignature .getTypeSignature(typeArgs[i])); } ClassTypeSignature classTypeSignature = new ClassTypeSignature( rawClassTypeSignature.getBinaryName(), typeArgSignatures, rawClassTypeSignature.getOwnerTypeSignature()); return classTypeSignature; }
getTypeSignature
public static OptionalString ofNullable(ResourceKey key, String value) { return new GenericOptionalString(RUNTIME_SOURCE, key, value); }
ofNullable
public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } }
parse
@SuppressWarnings({"unchecked", "unused"}) public static <T> T[] object2Array(final Class<T> clazz, final Object obj) { return (T[]) obj; }
object2Array
public void pauseUpload() throws LocalOperationException { if (state == State.UPLOADING) { setState(State.PAUSED); executor.hardStop(); } else { throw new LocalOperationException("Attempt to pause upload while assembly is not uploading"); } }
pauseUpload
protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException { AssemblyResponse response; do { response = getClient().getAssemblyByUrl(url); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new LocalOperationException(e); } } while (!response.isFinished()); setState(State.FINISHED); return response; }
watchStatus
private long getTotalUploadSize() throws IOException { long size = 0; for (Map.Entry<String, File> entry : files.entrySet()) { size += entry.getValue().length(); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { size += entry.getValue().available(); } return size; }
getTotalUploadSize
public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException { return InterconnectMapper.mapper.readValue(data, clazz); }
fromJson
public Response save() throws RequestException, LocalOperationException { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("name", name); options.put("steps", steps.toMap()); templateData.put("template", options); Request request = new Request(transloadit); return new Response(request.post("/templates", templateData)); }
save
public boolean matches(String resourcePath) { if (!valid) { return false; } if (resourcePath == null) { return acceptsContextPathEmpty; } if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) { return false; } if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) { return false; } return true; }
matches
private ClassLoaderInterface getClassLoader() { Map<String, Object> application = ActionContext.getContext().getApplication(); if (application != null) { return (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE); } return null; }
getClassLoader
public @Nullable String build() { StringBuilder queryString = new StringBuilder(); for (NameValuePair param : params) { if (queryString.length() > 0) { queryString.append(PARAM_SEPARATOR); } queryString.append(Escape.urlEncode(param.getName())); queryString.append(VALUE_SEPARATOR); queryString.append(Escape.urlEncode(param.getValue())); } if (queryString.length() > 0) { return queryString.toString(); } else { return null; } }
build
public AssemblyResponse cancelAssembly(String url) throws RequestException, LocalOperationException { Request request = new Request(this); return new AssemblyResponse(request.delete(url, new HashMap<String, Object>())); }
cancelAssembly
public Response getTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.get("/templates/" + id)); }
getTemplate
public Response updateTemplate(String id, Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.put("/templates/" + id, options)); }
updateTemplate
public Response deleteTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.delete("/templates/" + id, new HashMap<String, Object>())); }
deleteTemplate
public ListResponse listTemplates(Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new ListResponse(request.get("/templates", options)); }
listTemplates
public Response getBill(int month, int year) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.get("/bill/" + year + String.format("-%02d", month))); }
getBill
@SuppressWarnings("unchecked") public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException { return convert(fromValue, toType, (String) null); }
convert
public SignedJWT verifyToken(String jwtString) throws ParseException { try { SignedJWT jwt = SignedJWT.parse(jwtString); if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) { return jwt; } return null; } catch (JOSEException e) { throw new RuntimeException("Error verifying JSON Web Token", e); } }
verifyToken
public void bind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service); updateSortedServices(); } }
bind
public void unbind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props)); updateSortedServices(); } }
unbind
private void updateSortedServices() { List<T> copiedList = new ArrayList<T>(serviceMap.values()); sortedServices = Collections.unmodifiableList(copiedList); if (changeListener != null) { changeListener.changed(); } }
updateSortedServices
public static <T> JacksonParser<T> json(Class<T> contentType) { return new JacksonParser<>(null, contentType); }
json
public void addStep(String name, String robot, Map<String, Object> options) { all.put(name, new Step(name, robot, options)); }
addStep
protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) { final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue); final Object value = expression.execute(context); if (value != null) { return isFeatureActive(value.toString()); } else { return defaultState; } }
determineFeatureState
public void init(Configuration configuration) { if (devMode && reload && !listeningToDispatcher) { // this is the only way I found to be able to get added to to // ConfigurationProvider list // listening to events in Dispatcher listeningToDispatcher = true; Dispatcher.addDispatcherListener(this); } }
init
public void addFile(File file) { String name = "file"; files.put(normalizeDuplicateName(name), file); }
addFile
public void addFile(InputStream inputStream) { String name = "file"; fileStreams.put(normalizeDuplicateName(name), inputStream); }
addFile
public void removeFile(String name) { if(files.containsKey(name)) { files.remove(name); } if(fileStreams.containsKey(name)) { fileStreams.remove(name); } }
removeFile
public AssemblyResponse save(boolean isResumable) throws RequestException, LocalOperationException { Request request = new Request(getClient()); options.put("steps", steps.toMap()); // only do tus uploads if files will be uploaded if (isResumable && getFilesCount() > 0) { Map<String, String> tusOptions = new HashMap<String, String>(); tusOptions.put("tus_num_expected_upload_files", Integer.toString(getFilesCount())); AssemblyResponse response = new AssemblyResponse( request.post("/assemblies", options, tusOptions, null, null), true); // check if the assembly returned an error if (response.hasError()) { throw new RequestException("Request to Assembly failed: " + response.json().getString("error")); } try { handleTusUpload(response); } catch (IOException e) { throw new LocalOperationException(e); } catch (ProtocolException e) { throw new RequestException(e); } return response; } else { return new AssemblyResponse(request.post("/assemblies", options, null, files, fileStreams)); } }
save
protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException { tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + "/resumable/files/")); tusClient.enableResuming(tusURLStore); for (Map.Entry<String, File> entry : files.entrySet()) { processTusFile(entry.getValue(), entry.getKey(), assemblyUrl); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { processTusFile(entry.getValue(), entry.getKey(), assemblyUrl); } }
processTusFiles
@SuppressWarnings("unchecked") public static <T extends Serializable> T makeClone(T from) { return (T) SerializationUtils.clone(from); }
makeClone
private static int checkResult(int result) { if (exceptionsEnabled && result != cudnnStatus.CUDNN_STATUS_SUCCESS) { throw new CudaException(cudnnStatus.stringFor(result)); } return result; }
checkResult
public static int cudnnSetTensor4dDescriptorEx( cudnnTensorDescriptor tensorDesc, int dataType, /** image data type */ int n, /** number of inputs (batch size) */ int c, /** number of input feature maps */ int h, /** height of input section */ int w, /** width of input section */ int nStride, int cStride, int hStride, int wStride) { return checkResult(cudnnSetTensor4dDescriptorExNative(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride)); }
cudnnSetTensor4dDescriptorEx
public static int cudnnOpTensor( cudnnHandle handle, cudnnOpTensorDescriptor opTensorDesc, Pointer alpha1, cudnnTensorDescriptor aDesc, Pointer A, Pointer alpha2, cudnnTensorDescriptor bDesc, Pointer B, Pointer beta, cudnnTensorDescriptor cDesc, Pointer C) { return checkResult(cudnnOpTensorNative(handle, opTensorDesc, alpha1, aDesc, A, alpha2, bDesc, B, beta, cDesc, C)); }
cudnnOpTensor
public static int cudnnGetReductionIndicesSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
cudnnGetReductionIndicesSize
public static int cudnnGetReductionWorkspaceSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
cudnnGetReductionWorkspaceSize
public static int cudnnReduceTensor( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, Pointer indices, long indicesSizeInBytes, Pointer workspace, long workspaceSizeInBytes, Pointer alpha, cudnnTensorDescriptor aDesc, Pointer A, Pointer beta, cudnnTensorDescriptor cDesc, Pointer C) { return checkResult(cudnnReduceTensorNative(handle, reduceTensorDesc, indices, indicesSizeInBytes, workspace, workspaceSizeInBytes, alpha, aDesc, A, beta, cDesc, C)); }
cudnnReduceTensor
public static int cudnnGetConvolutionNdDescriptor( cudnnConvolutionDescriptor convDesc, int arrayLengthRequested, int[] arrayLength, int[] padA, int[] strideA, int[] dilationA, int[] mode, int[] computeType)/** convolution data type */ { return checkResult(cudnnGetConvolutionNdDescriptorNative(convDesc, arrayLengthRequested, arrayLength, padA, strideA, dilationA, mode, computeType)); }
cudnnGetConvolutionNdDescriptor
public static int cudnnConvolutionForward( cudnnHandle handle, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, cudnnFilterDescriptor wDesc, Pointer w, cudnnConvolutionDescriptor convDesc, int algo, Pointer workSpace, long workSpaceSizeInBytes, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnConvolutionForwardNative(handle, alpha, xDesc, x, wDesc, w, convDesc, algo, workSpace, workSpaceSizeInBytes, beta, yDesc, y)); }
cudnnConvolutionForward
public static int cudnnConvolutionBackwardBias( cudnnHandle handle, Pointer alpha, cudnnTensorDescriptor dyDesc, Pointer dy, Pointer beta, cudnnTensorDescriptor dbDesc, Pointer db) { return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db)); }
cudnnConvolutionBackwardBias
public static int cudnnSoftmaxForward( cudnnHandle handle, int algo, int mode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnSoftmaxForwardNative(handle, algo, mode, alpha, xDesc, x, beta, yDesc, y)); }
cudnnSoftmaxForward
public static int cudnnSoftmaxBackward( cudnnHandle handle, int algo, int mode, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, Pointer beta, cudnnTensorDescriptor dxDesc, Pointer dx) { return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx)); }
cudnnSoftmaxBackward
public static int cudnnPoolingForward( cudnnHandle handle, cudnnPoolingDescriptor poolingDesc, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnPoolingForwardNative(handle, poolingDesc, alpha, xDesc, x, beta, yDesc, y)); }
cudnnPoolingForward
public static int cudnnPoolingBackward( cudnnHandle handle, cudnnPoolingDescriptor poolingDesc, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor dxDesc, Pointer dx) { return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx)); }
cudnnPoolingBackward
public static int cudnnGetActivationDescriptor( cudnnActivationDescriptor activationDesc, int[] mode, int[] reluNanOpt, double[] coef)/** ceiling for clipped RELU, alpha for ELU */ { return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, coef)); }
cudnnGetActivationDescriptor
public static int cudnnActivationForward( cudnnHandle handle, cudnnActivationDescriptor activationDesc, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y)); }
cudnnActivationForward
public static int cudnnActivationBackward( cudnnHandle handle, cudnnActivationDescriptor activationDesc, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor dxDesc, Pointer dx) { return checkResult(cudnnActivationBackwardNative(handle, activationDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx)); }
cudnnActivationBackward
public static int cudnnLRNCrossChannelForward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnLRNCrossChannelForwardNative(handle, normDesc, lrnMode, alpha, xDesc, x, beta, yDesc, y)); }
cudnnLRNCrossChannelForward
public static int cudnnLRNCrossChannelBackward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor dxDesc, Pointer dx) { return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx)); }
cudnnLRNCrossChannelBackward
public static int cudnnBatchNormalizationBackward( cudnnHandle handle, int mode, Pointer alphaDataDiff, Pointer betaDataDiff, Pointer alphaParamDiff, Pointer betaParamDiff, cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */ Pointer x, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor dxDesc, Pointer dx, /** Shared tensor desc for the 4 tensors below */ cudnnTensorDescriptor dBnScaleBiasDesc, Pointer bnScale, /** bnBias doesn't affect backpropagation */ /** scale and bias diff are not backpropagated below this layer */ Pointer dBnScaleResult, Pointer dBnBiasResult, /** Same epsilon as forward pass */ double epsilon, /** Optionally cached intermediate results from forward pass */ Pointer savedMean, Pointer savedInvVariance) { return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance)); }
cudnnBatchNormalizationBackward
public static int cudnnRestoreDropoutDescriptor( cudnnDropoutDescriptor dropoutDesc, cudnnHandle handle, float dropout, Pointer states, long stateSizeInBytes, long seed) { return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout, states, stateSizeInBytes, seed)); }
cudnnRestoreDropoutDescriptor
public static int cudnnCreatePersistentRNNPlan( cudnnRNNDescriptor rnnDesc, int minibatch, int dataType, cudnnPersistentRNNPlan plan) { return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan)); }
cudnnCreatePersistentRNNPlan
public static int cudnnGetRNNWorkspaceSize( cudnnHandle handle, cudnnRNNDescriptor rnnDesc, int seqLength, cudnnTensorDescriptor[] xDesc, long[] sizeInBytes) { return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes)); }
cudnnGetRNNWorkspaceSize
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)); }
cudnnCTCLoss
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)); }
cudnnGetCTCLossWorkspaceSize
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)); }
cudnnGetRNNDataDescriptor
public static <T> OptionalValue<T> ofNullable(T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value); }
ofNullable
public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value); }
ofNullable
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(); } }
stopService
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"); } } }
handleSignals
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); }
abortSystem
@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); } }
initDatabase
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; }
with
public static ResourceResolutionContext context(ResourceResolutionComponent[] components, Map<String, Object> messageParams) { return new ResourceResolutionContext(components, messageParams); }
context
@Inject("struts.json.action.fileProtocols") public void setFileProtocols(String fileProtocols) { if (StringUtils.isNotBlank(fileProtocols)) { this.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols); } }
setFileProtocols
protected boolean cannotInstantiate(Class<?> actionClass) { return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum() || (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass(); }
cannotInstantiate
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; }
checkExcludePackages
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; }
checkActionPackages