auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void functionalFit(FitParams fitParams) throws Exception { try { ComputationGraph model = fitParams.getFunctionalModel(); DataSetIterator trainIterator; DataSetIterator testIterator; trainIterator = new HDF5MiniBatchDataSetIterator( fitParams.getTrainXPath(), fitParams.getTrainYPath() ); if(fitParams.isDoValidation()) { testIterator = new HDF5MiniBatchDataSetIterator( fitParams.getValidationXPath(), fitParams.getValidationYPath() ); } else { testIterator = null; } for (int i = 0; i < fitParams.getNbEpoch(); i++) { log.info("Fitting epoch: " + i); model.fit(trainIterator); double score = model.score(); log.info("Score is "+score); if(fitParams.isDoValidation()) { log.info("Evaluating epoch: " + i); model.evaluate(testIterator); <START> } <END> } log.info("model.fit() operation complete."); } catch (Throwable e) { log.error("Error while performing model.fit()", e); throw e; } }</code><technical_language>do results go</technical_language>

Target:
public void functionalFit(FitParams fitParams) throws Exception { try { ComputationGraph model = fitParams.getFunctionalModel(); DataSetIterator trainIterator; DataSetIterator testIterator; trainIterator = new HDF5MiniBatchDataSetIterator( fitParams.getTrainXPath(), fitParams.getTrainYPath() ); if(fitParams.isDoValidation()) { testIterator = new HDF5MiniBatchDataSetIterator( fitParams.getValidationXPath(), fitParams.getValidationYPath() ); } else { testIterator = null; } for (int i = 0; i < fitParams.getNbEpoch(); i++) { log.info("Fitting epoch: " + i); model.fit(trainIterator); double score = model.score(); log.info("Score is "+score); if(fitParams.isDoValidation()) { log.info("Evaluating epoch: " + i); Evaluation eval = model.evaluate(testIterator); log.info("Accuracy: "+eval.accuracy()); log.info("Precision: "+eval.precision()); } } log.info("model.fit() operation complete."); } catch (Throwable e) { log.error("Error while performing model.fit()", e); throw e; } }
Source:
<code>public void activate() { super.activate(); View view = getView(); if (view == null) { return; } <START> getDiagramEventBroker().addNotificationListener(view, this); <END> }</code><technical_language>subscribe()</technical_language>

