_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q8900
Transloadit.getTemplate
train
public Response getTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.get("/templates/" + id)); }
java
{ "resource": "" }
q8901
Transloadit.updateTemplate
train
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)); }
java
{ "resource": "" }
q8902
Transloadit.deleteTemplate
train
public Response deleteTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.delete("/templates/" + id, new HashMap<String, Object>())); }
java
{ "resource": "" }
q8903
Transloadit.listTemplates
train
public ListResponse listTemplates(Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new ListResponse(request.get("/templates", options)); }
java
{ "resource": "" }
q8904
Transloadit.getBill
train
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))); }
java
{ "resource": "" }
q8905
TypeConverter.convert
train
@SuppressWarnings("unchecked") public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException { return convert(fromValue, toType, (String) null); }
java
{ "resource": "" }
q8906
JWTAuth.verifyToken
train
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); } }
java
{ "resource": "" }
q8907
RankedServices.bind
train
public void bind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service); updateSortedServices(); } }
java
{ "resource": "" }
q8908
RankedServices.unbind
train
public void unbind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props)); updateSortedServices(); } }
java
{ "resource": "" }
q8909
RankedServices.updateSortedServices
train
private void updateSortedServices() { List<T> copiedList = new ArrayList<T>(serviceMap.values()); sortedServices = Collections.unmodifiableList(copiedList); if (changeListener != null) { changeListener.changed(); } }
java
{ "resource": "" }
q8910
JacksonParser.json
train
public static <T> JacksonParser<T> json(Class<T> contentType) { return new JacksonParser<>(null, contentType); }
java
{ "resource": "" }
q8911
Steps.addStep
train
public void addStep(String name, String robot, Map<String, Object> options) { all.put(name, new Step(name, robot, options)); }
java
{ "resource": "" }
q8912
AbstractFeatureAttrProcessor.determineFeatureState
train
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; } }
java
{ "resource": "" }
q8913
ClasspathConfigurationProvider.init
train
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); } }
java
{ "resource": "" }
q8914
Assembly.addFile
train
public void addFile(File file) { String name = "file"; files.put(normalizeDuplicateName(name), file); }
java
{ "resource": "" }
q8915
Assembly.addFile
train
public void addFile(InputStream inputStream) { String name = "file"; fileStreams.put(normalizeDuplicateName(name), inputStream); }
java
{ "resource": "" }
q8916
Assembly.removeFile
train
public void removeFile(String name) { if(files.containsKey(name)) { files.remove(name); } if(fileStreams.containsKey(name)) { fileStreams.remove(name); } }
java
{ "resource": "" }
q8917
Assembly.save
train
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)); } }
java
{ "resource": "" }
q8918
Assembly.processTusFiles
train
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); } }
java
{ "resource": "" }
q8919
AdlUtils.makeClone
train
@SuppressWarnings("unchecked") public static <T extends Serializable> T makeClone(T from) { return (T) SerializationUtils.clone(from); }
java
{ "resource": "" }
q8920
JCudnn.checkResult
train
private static int checkResult(int result) { if (exceptionsEnabled && result != cudnnStatus.CUDNN_STATUS_SUCCESS) { throw new CudaException(cudnnStatus.stringFor(result)); } return result; }
java
{ "resource": "" }
q8921
JCudnn.cudnnSetTensor4dDescriptorEx
train
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)); }
java
{ "resource": "" }
q8922
JCudnn.cudnnOpTensor
train
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)); }
java
{ "resource": "" }
q8923
JCudnn.cudnnGetReductionIndicesSize
train
public static int cudnnGetReductionIndicesSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
java
{ "resource": "" }
q8924
JCudnn.cudnnGetReductionWorkspaceSize
train
public static int cudnnGetReductionWorkspaceSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, reduceTensorDesc, aDesc, cDesc, sizeInBytes)); }
java
{ "resource": "" }
q8925
JCudnn.cudnnReduceTensor
train
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)); }
java
{ "resource": "" }
q8926
JCudnn.cudnnGetConvolutionNdDescriptor
train
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)); }
java
{ "resource": "" }
q8927
JCudnn.cudnnConvolutionForward
train
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)); }
java
{ "resource": "" }
q8928
JCudnn.cudnnConvolutionBackwardBias
train
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)); }
java
{ "resource": "" }
q8929
JCudnn.cudnnSoftmaxForward
train
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)); }
java
{ "resource": "" }
q8930
JCudnn.cudnnSoftmaxBackward
train
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)); }
java
{ "resource": "" }
q8931
JCudnn.cudnnPoolingForward
train
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)); }
java
{ "resource": "" }
q8932
JCudnn.cudnnPoolingBackward
train
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)); }
java
{ "resource": "" }
q8933
JCudnn.cudnnGetActivationDescriptor
train
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)); }
java
{ "resource": "" }
q8934
JCudnn.cudnnActivationForward
train
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)); }
java
{ "resource": "" }
q8935
JCudnn.cudnnActivationBackward
train
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)); }
java
{ "resource": "" }
q8936
JCudnn.cudnnLRNCrossChannelForward
train
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)); }
java
{ "resource": "" }
q8937
JCudnn.cudnnLRNCrossChannelBackward
train
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)); }
java
{ "resource": "" }
q8938
JCudnn.cudnnBatchNormalizationBackward
train
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)); }
java
{ "resource": "" }
q8939
JCudnn.cudnnRestoreDropoutDescriptor
train
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)); }
java
{ "resource": "" }
q8940
JCudnn.cudnnCreatePersistentRNNPlan
train
public static int cudnnCreatePersistentRNNPlan( cudnnRNNDescriptor rnnDesc, int minibatch, int dataType, cudnnPersistentRNNPlan plan) { return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan)); }
java
{ "resource": "" }
q8941
JCudnn.cudnnGetRNNWorkspaceSize
train
public static int cudnnGetRNNWorkspaceSize( cudnnHandle handle, cudnnRNNDescriptor rnnDesc, int seqLength, cudnnTensorDescriptor[] xDesc, long[] sizeInBytes) { return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes)); }
java
{ "resource": "" }
q8942
JCudnn.cudnnCTCLoss
train
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)); }
java
{ "resource": "" }
q8943
JCudnn.cudnnGetCTCLossWorkspaceSize
train
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)); }
java
{ "resource": "" }
q8944
JCudnn.cudnnGetRNNDataDescriptor
train
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)); }
java
{ "resource": "" }
q8945
ResourceValues.ofNullable
train
public static <T> OptionalValue<T> ofNullable(T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value); }
java
{ "resource": "" }
q8946
ResourceValues.ofNullable
train
public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value); }
java
{ "resource": "" }
q8947
DaemonStarter.stopService
train
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(); } }
java
{ "resource": "" }
q8948
DaemonStarter.handleSignals
train
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"); } } }
java
{ "resource": "" }
q8949
DaemonStarter.abortSystem
train
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); }
java
{ "resource": "" }
q8950
MongoDBInit.initDatabase
train
@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); } }
java
{ "resource": "" }
q8951
ResourceResolutionContext.with
train
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; }
java
{ "resource": "" }
q8952
ResourceResolutionContext.context
train
public static ResourceResolutionContext context(ResourceResolutionComponent[] components, Map<String, Object> messageParams) { return new ResourceResolutionContext(components, messageParams); }
java
{ "resource": "" }
q8953
PackageBasedActionConfigBuilder.setFileProtocols
train
@Inject("struts.json.action.fileProtocols") public void setFileProtocols(String fileProtocols) { if (StringUtils.isNotBlank(fileProtocols)) { this.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols); } }
java
{ "resource": "" }
q8954
PackageBasedActionConfigBuilder.cannotInstantiate
train
protected boolean cannotInstantiate(Class<?> actionClass) { return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum() || (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass(); }
java
{ "resource": "" }
q8955
PackageBasedActionConfigBuilder.checkExcludePackages
train
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; }
java
{ "resource": "" }
q8956
PackageBasedActionConfigBuilder.checkActionPackages
train
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; }
java
{ "resource": "" }
q8957
PackageBasedActionConfigBuilder.checkPackageLocators
train
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; }
java
{ "resource": "" }
q8958
RmPath.parseSegments
train
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; }
java
{ "resource": "" }
q8959
Request.get
train
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); } }
java
{ "resource": "" }
q8960
Request.delete
train
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); } }
java
{ "resource": "" }
q8961
Request.getFullUrl
train
private String getFullUrl(String url) { return url.startsWith("https://") || url.startsWith("http://") ? url : transloadit.getHostUrl() + url; }
java
{ "resource": "" }
q8962
Request.toPayload
train
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; }
java
{ "resource": "" }
q8963
Request.jsonifyData
train
private String jsonifyData(Map<String, ? extends Object> data) { JSONObject jsonData = new JSONObject(data); return jsonData.toString(); }
java
{ "resource": "" }
q8964
RequestParam.convertISO88591toUTF8
train
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; } }
java
{ "resource": "" }
q8965
JsonActionInvocation.getResult
train
@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; }
java
{ "resource": "" }
q8966
JsonActionInvocation.executeResult
train
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); } }
java
{ "resource": "" }
q8967
ServerJSONWebSocketAdapter.convert
train
protected <C> C convert(Object object, Class<C> targetClass) { return this.mapper.convertValue(object, targetClass); }
java
{ "resource": "" }
q8968
ServerJSONWebSocketAdapter.sendObjectToSocket
train
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); } }
java
{ "resource": "" }
q8969
IosApplicationBundle.deviceTypes
train
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; }
java
{ "resource": "" }
q8970
JaxRsAnnotationScanner.hasAnnotation
train
public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) { return !searchForAnnotation(method, annotation).isEmpty(); }
java
{ "resource": "" }
q8971
JaxRsAnnotationScanner.searchForAnnotation
train
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()); }
java
{ "resource": "" }
q8972
OptionsBuilder.addStep
train
public void addStep(String name, String robot, Map<String, Object> options){ steps.addStep(name, robot, options); }
java
{ "resource": "" }
q8973
ArchetypeMerger.merge
train
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()); } }
java
{ "resource": "" }
q8974
ChangelogUtil.addTTLIndex
train
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)); }
java
{ "resource": "" }
q8975
ChangelogUtil.addIndex
train
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)); }
java
{ "resource": "" }
q8976
ArchetypeValidator.checkRmModelConformance
train
void checkRmModelConformance() { final AmVisitor<AmObject, AmConstraintContext> visitor = AmVisitors.preorder(new ConformanceVisitor()); ArchetypeWalker.walkConstraints(visitor, archetype, new AmConstraintContext()); }
java
{ "resource": "" }
q8977
ResourceKey.key
train
public static ResourceKey key(Enum<?> value) { return new ResourceKey(value.getClass().getName(), value.name()); }
java
{ "resource": "" }
q8978
ResourceKey.key
train
public static ResourceKey key(Class<?> clazz, String id) { return new ResourceKey(clazz.getName(), id); }
java
{ "resource": "" }
q8979
ResourceKey.key
train
public static ResourceKey key(Class<?> clazz, Enum<?> value) { return new ResourceKey(clazz.getName(), value.name()); }
java
{ "resource": "" }
q8980
ResourceKey.key
train
public static ResourceKey key(Enum<?> enumValue, String key) { return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key); }
java
{ "resource": "" }
q8981
Vector3d.set
train
public void set(int i, double value) { switch (i) { case 0: { x = value; break; } case 1: { y = value; break; } case 2: { z = value; break; } default: { throw new ArrayIndexOutOfBoundsException(i); } } }
java
{ "resource": "" }
q8982
Vector3d.set
train
public void set(Vector3d v1) { x = v1.x; y = v1.y; z = v1.z; }
java
{ "resource": "" }
q8983
Vector3d.add
train
public void add(Vector3d v1, Vector3d v2) { x = v1.x + v2.x; y = v1.y + v2.y; z = v1.z + v2.z; }
java
{ "resource": "" }
q8984
Vector3d.add
train
public void add(Vector3d v1) { x += v1.x; y += v1.y; z += v1.z; }
java
{ "resource": "" }
q8985
Vector3d.sub
train
public void sub(Vector3d v1, Vector3d v2) { x = v1.x - v2.x; y = v1.y - v2.y; z = v1.z - v2.z; }
java
{ "resource": "" }
q8986
Vector3d.sub
train
public void sub(Vector3d v1) { x -= v1.x; y -= v1.y; z -= v1.z; }
java
{ "resource": "" }
q8987
Vector3d.distance
train
public double distance(Vector3d v) { double dx = x - v.x; double dy = y - v.y; double dz = z - v.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); }
java
{ "resource": "" }
q8988
Vector3d.distanceSquared
train
public double distanceSquared(Vector3d v) { double dx = x - v.x; double dy = y - v.y; double dz = z - v.z; return dx * dx + dy * dy + dz * dz; }
java
{ "resource": "" }
q8989
Vector3d.dot
train
public double dot(Vector3d v1) { return x * v1.x + y * v1.y + z * v1.z; }
java
{ "resource": "" }
q8990
Vector3d.normalize
train
public void normalize() { double lenSqr = x * x + y * y + z * z; double err = lenSqr - 1; if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) { double len = Math.sqrt(lenSqr); x /= len; y /= len; z /= len; } }
java
{ "resource": "" }
q8991
Vector3d.cross
train
public void cross(Vector3d v1, Vector3d v2) { double tmpx = v1.y * v2.z - v1.z * v2.y; double tmpy = v1.z * v2.x - v1.x * v2.z; double tmpz = v1.x * v2.y - v1.y * v2.x; x = tmpx; y = tmpy; z = tmpz; }
java
{ "resource": "" }
q8992
Vector3d.setRandom
train
protected void setRandom(double lower, double upper, Random generator) { double range = upper - lower; x = generator.nextDouble() * range + lower; y = generator.nextDouble() * range + lower; z = generator.nextDouble() * range + lower; }
java
{ "resource": "" }
q8993
LuaScriptBlockBuilder.endBlockReturn
train
public LuaScriptBlock endBlockReturn(LuaValue value) { add(new LuaAstReturnStatement(argument(value))); return new LuaScriptBlock(script); }
java
{ "resource": "" }
q8994
LuaConditions.isNull
train
public static LuaCondition isNull(LuaValue value) { LuaAstExpression expression; if (value instanceof LuaLocal) { expression = new LuaAstLocal(((LuaLocal) value).getName()); } else { throw new IllegalArgumentException("Unexpected value type: " + value.getClass().getName()); } return new LuaCondition(new LuaAstNot(expression)); }
java
{ "resource": "" }
q8995
HalfEdge.getVertexString
train
public String getVertexString() { if (tail() != null) { return "" + tail().index + "-" + head().index; } else { return "?-" + head().index; } }
java
{ "resource": "" }
q8996
Face.createTriangle
train
public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) { Face face = new Face(); HalfEdge he0 = new HalfEdge(v0, face); HalfEdge he1 = new HalfEdge(v1, face); HalfEdge he2 = new HalfEdge(v2, face); he0.prev = he2; he0.next = he1; he1.prev = he0; he1.next = he2; he2.prev = he1; he2.next = he0; face.he0 = he0; // compute the normal and offset face.computeNormalAndCentroid(minArea); return face; }
java
{ "resource": "" }
q8997
Face.distanceToPlane
train
public double distanceToPlane(Point3d p) { return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset; }
java
{ "resource": "" }
q8998
Face.getEdge
train
public HalfEdge getEdge(int i) { HalfEdge he = he0; while (i > 0) { he = he.next; i--; } while (i < 0) { he = he.prev; i++; } return he; }
java
{ "resource": "" }
q8999
Face.areaSquared
train
public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) { Point3d p0 = hedge0.tail().pnt; Point3d p1 = hedge0.head().pnt; Point3d p2 = hedge1.head().pnt; double dx1 = p1.x - p0.x; double dy1 = p1.y - p0.y; double dz1 = p1.z - p0.z; double dx2 = p2.x - p0.x; double dy2 = p2.y - p0.y; double dz2 = p2.z - p0.z; double x = dy1 * dz2 - dz1 * dy2; double y = dz1 * dx2 - dx1 * dz2; double z = dx1 * dy2 - dy1 * dx2; return x * x + y * y + z * z; }
java
{ "resource": "" }