Target:
public void activate() { super.activate(); View view = getView(); if (view == null) { return; } subscribe(view); }
Source:
<code>public void testApplication() throws IOException, Exception { try { cleanup(); createTopics(); Configuration conf = getConfig(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(new Application(), conf); ValidationToFile validationToFile = (ValidationToFile)lma.getDAG().getOperatorMeta("validationToFile").getOperator(); LocalMode.Controller lc = lma.getController(); lc.runAsync(); <START> while(!validationToFile.validationDone) <END> { System.out.println("Sleeping ...."); Thread.sleep(500); } lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }</code><technical_language>Infinite loop if validation fails</technical_language>

Target:
public void testApplication() throws IOException, Exception { try { createTopics(); Configuration conf = getConfig(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(new Application(), conf); ValidationToFile validationToFile = (ValidationToFile)lma.getDAG().getOperatorMeta("validationToFile").getOperator(); LocalMode.Controller lc = lma.getController(); lc.runAsync(); int count = 1; int maxSleepRounds = 300; while (!validationToFile.validationDone) { logger.info("Sleeping ...."); Thread.sleep(500); if(count > maxSleepRounds){ fail("validationDone flag did not get set to true in ValidationToFile operator"); } count++; } lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
<code>protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("RELAY,1#"); case Command.TYPE_ENGINE_RESUME: return encodeContent("RELAY,0#"); case Command.TYPE_REBOOT_DEVICE: return encodeContent("RESET#"); case Command.TYPE_GET_VERSION: return encodeContent("VERSION#"); case Command.TYPE_GET_DEVICE_STATUS: return encodeContent("STATUS#"); case Command.TYPE_SOS_NUMBER: String num = command.getString(Command.KEY_DATA); <START> if (!num.isEmpty()) { <END> return encodeContent("SOS,A," + num + "#"); } else { return encodeContent("SOS,D#"); } default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }</code><technical_language>I check for null well</technical_language>

Target:
protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("RELAY,1#"); case Command.TYPE_ENGINE_RESUME: return encodeContent("RELAY,0#"); case Command.TYPE_REBOOT_DEVICE: return encodeContent("RESET#"); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }
Source:
<code>private String computeSourceForEnumerator(IASTTranslationUnit ast, IEnumerator binding) throws CoreException { Long numValue = binding.getValue().numericalValue(); <START> if ( numValue != null) { <END> return String.valueOf(numValue); } else { IName[] defs = ast.getDefinitions(binding); for (IName def : defs) { String source= computeSourceForName(def, binding); if (source != null) { return source; } } } return null; }</code><technical_language>Extra space (</technical_language>

Target:
private String computeSourceForEnumerator(IASTTranslationUnit ast, IEnumerator binding) throws CoreException { Long numValue = binding.getValue().numericalValue(); if ( numValue != null) { return numValue.toString(); } else { IName[] defs = ast.getDefinitions(binding); for (IName def : defs) { String source= computeSourceForName(def, binding); if (source != null) { return source; } } } return null; }
Source:
<code><START> public <T> List<T> getBackendCollection(Class<T> clz, VdcQueryType query, VdcQueryParametersBase queryParams) { <END> try { VdcQueryReturnValue result = runQuery(query, queryParams); if (!result.getSucceeded()) { backendFailure(result.getExceptionString()); } List<T> results = asCollection(clz, result.getReturnValue()); if (results!=null && getMaxResults()!=NO_LIMIT && getMaxResults()<results.size()) { results = results.subList(0, getMaxResults()); } return results; } catch (Exception e) { return handleError(e, false); } }</code><technical_language>is this needed</technical_language>

Target:
protected <T> List<T> getBackendCollection(Class<T> clz, VdcQueryType query, VdcQueryParametersBase queryParams) { try { VdcQueryReturnValue result = runQuery(query, queryParams); if (!result.getSucceeded()) { backendFailure(result.getExceptionString()); } List<T> results = asCollection(clz, result.getReturnValue()); if (results!=null && getMaxResults()!=NO_LIMIT && getMaxResults()<results.size()) { results = results.subList(0, getMaxResults()); } return results; } catch (Exception e) { return handleError(e, false); } }
Source:
<code>protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, org.jboss.as.controller.AbstractWriteAttributeHandler.HandbackHolder<ModelNode> handbackHolder) throws OperationFailedException { if (!context.isBooting()) { MonitorService agent = getMonitorService(context); if (agent.isImmutable()) { throw new OperationFailedException("The agent is configured to be immutable - no changes are allowed"); } } ModelNode headers = operation.has(OPERATION_HEADERS) ? operation.get(OPERATION_HEADERS) : null; boolean restartAllowedOptionSet = (headers != null) && headers.hasDefined(ALLOW_RESOURCE_SERVICE_RESTART); boolean restartAllowed = !restartAllowedOptionSet || headers.get(ALLOW_RESOURCE_SERVICE_RESTART).asBoolean(); Object tempOwner = null; PathAddress address = null; if (!restartAllowed) { <START> address = getParentAddress(context.getCurrentAddress()); <END> tempOwner = new Object(); context.markResourceRestarted(address, tempOwner); } super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handbackHolder); if (!restartAllowed) { context.revertResourceRestarted(address, tempOwner); } return false; }</code><technical_language>missed this before, this method EAP6 OperationContext.getCurrentAddress Please [this](<LINK_0> instead. WildflyCompatibilityUtils.getCurrentAddress(context, operation) Note EAP6 address is operation</technical_language>

Target:
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, org.jboss.as.controller.AbstractWriteAttributeHandler.HandbackHolder<ModelNode> handbackHolder) throws OperationFailedException { if (!context.isBooting()) { MonitorService agent = getMonitorService(context); if (agent.isImmutable()) { throw new OperationFailedException("The agent is configured to be immutable - no changes are allowed"); } } ModelNode headers = operation.has(OPERATION_HEADERS) ? operation.get(OPERATION_HEADERS) : null; boolean restartAllowedOptionSet = (headers != null) && headers.hasDefined(ALLOW_RESOURCE_SERVICE_RESTART); boolean restartAllowed = !restartAllowedOptionSet || headers.get(ALLOW_RESOURCE_SERVICE_RESTART).asBoolean(); Object tempOwner = null; PathAddress address = null; try { if (!restartAllowed) { address = getParentAddress(WildflyCompatibilityUtils.getCurrentAddress(context, operation)); tempOwner = new Object(); context.markResourceRestarted(address, tempOwner); } super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handbackHolder); } finally { if (!restartAllowed && null != address && null != tempOwner) { context.revertResourceRestarted(address, tempOwner); } } return false; }
Source:
<code><START> public void addNewModelElements(EObject eObject, EReference eReference) { <END> final EObject newMEInstance = getNewModelElementInstance(eObject, eReference); if (newMEInstance == null) { return; } if (eReference.isContainer()) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Operation not permitted for container references!"); return; } if (!eReference.isContainment()) { attachment.addElementToModel(eObject, eReference, newMEInstance); } addReference.addElementToReference(eObject, eReference, newMEInstance); openInNewContext(newMEInstance); }</code><technical_language>I of add() methods return void. user of ReferenceService receive a result of element(s) added. This is useful for example select newly created element, i.e. a table viewer. Note: result empty user pressed cancel in wizard/dialog. I return Optional here, similar I suggested in bug #115184</technical_language>

Target:
public void addNewModelElements(EObject eObject, EReference eReference) { final EObject newMEInstance = getNewModelElementInstance(eObject, eReference); if (newMEInstance == null) { return; } if (eReference.isContainer()) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Operation not permitted for container references!"); return; } if (!eReference.isContainment()) { attachment.addElementToModel(eObject, eReference, newMEInstance); } addReference.addElementsToReference(eObject, eReference, singleton(newMEInstance)); openInNewContext(newMEInstance); }
Source:
<code>public void doManualAck(LinkedList<MessageHeaders> messageHeadersList) { Iterator<MessageHeaders> iterator = messageHeadersList.iterator(); Map<Object, Long> channelsToAck = new HashMap<Object, Long>(); while(iterator.hasNext()) { MessageHeaders messageHeaders = iterator.next(); if (messageHeaders.containsKey(AmqpHeaders.CHANNEL)) { Channel channel = (com.rabbitmq.client.Channel) messageHeaders.get(AmqpHeaders.CHANNEL); Long deliveryTag = (Long) messageHeaders.get(AmqpHeaders.DELIVERY_TAG); <START> channelsToAck.put(channel, deliveryTag); <END> } } for (Map.Entry<Object, Long> entry : channelsToAck.entrySet()) { try { Channel channel = (Channel) entry.getKey(); channel.basicAck(entry.getValue(), true); } catch (IOException e) { logger.error("Exception while manually acknowledging " + e); } } }</code><technical_language>delivery tags (by channel) in right (delivery) order I safe (multiple) ack tag for channel. Understand, though, get duplicates messages. Connection resets half-way a block, unacked messages redelivered added block. delivery tag handling correct</technical_language>

Target:
public void doManualAck(LinkedList<MessageHeaders> messageHeadersList) { Iterator<MessageHeaders> iterator = messageHeadersList.iterator(); Map<Object, Long> channelsToAck = new HashMap<Object, Long>(); while(iterator.hasNext()) { MessageHeaders messageHeaders = iterator.next(); if (messageHeaders.containsKey(AmqpHeaders.CHANNEL)) { Channel channel = (com.rabbitmq.client.Channel) messageHeaders.get(AmqpHeaders.CHANNEL); Long deliveryTag = (Long) messageHeaders.get(AmqpHeaders.DELIVERY_TAG); channelsToAck.put(channel, deliveryTag); } } for (Map.Entry<Object, Long> entry : channelsToAck.entrySet()) { try { ((Channel) entry.getKey()).basicAck(entry.getValue(), true); } catch (IOException e) { logger.error("Exception while manually acknowledging " + e); } } }
Source:
<code>public void testArrayRemoveFunctionVarcharFromCharArray() throws Exception { ResultSet rs = conn.createStatement().executeQuery( "SELECT ARRAY_REMOVE(chars,varchar1) FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); <START> assertEquals(conn.createArrayOf("CHAR", new String[] { "a", "c", "ddd", "e", "c" }), rs.getArray(1)); <END> assertFalse(rs.next()); }</code><technical_language>Instead of removing "bbbb" is longest element trailing spaces, try removing "a" "c" a test</technical_language>

Target:
public void testArrayRemoveFunctionVarcharFromCharArray() throws Exception { ResultSet rs = conn.createStatement().executeQuery( "SELECT ARRAY_REMOVE(chars,varchar1) FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); assertEquals(conn.createArrayOf("CHAR", new String[] { "bbbb", "c", "ddd", "e", "c" }), rs.getArray(1)); assertFalse(rs.next()); }
Source:
<code>private Optional<String> addExplicitEquivalence(Content from, Content to) { if (from.getEquivalentTo().contains(LookupRef.from(to))) { return Optional.empty(); } Set<LookupRef> newExplicits = new HashSet<>(from.getEquivalentTo()); newExplicits.add(LookupRef.from(to)); writeExecutor.updateExplicitEquivalence(from, publishers(newExplicits), newExplicits); <START> return Optional.of(encodeId(from.getId())); <END> }</code><technical_language>response is for response, id1->id2</technical_language>

Target:
private Optional<ExplicitEquivalenceResponse.EquivalenceLink> addExplicitEquivalence(Content from, Content to) { if (from.getEquivalentTo().contains(LookupRef.from(to))) { return Optional.empty(); } Set<LookupRef> newExplicits = new HashSet<>(from.getEquivalentTo()); newExplicits.add(LookupRef.from(to)); writeExecutor.updateExplicitEquivalence(from, publishers(newExplicits), newExplicits); return Optional.of( new ExplicitEquivalenceResponse.EquivalenceLink( encodeId(from.getId()), encodeId(to.getId()) )); }
Source:
<code>public Set<Tuple> zRangeByScoreWithScores(byte[] key, Range range, Limit limit) { Assert.notNull(range, "Range cannot be null for ZRANGEBYSCOREWITHSCORES."); <START> byte[] min = JedisConverters.boundaryToBytesForZRange(range.getMin(), JedisConverters.toBytes("-inf")); <END> byte[] max = JedisConverters.boundaryToBytesForZRange(range.getMax(), JedisConverters.toBytes("+inf")); try { if (isPipelined()) { if (limit != null) { pipeline(new JedisResult( pipeline.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount()), JedisConverters.tupleSetToTupleSet())); } else { pipeline(new JedisResult(pipeline.zrangeByScoreWithScores(key, min, max), JedisConverters.tupleSetToTupleSet())); } return null; } if (isQueueing()) { if (limit != null) { transaction(new JedisResult(transaction.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount()), JedisConverters.tupleSetToTupleSet())); } else { transaction(new JedisResult(transaction.zrangeByScoreWithScores(key, min, max), JedisConverters.tupleSetToTupleSet())); } return null; } if (limit != null) { return JedisConverters.toTupleSet(jedis.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount())); } return JedisConverters.toTupleSet(jedis.zrangeByScoreWithScores(key, min, max)); } catch (Exception ex) { throw convertJedisAccessException(ex); } }</code><technical_language>create a constant for -inf +inf in JedisConverters</technical_language>

Target:
public Set<Tuple> zRangeByScoreWithScores(byte[] key, Range range, Limit limit) { Assert.notNull(range, "Range cannot be null for ZRANGEBYSCOREWITHSCORES."); byte[] min = JedisConverters.boundaryToBytesForZRange(range.getMin(), JedisConverters.NEGATIVE_INFINITY_BYTES); byte[] max = JedisConverters.boundaryToBytesForZRange(range.getMax(), JedisConverters.POSITIVE_INFINITY_BYTES); try { if (isPipelined()) { if (limit != null) { pipeline(new JedisResult( pipeline.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount()), JedisConverters.tupleSetToTupleSet())); } else { pipeline(new JedisResult(pipeline.zrangeByScoreWithScores(key, min, max), JedisConverters.tupleSetToTupleSet())); } return null; } if (isQueueing()) { if (limit != null) { transaction(new JedisResult(transaction.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount()), JedisConverters.tupleSetToTupleSet())); } else { transaction(new JedisResult(transaction.zrangeByScoreWithScores(key, min, max), JedisConverters.tupleSetToTupleSet())); } return null; } if (limit != null) { return JedisConverters.toTupleSet(jedis.zrangeByScoreWithScores(key, min, max, limit.getOffset(), limit.getCount())); } return JedisConverters.toTupleSet(jedis.zrangeByScoreWithScores(key, min, max)); } catch (Exception ex) { throw convertJedisAccessException(ex); } }
Source:
<code>public BackdropNode(Context context) { backdropProvider = context.get(BackdropProvider.class); renderingConfig = context.get(Config.class).getRendering(); worldProvider = context.get(WorldProvider.class); worldRenderer = context.get(WorldRenderer.class); <START> Camera playerCamera = worldRenderer.getActiveCamera(); <END> addDesiredStateChange(new LookThroughNormalized(playerCamera)); initSkysphere(playerCamera.getzFar() < RADIUS ? playerCamera.getzFar() : RADIUS); wireframeStateChange = new SetWireframe(true); RenderingDebugConfig renderingDebugConfig = context.get(Config.class).getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetFboWriteMask(true, false, false, READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new EnableMaterial(SKY_MATERIAL)); addDesiredStateChange(new DisableDepthWriting()); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); skyMaterial = getMaterial(SKY_MATERIAL); int textureSlot = 0; addDesiredStateChange(new SetInputTexture(textureSlot++, Assets.getTexture("engine:sky90").get().getId(), SKY_MATERIAL, "texSky90")); addDesiredStateChange(new SetInputTexture(textureSlot, Assets.getTexture("engine:sky180").get().getId(), SKY_MATERIAL, "texSky180")); }</code><technical_language>activeCamera field: instead of this local playerCamera variable</technical_language>

Target:
public BackdropNode(Context context) { backdropProvider = context.get(BackdropProvider.class); worldRenderer = context.get(WorldRenderer.class); SubmersibleCamera activeCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThroughNormalized(activeCamera)); initSkysphere(activeCamera.getzFar() < RADIUS ? activeCamera.getzFar() : RADIUS); wireframeStateChange = new SetWireframe(true); RenderingDebugConfig renderingDebugConfig = context.get(Config.class).getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); addDesiredStateChange(new BindFbo(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetFboWriteMask(true, false, false, READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new EnableMaterial(SKY_MATERIAL)); addDesiredStateChange(new DisableDepthWriting()); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); skyMaterial = getMaterial(SKY_MATERIAL); int textureSlot = 0; addDesiredStateChange(new SetInputTexture(textureSlot++, "engine:sky90", SKY_MATERIAL, "texSky90")); addDesiredStateChange(new SetInputTexture(textureSlot, "engine:sky180", SKY_MATERIAL, "texSky180")); }
Source:
<code>protected void addResponseHandlers(ChannelPipeline p, Downstream<? super StreamedResponse> downstream) { addHandler(p, "httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { private boolean isKeepAlive; @Override protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { isKeepAlive = HttpUtil.isKeepAlive(msg); <START> msg.headers().forEach(h -> LOGGER.info(h.getKey() + "=" + h.getValue())); <END> p.channel().config().setAutoRead(false); execution.onComplete(() -> { channelPoolMap.get(baseURI).release(ctx.channel()); if (!subscribedTo.get() && ctx.channel().isOpen()) { if (!isKeepAlive) { ctx.close(); } } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(downstream, new DefaultStreamedResponse(p, status, headers, isKeepAlive)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { channelPoolMap.get(baseURI).release(ctx.channel()); if (!isKeepAlive) { LOGGER.error("Closing channel={}", ctx.channel().id().asShortText(), cause); ctx.close(); } error(downstream, cause); } }); }</code><technical_language>is this logging for debugging while working this</technical_language>

Target:
protected void addResponseHandlers(ChannelPipeline p, Downstream<? super StreamedResponse> downstream) { addHandler(p, "httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { private boolean isKeepAlive; @Override protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { isKeepAlive = HttpUtil.isKeepAlive(msg); p.channel().config().setAutoRead(false); execution.onComplete(() -> { channelPoolMap.get(baseURI).release(ctx.channel()); if (!subscribedTo.get() && ctx.channel().isOpen()) { ctx.close(); } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(downstream, new DefaultStreamedResponse(p, status, headers, isKeepAlive)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { channelPoolMap.get(baseURI).release(ctx.channel()); ctx.close(); error(downstream, cause); } }); }
Source:
<code>protected void startDebugging(OpenShiftServerBehaviour beh, DebugContext context, IProgressMonitor monitor) { Dialogs.INSTANCE.warn("Node.js 8+ unsupported ", "Debugging is only supported up to Node.js 7. If your Node.js is newer, debugging will not work.\n" <START> + "If using an OpenShift template to create the application, set 'NODEJS_PROPERTY' to '6'", <END> WARN_NEWER_THAN_NODEJS7_UNSUPPORTED); IDebugListener listener = new IDebugListener() { @Override public void onDebugChange(DebugContext debuggingContext, IProgressMonitor monitor) throws CoreException { int localPort = startPortForwarding(debuggingContext, monitor); NodeDebugLauncher.launch(beh.getServer(), localPort); } @Override public void onPodRestart(DebugContext debuggingContext, IProgressMonitor monitor) throws CoreException { onDebugChange(debuggingContext, monitor); } }; context.setDebugListener(listener); new OpenShiftDebugMode(context).enableDebugging(); }</code><technical_language>do recommand Node 6 text claims support Node 7</technical_language>

Target:
protected void startDebugging(OpenShiftServerBehaviour beh, DebugContext context, IProgressMonitor monitor) { Dialogs.INSTANCE.warn("Node.js 8+ unsupported ", "Debugging is only supported up to Node.js 7. If your Node.js is newer, debugging will not work.\n" + "If using an OpenShift template to create the application, set 'NODEJS_PROPERTY' to '7'", WARN_NEWER_THAN_NODEJS7_UNSUPPORTED); IDebugListener listener = new IDebugListener() { @Override public void onDebugChange(DebugContext debuggingContext, IProgressMonitor monitor) throws CoreException { int localPort = startPortForwarding(debuggingContext, monitor); NodeDebugLauncher.launch(beh.getServer(), localPort); } @Override public void onPodRestart(DebugContext debuggingContext, IProgressMonitor monitor) throws CoreException { onDebugChange(debuggingContext, monitor); } }; context.setDebugListener(listener); new OpenShiftDebugMode(context).enableDebugging(); }
Source:
<code>public void onItemClick(AdapterView<?> parent, View view, int position, long id) { BoxCollaboration collaboration = (BoxCollaboration) mCollaboratorsAdapter.getItem(position); if (collaboration != null) { ArrayList<BoxCollaboration.Role> rolesArr = getRoles(); <START> String collabId = collaboration.getAccessibleBy().getId(); <END> if ((rolesArr == null || rolesArr.size() == 0) && !collabId.equals(mCollaborationsShareVM.getUserId())) { showToast(R.string.box_sharesdk_cannot_get_collaborators); return; } BoxCollaborator collaborator = collaboration.getAccessibleBy(); BoxCollaboration.Role role = collaboration.getRole(); String name = collaborator == null ? getString(R.string.box_sharesdk_another_person) : collaborator.getName(); boolean allowOwner = getItem().getOwnedBy().getId().equals(mCollaborationsShareVM.getUserId()); if (allowOwner){ allowOwner = getItem() instanceof BoxFolder; } mSelectRoleShareVM.setSelectedRole(role); mSelectRoleShareVM.setRoles(rolesArr); mSelectRoleShareVM.setName(name); mSelectRoleShareVM.setAllowRemove(true); mSelectRoleShareVM.setAllowOwnerRole(allowOwner); mSelectRoleShareVM.setCollaboration(collaboration); mCallback.notifySwitchToAccessRoleFragment(); } }</code><technical_language>null check</technical_language>

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { BoxCollaboration collaboration = (BoxCollaboration) mCollaboratorsAdapter.getItem(position); if (collaboration != null) { ArrayList<BoxCollaboration.Role> rolesArr = getRoles(); BoxCollaborator collaborator = collaboration.getAccessibleBy(); String collabId = collaborator == null ? "" : collaborator.getId(); if ((rolesArr == null || rolesArr.size() == 0) && !collabId.equals(mCollaborationsShareVM.getUserId())) { showToast(R.string.box_sharesdk_cannot_get_collaborators); return; } BoxCollaboration.Role role = collaboration.getRole(); String name = collaborator == null ? getString(R.string.box_sharesdk_another_person) : collaborator.getName(); boolean allowOwner = getItem().getOwnedBy().getId().equals(mCollaborationsShareVM.getUserId()); if (allowOwner){ allowOwner = getItem() instanceof BoxFolder; } mSelectRoleShareVM.setSelectedRole(role); mSelectRoleShareVM.setRoles(rolesArr); mSelectRoleShareVM.setName(name); mSelectRoleShareVM.setAllowRemove(true); mSelectRoleShareVM.setAllowOwnerRole(allowOwner); mSelectRoleShareVM.setCollaboration(collaboration); mCallback.notifySwitchToAccessRoleFragment(); } }
Source:
<code>public static void getSpmCandidates(AsyncQuery aQuery, Guid storagePoolId, boolean localFsOnly) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) <START> { <END> if (source != null) { ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source); return list; } return new ArrayList<VDS>(); } }; Frontend.RunQuery(VdcQueryType.GetSpmCandidates, new GetSpmCandidatesQueryParameters(storagePoolId, localFsOnly), aQuery); }</code><technical_language>if write new code please java formatting</technical_language>

Target:
public static void getSpmCandidates(AsyncQuery aQuery, Guid storagePoolId, boolean localFsOnly) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { if (source != null) { return source; } return new ArrayList<VDS>(); } }; Frontend.RunQuery(VdcQueryType.GetSpmCandidates, new GetSpmCandidatesQueryParameters(storagePoolId, localFsOnly), aQuery); }
Source:
<code>public void update(VdsDeployConfig cfg) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("cfg_name", cfg.getConfigName()) .addValue("cfg_type", cfg.getConfigType()) .addValue("cfg_value", cfg.getConfigValue()) .addValue("cfg_id", cfg.getConfigId()); <START> getCallsHandler().executeModification("UpdateVdsDeplotConfig", parameterSource); <END> }</code><technical_language>typo</technical_language>

Target:
public void update(VdsDeployConfig cfg) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("cfg_name", cfg.getConfigName()) .addValue("cfg_type", cfg.getConfigType().toString()) .addValue("cfg_value", cfg.getConfigValue()) .addValue("cfg_id", cfg.getConfigId()); getCallsHandler().executeModification("UpdateVdsDeployConfig", parameterSource); }
Source:
<code>public static String getDefInstallPath () { switch (getCurrentOS()) { case WINDOWS: <START> return "C:\\FTB"; <END> case MACOSX: return System.getProperty("user.home") + "/FTB"; case UNIX: return System.getProperty("user.home") + "/FTB"; default: return System.getProperty("user.home") + System.getProperty("path.separator") + "FTB"; } }</code><technical_language>if a user write permissions directories fallback older code, some users get folders some permissions setups windows domains</technical_language>

Target:
public static String getDefInstallPath () { switch (getCurrentOS()) { case WINDOWS: String defaultLocation = "C:\\FTB"; File testFile = new File(defaultLocation); if (testFile.canWrite()) { return defaultLocation; } if (testFile.getParentFile().canWrite()) { return defaultLocation; } Logger.logWarn("Can't use default installation location. Using current location of the launcher executable."); case MACOSX: return System.getProperty("user.home") + "/FTB"; case UNIX: return System.getProperty("user.home") + "/FTB"; default: try { CodeSource codeSource = LaunchFrame.class.getProtectionDomain().getCodeSource(); File jarFile; jarFile = new File(codeSource.getLocation().toURI().getPath()); return jarFile.getParentFile().getPath(); } catch (URISyntaxException e) { Logger.logError("Unexcepted error", e); } return System.getProperty("user.home") + System.getProperty("path.separator") + "FTB"; } }
Source:
<code>private VariantContext addGenotypingAnnotations(final Map<String, Object> originalAttributes, final VariantContext newVC) { <START> final Map<String, Object> attrs = new HashMap<>(originalAttributes); <END> attrs.put(GATKVCFConstants.MLE_ALLELE_COUNT_KEY, newVC.getAttribute(GATKVCFConstants.MLE_ALLELE_COUNT_KEY)); attrs.put(GATKVCFConstants.MLE_ALLELE_FREQUENCY_KEY, newVC.getAttribute(GATKVCFConstants.MLE_ALLELE_FREQUENCY_KEY)); if (newVC.hasAttribute(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY)) attrs.put(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY, newVC.getAttribute(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY)); return new VariantContextBuilder(newVC).attributes(attrs).make(); }</code><technical_language>a linkedhashmap a treemap if sorting is required</technical_language>

Target:
private VariantContext addGenotypingAnnotations(final Map<String, Object> originalAttributes, final VariantContext newVC) { final Map<String, Object> attrs = new LinkedHashMap<>(originalAttributes); attrs.put(GATKVCFConstants.MLE_ALLELE_COUNT_KEY, newVC.getAttribute(GATKVCFConstants.MLE_ALLELE_COUNT_KEY)); attrs.put(GATKVCFConstants.MLE_ALLELE_FREQUENCY_KEY, newVC.getAttribute(GATKVCFConstants.MLE_ALLELE_FREQUENCY_KEY)); if (newVC.hasAttribute(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY)) { attrs.put(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY, newVC.getAttribute(GATKVCFConstants.NUMBER_OF_DISCOVERED_ALLELES_KEY)); } return new VariantContextBuilder(newVC).attributes(attrs).make(); }
Source:
<code>public AwsRequestSignature sign() { AwsDates dates = getDates(); String serviceName = Splitter.on(".").split(uri.getHost()).iterator().next(); Map<String, String> canonicalHeaders = getCanonicalHeaders(dates.getOriginalDate()); List<String> sortedHeaders = new ArrayList<>(); <START> for (String k : canonicalHeaders.keySet()) { <END> sortedHeaders.add(k.toLowerCase()); } Collections.sort(sortedHeaders); String canonicalRequestHash = createCanonicalRequestHash(canonicalHeaders, sortedHeaders); String credentialScope = dates.getFormattedDate() + "/" + region + "/" + serviceName + "/" + AWS_REQUEST_TYPE; String stringToSign = createStringToSign(canonicalRequestHash, dates.getAmzDate(), credentialScope); String signature = calculateAwsV4Signature( serviceName, awsSecurityCredentials.getSecretAccessKey(), dates.getFormattedDate(), region, stringToSign); return new AwsRequestSignature.Builder() .setSignature(signature) .setCanonicalHeaders(canonicalHeaders) .setHttpMethod(httpMethod) .setSecurityCredentials(awsSecurityCredentials) .setCredentialScope(credentialScope) .setUrl(uri.toString()) .setDate(dates.getOriginalDate()) .setSortedHeaderNames(sortedHeaders) .setRegion(region) .build(); }</code><technical_language>-> key headerName</technical_language>

Target:
AwsRequestSignature sign() { String serviceName = Splitter.on(".").split(uri.getHost()).iterator().next(); Map<String, String> canonicalHeaders = getCanonicalHeaders(dates.getOriginalDate()); List<String> sortedHeaderNames = new ArrayList<>(); for (String headerName : canonicalHeaders.keySet()) { sortedHeaderNames.add(headerName.toLowerCase(Locale.US)); } Collections.sort(sortedHeaderNames); String canonicalRequestHash = createCanonicalRequestHash(canonicalHeaders, sortedHeaderNames); String credentialScope = dates.getFormattedDate() + "/" + region + "/" + serviceName + "/" + AWS_REQUEST_TYPE; String stringToSign = createStringToSign(canonicalRequestHash, dates.getXAmzDate(), credentialScope); String signature = calculateAwsV4Signature( serviceName, awsSecurityCredentials.getSecretAccessKey(), dates.getFormattedDate(), region, stringToSign); String authorizationHeader = generateAuthorizationHeader( sortedHeaderNames, awsSecurityCredentials.getAccessKeyId(), credentialScope, signature); return new AwsRequestSignature.Builder() .setSignature(signature) .setCanonicalHeaders(canonicalHeaders) .setHttpMethod(httpMethod) .setSecurityCredentials(awsSecurityCredentials) .setCredentialScope(credentialScope) .setUrl(uri.toString()) .setDate(dates.getOriginalDate()) .setRegion(region) .setAuthorizationHeader(authorizationHeader) .build(); }
Source:
<code>public void openLocationSettings() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); try { getContext().startActivity(intent); Toast.makeText(getContext(), R.string.set_location_mode_high_accuracy, Toast.LENGTH_LONG).show(); <START> } catch (Exception e) { <END> Toast.makeText(getContext(), R.string.cannot_open_location_settings, Toast.LENGTH_LONG).show(); Timber.e(e); } }</code><technical_language>catch Exception, if need catch exception catch is thrown. need catch Exception here, [resolve intent](<LINK_0></technical_language>

Target:
public void openLocationSettings() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); PackageManager packageManager = getActivity().getPackageManager(); if (intent.resolveActivity(packageManager)!= null) { startActivity(intent); Toast.makeText(getContext(), R.string.recommend_high_accuracy_mode, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getContext(), R.string.cannot_open_location_settings, Toast.LENGTH_LONG).show(); } }
Source:
<code><START> public void submit(String eventBody) throws IOException { <END> DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName(this.getHost()); int port = java.lang.Integer.parseInt(this.getName()); byte[] buffer = eventBody.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port); socket.send(packet); socket.close(); }</code><technical_language>semantics of this submit consistent TcpInput's: submit multiple events this method</technical_language>

Target:
public void submit(String eventBody) throws IOException { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName(this.getHost()); int port = java.lang.Integer.parseInt(this.getName()); byte[] buffer = eventBody.getBytes("UTF8"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port); socket.send(packet); socket.close(); }
Source:
<code>public PoolPickerResponse getPickersBySearch(@RequestParam("platform") String platform, @RequestParam("query") String query) throws IOException { PlatformType platformType = PlatformType.get(platform); return getPoolPickerWithFilters(100, <START> PaginationFilter.platformType(platformType), <END> PaginationFilter.query(query)); }</code><technical_language>sense this support usual search PaginationFilter.parse, indifferent</technical_language>

Target:
public PoolPickerResponse getPickersBySearch(@RequestParam("platform") String platform, @RequestParam("query") String query) throws IOException { return getPoolPickerWithFilters(100, PaginationFilter.platformType(PlatformType.valueOf(platform)), PaginationFilter.query(query)); }
Source:
<code>private static <T> T createClientToMultipleNodes(Class<T> clazz, List<String> nodeNames, short port) { Collection<String> uris = nodeNames.stream() .map(nodeName -> String.format("http://%s:%s", nodeName, port)) .collect(Collectors.toList()); return AtlasDbHttpClients.createProxyWithFailover( new MetricRegistry(), ImmutableServerListConfig.builder() .addAllServers(uris) <START> .sslConfiguration(SslConfiguration.of(Paths.get("var/security/trustStore.jks"))) <END> .build(), clazz, TestProxyUtils.AUXILIARY_REMOTING_PARAMETERS); }</code><technical_language>nit: pull out SslConfiguration a separate constant? share TRUST_CONTEXT above</technical_language>

Target:
private static <T> T createClientToMultipleNodes(Class<T> clazz, List<String> nodeNames, short port) { Collection<String> uris = nodeNames.stream() .map(nodeName -> String.format("http://%s:%s", nodeName, port)) .collect(Collectors.toList()); return AtlasDbHttpClients.createProxyWithFailover( new MetricRegistry(), ImmutableServerListConfig.builder() .addAllServers(uris) .sslConfiguration(SSL_CONFIGURATION) .build(), clazz, TestProxyUtils.AUXILIARY_REMOTING_PARAMETERS); }
Source:
<code>public void stopAndDrainQueueInto(List<Runnable> removedTasks) { stopIfRunning(); <START> synchronized (executeQueueRemoveLock) { <END> clearQueue(executeQueue, removedTasks); } synchronized (scheduleQueue.getModificationLock()) { clearQueue(scheduleQueue, removedTasks); } }</code><technical_language>locking buy anything? locking .add this queue I matter</technical_language>

Target:
public void stopAndDrainQueueInto(List<Runnable> removedTasks) { stopIfRunning(); clearQueue(executeQueue, removedTasks); synchronized (scheduleQueue.getModificationLock()) { clearQueue(scheduleQueue, removedTasks); } }
Source:
<code>protected Map<String, List<Object>> extractPersonAttributes(final X509Certificate certificate) { val attributes = new LinkedHashMap<String, List<Object>>(); if (certificate != null) { if (StringUtils.isNotBlank(certificate.getSigAlgOID())) { attributes.put("sigAlgOid", CollectionUtils.wrapList(certificate.getSigAlgOID())); } val subjectDn = certificate.getSubjectDN(); if (subjectDn != null) { attributes.put("subjectDn", CollectionUtils.wrapList(subjectDn.getName())); } val subjectPrincipal = certificate.getSubjectX500Principal(); if (subjectPrincipal != null) { attributes.put("subjectX500Principal", CollectionUtils.wrapList(subjectPrincipal.getName())); } try { val rfc822Email = getRFC822EmailAddress(certificate.getSubjectAlternativeNames()); if (rfc822Email != null) { attributes.put("x509Rfc822Email", CollectionUtils.wrapList(rfc822Email)); } } catch (final CertificateParsingException e) { <START> LOGGER.warn("Error parsing subject alternative names to get rfc822 email {}", e.getMessage()); <END> } } return attributes; }</code><technical_language>Switch for consistency. Also, log stacktrace please</technical_language>

Target:
protected Map<String, List<Object>> extractPersonAttributes(final X509Certificate certificate) { val attributes = new LinkedHashMap<String, List<Object>>(); if (certificate != null) { if (StringUtils.isNotBlank(certificate.getSigAlgOID())) { attributes.put("sigAlgOid", CollectionUtils.wrapList(certificate.getSigAlgOID())); } val subjectDn = certificate.getSubjectDN(); if (subjectDn != null) { attributes.put("subjectDn", CollectionUtils.wrapList(subjectDn.getName())); } val subjectPrincipal = certificate.getSubjectX500Principal(); if (subjectPrincipal != null) { attributes.put("subjectX500Principal", CollectionUtils.wrapList(subjectPrincipal.getName())); } try { val rfc822Email = getRFC822EmailAddress(certificate.getSubjectAlternativeNames()); if (rfc822Email != null) { attributes.put("x509Rfc822Email", CollectionUtils.wrapList(rfc822Email)); } } catch (final CertificateParsingException e) { LOGGER.warn("Error parsing subject alternative names to get rfc822 email [{}]", e.getMessage()); } } return attributes; }
Source:
<code>@Test public void requestAfterEnqueueFailingThrows() throws IOException, InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); final CountDownLatch latch = new CountDownLatch(1); call.enqueue(new Callback<String>() { <START> @Override public void onResponse(Call<String> call, Response<String> response) { <END> } @Override public void onFailure(Call<String> call, Throwable t) { assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!"); assertThat(writeCount.get()).isEqualTo(1); latch.countDown(); } }); assertTrue(latch.await(1, SECONDS)); try { call.request(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }</code><technical_language>throw new AssertionError</technical_language>

Target:
@Test public void requestAfterEnqueueFailingThrows() throws IOException, InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); final CountDownLatch latch = new CountDownLatch(1); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { } @Override public void onFailure(Call<String> call, Throwable t) { assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!"); assertThat(writeCount.get()).isEqualTo(1); latch.countDown(); } }); assertTrue(latch.await(1, SECONDS)); try { call.request(); fail(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }
Source:
<code>private void enableImmutableTables(ConnectionQueryServices queryServices, ArrayList<String> immutableList, long startWaitTime) { long endWaitTime = EnvironmentEdgeManager.currentTimeMillis(); long waitMore = getWaitMoreTime(endWaitTime, startWaitTime); while (waitMore>0 && !isWaitComplete) { LOGGER.info("waiting for more " + waitMore + " ms for client cache " + "to expire for immutable tables"); try { <START> startWaitTime = EnvironmentEdgeManager.currentTimeMillis(); <END> Thread.sleep(waitMore); isWaitComplete = true; } catch (InterruptedException e) { endWaitTime = EnvironmentEdgeManager.currentTimeMillis(); waitMore = getWaitMoreTime(endWaitTime, startWaitTime); LOGGER.warning("Sleep before starting index rebuild is interrupted. " + "Attempting to sleep again! " + e.getMessage()); isWaitComplete = false; } } for (String dataTableFullName: immutableList) { try (Admin admin = queryServices.getAdmin()) { HashSet<String> indexes = tablesAndIndexes.get(dataTableFullName); enableTable(admin, dataTableFullName, indexes); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while enabling immutable table " + e); tablesAndIndexes.remove(dataTableFullName); immutableList.remove(dataTableFullName); throw new RuntimeException("Manually enable the following tables " + getSubListString(immutableList, dataTableFullName) + " and run the index rebuild ", e); } } }</code><technical_language>change startWaitTime here</technical_language>

Target:
private void enableImmutableTables(ConnectionQueryServices queryServices, ArrayList<String> immutableList, long startWaitTime) { while(true) { long waitMore = getWaitMoreTime(startWaitTime); if (waitMore <= 0) { isWaitComplete = true; break; } try { Thread.sleep(waitMore); isWaitComplete = true; } catch(InterruptedException e) { LOGGER.warning("Sleep before starting index rebuild is interrupted. " + "Attempting to sleep again! " + e.getMessage()); } } for (String dataTableFullName: immutableList) { try (Admin admin = queryServices.getAdmin()) { HashSet<String> indexes = tablesAndIndexes.get(dataTableFullName); enableTable(admin, dataTableFullName, indexes); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while enabling immutable table " + e); tablesAndIndexes.remove(dataTableFullName); immutableList.remove(dataTableFullName); throw new RuntimeException("Manually enable the following tables " + getSubListString(immutableList, dataTableFullName) + " and run the index rebuild ", e); } } }
Source:
<code><START> private synchronized void setVersion() { <END> ClassLoader classLoader = getClass().getClassLoader(); if (classLoader == null) { version.set("dev"); return; } try { Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { try (InputStream is = resources.nextElement().openStream()) { Manifest manifest = new Manifest(is); boolean minioManifestFound; for (Map.Entry<Object, Object> entry : manifest.getMainAttributes().entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); minioManifestFound = key.equals(META_INF_ATTRIB_IMPLEMENTATION_TITLE) && value.equals(META_INF_ATTRIB_IMPLEMENTATION_TITLE_VALUE); if (minioManifestFound) { version.set( manifest.getMainAttributes().getValue(META_INF_ATTRIB_IMPLEMENTATION_VERSION)); return; } } } } } catch (IOException e) { LOGGER.log(Level.SEVERE, "IOException occured", e); version.set("unknown"); return; } version.set("dev"); }</code><technical_language>Do no-op if version is set in another thread. java if (version.get() != null) { return; }</technical_language>

Target:
private synchronized void setVersion() { if (version.get() != null) { return; } version.set("dev"); ClassLoader classLoader = getClass().getClassLoader(); if (classLoader == null) { return; } try { Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { try (InputStream is = resources.nextElement().openStream()) { Manifest manifest = new Manifest(is); if ("minio".equals(manifest.getMainAttributes().getValue("Implementation-Title"))) { version.set(manifest.getMainAttributes().getValue("Implementation-Version")); return; } } } } catch (IOException e) { LOGGER.log(Level.SEVERE, "IOException occurred", e); version.set("unknown"); } }