auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static NumberGenerator getKeyChooser(String requestDistrib, int recordCount, double zipfContant, Properties p) throws WorkloadException { NumberGenerator keychooser = null; if (requestDistrib.compareTo("exponential") == 0) { double percentile = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_PERCENTILE_PROPERTY, ExponentialGenerator.EXPONENTIAL_PERCENTILE_DEFAULT)); double frac = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_FRAC_PROPERTY, ExponentialGenerator.EXPONENTIAL_FRAC_DEFAULT)); keychooser = new ExponentialGenerator(percentile, recordCount * frac); } else if (requestDistrib.compareTo("uniform") == 0) { keychooser = new UniformIntegerGenerator(0, recordCount - 1); } else if (requestDistrib.compareTo("zipfian") == 0) { keychooser = new ZipfianGenerator(recordCount, zipfContant); } else if (requestDistrib.compareTo("latest") == 0) { <START> System.err.println("Latest request distribution is not supported"); <END> } else if (requestDistrib.equals("hotspot")) { double hotsetfraction = Double .parseDouble(p.getProperty(HOTSPOT_DATA_FRACTION, HOTSPOT_DATA_FRACTION_DEFAULT)); double hotopnfraction = Double .parseDouble(p.getProperty(HOTSPOT_OPN_FRACTION, HOTSPOT_OPN_FRACTION_DEFAULT)); keychooser = new HotspotIntegerGenerator(0, recordCount - 1, hotsetfraction, hotopnfraction); } else { throw new WorkloadException("Unknown request distribution \"" + requestDistrib + "\""); } return keychooser; }</code><technical_language>This exit instead of returning null</technical_language>

Target:
private static NumberGenerator getKeyChooser(String requestDistrib, int recordCount, double zipfContant, Properties p) throws WorkloadException { NumberGenerator keychooser = null; switch(requestDistrib) { case "exponential": double percentile = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_PERCENTILE_PROPERTY, ExponentialGenerator.EXPONENTIAL_PERCENTILE_DEFAULT)); double frac = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_FRAC_PROPERTY, ExponentialGenerator.EXPONENTIAL_FRAC_DEFAULT)); keychooser = new ExponentialGenerator(percentile, recordCount * frac); break; case "uniform": keychooser = new UniformIntegerGenerator(0, recordCount - 1); break; case "zipfian": keychooser = new ZipfianGenerator(recordCount, zipfContant); break; case "latest": throw new WorkloadException("Latest request distribution is not supported for RestWorkload."); case "hotspot": double hotsetfraction = Double .parseDouble(p.getProperty(HOTSPOT_DATA_FRACTION, HOTSPOT_DATA_FRACTION_DEFAULT)); double hotopnfraction = Double .parseDouble(p.getProperty(HOTSPOT_OPN_FRACTION, HOTSPOT_OPN_FRACTION_DEFAULT)); keychooser = new HotspotIntegerGenerator(0, recordCount - 1, hotsetfraction, hotopnfraction); break; default: throw new WorkloadException("Unknown request distribution \"" + requestDistrib + "\""); } return keychooser; }
Source:
<code>public void initCredentials() throws Ex; public void act() throws HttpResponseException, IOException, InterruptedException, ExecutorException, Ex; public boolean moreWork(); } <START> <END> public static <Ex extends Throwable> void performRequestWithReinitCredentials(RepeatAction<Ex> a, int retries) throws IOException, InterruptedException, ExecutorException, Ex { int budget = retries; do { a.initCredentials(); try { while (a.moreWork()) { a.act(); budget = retries; } } catch (HttpResponseException e) { if (budget > 0 && e.getStatusCode() == STATUS_CODE_UNAUTHORIZED) { logger.fine("Remote credentials expired, retrying."); budget--; } else { throw new IOException(Messages.AbstractUpload_ExceptionFileUpload(), e); } } } while (a.moreWork()); }</code><technical_language>Nit: remove blank line</technical_language>

Target:
public void initCredentials() throws Ex; public void act() throws HttpResponseException, IOException, InterruptedException, ExecutorException, Ex; public boolean moreWork(); } public static <Ex extends Throwable> void performRequestWithReinitCredentials(RepeatOperation<Ex> a, int retries) throws IOException, InterruptedException, ExecutorException, Ex { int budget = retries; do { a.initCredentials(); try { while (a.moreWork()) { a.act(); budget = retries; } } catch (HttpResponseException e) { if (budget > 0 && e.getStatusCode() == STATUS_CODE_UNAUTHORIZED) { logger.fine("Remote credentials expired, retrying."); budget--; } else { throw new IOException(Messages.AbstractUpload_ExceptionFileUpload(), e); } } } while (a.moreWork()); }
Source:
<code>void setLocalPartitionCount(int partitionCount) { if (!offlineCount.compareAndSet(0, partitionCount)) { <START> logger.warn("Number of OFFLINE partitions has changed before initializing participant metrics"); <END> } }</code><technical_language>this throw IllegalStateException? bug case</technical_language>

Target:
void setLocalPartitionCount(int partitionCount) { if (!offlineCount.compareAndSet(0, partitionCount)) { throw new IllegalStateException( "Number of OFFLINE partitions has changed before initializing participant metrics"); } }
Source:
<code>public void testDumpCommandOnLinux() throws Exception { String[] cmdArray; Process processDump = null; try { if (CarbonCommandToolsUtil.isCurrentOSWindows()) { <START> throw new SkipException("Feature --start is not available for windows"); <END> } else { cmdArray = new String[] {"sh", "carbondump.sh", "-carbonHome", carbonHome, "-pid", processId}; processDump = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArray); } assertTrue(isFoundDumpFile(carbonHome), "Couldn't find the dump file"); } finally { processDump.destroy(); } }</code><technical_language>get utill return current operating system change returning CarbonCommandToolsUtil.getCurrentOperatingSystem() if(CarbonCommandToolsUtil.getCurrentOperatingSystem().equals(OperatingSystem.WINDOWS))</technical_language>

Target:
public void testDumpCommandOnLinux() throws CarbonToolsIntegrationTestException { String[] cmdArray; Process processDump = null; try { if ((CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) ) { throw new SkipException("Feature --start is not available for windows"); } else { cmdArray = new String[] {"sh", "carbondump.sh", "-carbonHome", carbonHome, "-pid", processId}; processDump = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArray); } assertTrue(isFoundDumpFile(carbonHome), "Couldn't find the dump file"); } finally { processDump.destroy(); } }
Source:
<code>public void cleanup() { if (weld != null) { try { weld.shutdown(); } catch (NullPointerException npeException) { <START> Logger.getLogger(CDITestSetup.class.getName()) <END> .log(Level.WARNING, "Problem occured during weld clean up: " + npeException.getMessage()); } } }</code><technical_language>out of curiosity: is a reason java util logging (as opposed slf4j in other places)</technical_language>

Target:
public void cleanup() { if (weld != null) { try { weld.shutdown(); } catch (NullPointerException npeException) { LoggerFactory.getLogger(CDITestSetup.class) .warn("Problem occured during weld clean up: " + npeException.getMessage()); } } }
Source:
<code>private void runWriteRequest(SensorTagRequestInfo requestInfo) { ChannelRecord record = requestInfo.channelRecord; record.setTimestamp(System.currentTimeMillis()); TiSensorTag sensorTag; try { sensorTag = getSensorTag(requestInfo); } catch (KuraBluetoothIOException e) { record.setChannelStatus(new ChannelStatus(FAILURE, message.writeFailed(), null)); <START> logger.error("Io Exception encountered while connecting."); <END> return; } final TypedValue<?> value = record.getValue(); if (!value.getType().equals(DataType.BOOLEAN)) { record.setChannelStatus(new ChannelStatus(FAILURE, message.writeFailed(), null)); logger.error("Only boolean types are allowed for this asset"); return; } switch (requestInfo.sensorName) { case GREEN_LED: if ((boolean) value.getValue()) { sensorTag.switchOnGreenLed(); } else { sensorTag.switchOffGreenLed(); } break; case RED_LED: if ((boolean) value.getValue()) { sensorTag.switchOnRedLed(); } else { sensorTag.switchOffRedLed(); } break; case BUZZER: if ((boolean) value.getValue()) { sensorTag.switchOnBuzzer(); } else { sensorTag.switchOffBuzzer(); } break; default: } record.setChannelStatus(new ChannelStatus(SUCCESS)); }</code><technical_language>a small remark - Io -> IO for comprehension</technical_language>

Target:
private void runWriteRequest(SensorTagRequestInfo requestInfo) { ChannelRecord record = requestInfo.channelRecord; record.setTimestamp(System.currentTimeMillis()); TiSensorTag sensorTag; try { sensorTag = getSensorTag(requestInfo); } catch (KuraBluetoothIOException e) { record.setChannelStatus(new ChannelStatus(FAILURE, message.writeFailed(), null)); logger.error("IO Exception encountered while connecting."); return; } final TypedValue<?> value = record.getValue(); if (!value.getType().equals(DataType.BOOLEAN)) { record.setChannelStatus(new ChannelStatus(FAILURE, message.writeFailed(), null)); logger.error("Only boolean types are allowed for this asset"); return; } switch (requestInfo.sensorName) { case GREEN_LED: if ((boolean) value.getValue()) { sensorTag.switchOnGreenLed(); } else { sensorTag.switchOffGreenLed(); } break; case RED_LED: if ((boolean) value.getValue()) { sensorTag.switchOnRedLed(); } else { sensorTag.switchOffRedLed(); } break; case BUZZER: if ((boolean) value.getValue()) { sensorTag.switchOnBuzzer(); } else { sensorTag.switchOffBuzzer(); } break; default: } record.setChannelStatus(new ChannelStatus(SUCCESS)); }
Source:
<code><START> public CounterToRateMetricTransform( <END> MetricObserver observer, long heartbeat, long estPollingInterval, TimeUnit unit, final Clock clock) { this.observer = observer; this.intervalMillis = TimeUnit.MILLISECONDS.convert(estPollingInterval, unit); final long heartbeatMillis = TimeUnit.MILLISECONDS.convert(heartbeat, unit); this.cache = new LinkedHashMap<MonitorConfig, CounterValue>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<MonitorConfig, CounterValue> eldest) { final long now = clock.now(); final long lastMod = eldest.getValue().getTimestamp(); final boolean expired = (now - lastMod) > heartbeatMillis; if (expired) { LOGGER.debug("heartbeat interval exceeded, expiring {}", eldest.getKey()); } return expired; } }; }</code><technical_language>this is a new constructor, this package private</technical_language>

Target:
CounterToRateMetricTransform( MetricObserver observer, long heartbeat, long estPollingInterval, TimeUnit unit, final Clock clock) { this.observer = observer; this.intervalMillis = TimeUnit.MILLISECONDS.convert(estPollingInterval, unit); final long heartbeatMillis = TimeUnit.MILLISECONDS.convert(heartbeat, unit); this.cache = new LinkedHashMap<MonitorConfig, CounterValue>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<MonitorConfig, CounterValue> eldest) { final long now = clock.now(); final long lastMod = eldest.getValue().getTimestamp(); final boolean expired = (now - lastMod) > heartbeatMillis; if (expired) { LOGGER.debug("heartbeat interval exceeded, expiring {}", eldest.getKey()); } return expired; } }; }
Source:
<code>public Long getOvfGeneration(Guid id) { return getCallsHandler().executeRead("GetOvfGeneration", <START> new ParameterizedRowMapper<Long>() { <END> @Override public Long mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getLong(1); }; }, getCustomMapSqlParameterSource() .addValue("vm_id", id)); }</code><technical_language>Add a createLongMapper() function BaseDAODbFacade instead</technical_language>

Target:
public Long getOvfGeneration(Guid id) { return getCallsHandler().executeRead("GetOvfGeneration", createLongMapper(), getCustomMapSqlParameterSource() .addValue("vm_id", id)); }
Source:
<code>void expandConditions() { expandConditions(whereExpressions, false); for (HsqlArrayList whereExpression : whereExpressions) { <START> if (whereExpression.size() > whereExpressionElementsUpperBound) { <END> String msg = "Limit of predicate expressions in \"where\" clause exceeded the maximum limit of " + whereExpressionElementsUpperBound + " predicates, predicates detected: " + whereExpression.size() + ". Reduce the number of predicates in the \"where\" clause to " + whereExpressionElementsUpperBound; throw new HsqlException(msg, "", ErrorCode.X_47002); } } expandConditions(joinExpressions, false); }</code><technical_language>HSQL parsed expressions here? this parser crashed</technical_language>

Target:
void expandConditions() { expandConditions(whereExpressions, false); expandConditions(joinExpressions, false); }
Source:
<code>protected void onAddElement(Rule element) throws IllegalArgumentException { try { validateModuleIDs(element, element.getModules(Module.class)); resolveConfigurations(element); <START> } catch (Exception e) { <END> logger.debug("Added rule '{}' is invalid", element.getUID(), e); } }</code><technical_language>catch generic Exceptions. this more specific</technical_language>

Target:
protected void onAddElement(Rule element) throws IllegalArgumentException { String uid = element.getUID(); try { resolveConfigurations(element); } catch (IllegalArgumentException e) { logger.debug("Added rule '{}' is invalid", uid, e); } }
Source:
<code>void outputSingleBinary(B options) throws IOException { <START> Function<String, String> escaper = null; <END> String marker = OUTPUT_MARKER; if (config.outputWrapper.contains(OUTPUT_MARKER_JS_STRING)) { marker = OUTPUT_MARKER_JS_STRING; escaper = getJavascriptEscaper(); } Appendable jsOutput; if (config.useJsonStreams) { jsOutput = new StringBuilder(); } else { jsOutput = createDefaultOutput(); } writeOutput( jsOutput, compiler, compiler.toSource(), config.outputWrapper, marker, escaper); closeAppendable(jsOutput); if (config.useJsonStreams) { JsonFileSpec jsonOutput = new JsonFileSpec(jsOutput.toString(), Strings.isNullOrEmpty(config.jsOutputFile) ? "compiled.js" : config.jsOutputFile); if (!Strings.isNullOrEmpty(options.sourceMapOutputPath)) { StringBuilder sourcemap = new StringBuilder(); compiler.getSourceMap().appendTo(sourcemap, jsonOutput.getPath()); jsonOutput.setSourceMap(sourcemap.toString()); } this.filesToStreamOut.add(jsonOutput); } }</code><technical_language>a bit confused this method. Do want output files a json stream in compilation</technical_language>

Target:
void outputSingleBinary(B options) throws IOException { Function<String, String> escaper = null; String marker = OUTPUT_MARKER; if (config.outputWrapper.contains(OUTPUT_MARKER_JS_STRING)) { marker = OUTPUT_MARKER_JS_STRING; escaper = getJavascriptEscaper(); } if (config.useJsonStreams) { this.filesToStreamOut.add(createJsonFile(options, marker, escaper)); } else { Appendable jsOutput = createDefaultOutput(); writeOutput( jsOutput, compiler, compiler.toSource(), config.outputWrapper, marker, escaper); closeAppendable(jsOutput); } }
Source:
<code>public static double calculateDistance(Position firstPosition, Position lastPosition, boolean useOdometer) { <START> BigDecimal distance = new BigDecimal("0.0"); <END> if (useOdometer && firstPosition.getAttributes().containsKey(Position.KEY_ODOMETER) && lastPosition.getAttributes().containsKey(Position.KEY_ODOMETER)) { distance = new BigDecimal(lastPosition.getAttributes().get(Position.KEY_ODOMETER).toString()) .subtract(new BigDecimal(firstPosition.getAttributes().get(Position.KEY_ODOMETER).toString())) .multiply(new BigDecimal("1000")); } else if (firstPosition.getAttributes().containsKey(Position.KEY_TOTAL_DISTANCE) && lastPosition.getAttributes().containsKey(Position.KEY_TOTAL_DISTANCE)) { distance = new BigDecimal(lastPosition.getAttributes().get(Position.KEY_TOTAL_DISTANCE).toString()) .subtract(new BigDecimal(firstPosition.getAttributes().get(Position.KEY_TOTAL_DISTANCE) .toString())); } return distance.setScale(2, RoundingMode.HALF_EVEN).doubleValue(); }</code><technical_language>BigDecimal double value. String weird. for "1000" below. int</technical_language>

Target:
public static double calculateDistance(Position firstPosition, Position lastPosition, boolean useOdometer) { double distance = 0.0; if (useOdometer && firstPosition.getAttributes().containsKey(Position.KEY_ODOMETER) && lastPosition.getAttributes().containsKey(Position.KEY_ODOMETER)) { distance = (((Number) lastPosition.getAttributes().get(Position.KEY_ODOMETER)).doubleValue() - ((Number) firstPosition.getAttributes().get(Position.KEY_ODOMETER)).doubleValue()) * 1000; } else if (firstPosition.getAttributes().containsKey(Position.KEY_TOTAL_DISTANCE) && lastPosition.getAttributes().containsKey(Position.KEY_TOTAL_DISTANCE)) { distance = ((Number) lastPosition.getAttributes().get(Position.KEY_TOTAL_DISTANCE)).doubleValue() - ((Number) firstPosition.getAttributes().get(Position.KEY_TOTAL_DISTANCE)).doubleValue(); } return distance; }
Source:
<code>public void refresh(BavetJoinTriTuple<A, B, C> tuple) { <START> A a = tuple.getFactA(); <END> B b = tuple.getFactB(); C c = tuple.getFactC(); List<BavetAbstractTriTuple<A, B, C>> childTupleList = tuple.getChildTupleList(); for (BavetAbstractTriTuple<A, B, C> childTuple : childTupleList) { session.transitionTuple(childTuple, BavetTupleState.DYING); } childTupleList.clear(); if (tuple.isActive()) { for (BavetAbstractTriNode<A, B, C> childNode : childNodeList) { BavetAbstractTriTuple<A, B, C> childTuple = childNode.createTuple(tuple); childTupleList.add(childTuple); session.transitionTuple(childTuple, BavetTupleState.CREATING); } } tuple.refreshed(); }</code><technical_language>variables</technical_language>

Target:
public void refresh(BavetJoinTriTuple<A, B, C> tuple) { List<BavetAbstractTriTuple<A, B, C>> childTupleList = tuple.getChildTupleList(); for (BavetAbstractTriTuple<A, B, C> childTuple : childTupleList) { session.transitionTuple(childTuple, BavetTupleState.DYING); } childTupleList.clear(); if (tuple.isActive()) { for (BavetAbstractTriNode<A, B, C> childNode : childNodeList) { BavetAbstractTriTuple<A, B, C> childTuple = childNode.createTuple(tuple); childTupleList.add(childTuple); session.transitionTuple(childTuple, BavetTupleState.CREATING); } } tuple.refreshed(); }
Source:
<code>public void testLoadDuringMaitenance() { final LoadQueuePeon mockPeon1 = createEmptyPeon(); final LoadQueuePeon mockPeon2 = createOneCallPeonMock(); LoadRule rule = createLoadRule(ImmutableMap.of( "tier1", 1, "tier2", 1 )); final DataSegment segment = createDataSegment("foo"); EasyMock.expect(mockBalancerStrategy.findNewSegmentHomeReplicator(EasyMock.anyObject(), EasyMock.anyObject())) .andDelegateTo(balancerStrategy) .times(1); EasyMock.replay(mockPeon1, mockPeon2, mockBalancerStrategy); DruidCluster druidCluster = new DruidCluster( null, ImmutableMap.of( "tier1", <START> Stream.of( <END> createServerHolder("tier1", mockPeon1, true) ).collect(Collectors.toCollection(() -> new TreeSet<>())), "tier2", Stream.of( createServerHolder("tier2", mockPeon2, false) ).collect(Collectors.toCollection(() -> new TreeSet<>())) ) ); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(druidCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(druidCluster)) .withReplicationManager(throttler) .withBalancerStrategy(mockBalancerStrategy) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) .withAvailableSegments(Collections.singletonList(segment)).build(), segment ); Assert.assertEquals(1L, stats.getTieredStat(LoadRule.ASSIGNED_COUNT, "tier2")); EasyMock.verify(mockPeon1, mockPeon2, mockBalancerStrategy); }</code><technical_language>For testing purposes, easier Map<String, Iterable<ServerHolder>> parameter in exposed DruidCluster constructor, convert TreeSets internally. tedious provide proper comparator in tests, for example do it</technical_language>

Target:
public void testLoadDuringMaitenance() { final LoadQueuePeon mockPeon1 = createEmptyPeon(); final LoadQueuePeon mockPeon2 = createOneCallPeonMock(); LoadRule rule = createLoadRule(ImmutableMap.of( "tier1", 1, "tier2", 1 )); final DataSegment segment = createDataSegment("foo"); EasyMock.expect(mockBalancerStrategy.findNewSegmentHomeReplicator(EasyMock.anyObject(), EasyMock.anyObject())) .andDelegateTo(balancerStrategy) .times(1); EasyMock.replay(mockPeon1, mockPeon2, mockBalancerStrategy); DruidCluster druidCluster = new DruidCluster( null, ImmutableMap.of( "tier1", Collections.singleton(createServerHolder("tier1", mockPeon1, true)), "tier2", Collections.singleton(createServerHolder("tier2", mockPeon2, false)) ) ); CoordinatorStats stats = rule.run( null, DruidCoordinatorRuntimeParams.newBuilder() .withDruidCluster(druidCluster) .withSegmentReplicantLookup(SegmentReplicantLookup.make(druidCluster)) .withReplicationManager(throttler) .withBalancerStrategy(mockBalancerStrategy) .withBalancerReferenceTimestamp(DateTimes.of("2013-01-01")) .withAvailableSegments(segment).build(), segment ); Assert.assertEquals(1L, stats.getTieredStat(LoadRule.ASSIGNED_COUNT, "tier2")); EasyMock.verify(mockPeon1, mockPeon2, mockBalancerStrategy); }
Source:
<code>private static void putCpus(ITmfStateSystem ss, int quark, Map<String, String> retMap, List<ITmfStateInterval> full, String irqs, int status) { List<@NonNull String> cpuList = new ArrayList<>(); int grandParentAttribute = ss.getParentAttributeQuark(ss.getParentAttributeQuark(quark)); if (grandParentAttribute != org.eclipse.tracecompass.statesystem.core.ITmfStateSystem.ROOT_ATTRIBUTE && ss.getAttributeName(ss.getParentAttributeQuark(ss.getParentAttributeQuark(ss.getParentAttributeQuark(quark)))).equals(Attributes.CPUS)) { cpuList.add(ss.getAttributeName(grandParentAttribute)); } else { for (int cpuQuark : ss.getQuarks(Attributes.CPUS, "*", irqs, ss.getAttributeName(quark))) { ITmfStateInterval interval = full.get(cpuQuark); if (interval.getValue() != null) { Object object = full.get(cpuQuark).getValue(); if (object instanceof Integer) { int objectStatus = (int) object; if (objectStatus == status) { String cpu = ss.getAttributeName(ss.getParentAttributeQuark(ss.getParentAttributeQuark(cpuQuark))); cpuList.add(cpu); } } } } } if (!cpuList.isEmpty()) { <START> Collections.sort(cpuList); <END> retMap.put(Messages.ResourcesStatusDataProvider_attributeCpuName, String.join(", ", cpuList)); } }</code><technical_language>compare numerically</technical_language>

Target:
private static void putCpus(ITmfStateSystem ss, int quark, Map<String, String> retMap, List<ITmfStateInterval> full, String irqs, int status) { List<@NonNull String> cpuList = new ArrayList<>(); int grandParentAttribute = ss.getParentAttributeQuark(ss.getParentAttributeQuark(quark)); if (grandParentAttribute != org.eclipse.tracecompass.statesystem.core.ITmfStateSystem.ROOT_ATTRIBUTE && ss.getAttributeName(ss.getParentAttributeQuark(ss.getParentAttributeQuark(ss.getParentAttributeQuark(quark)))).equals(Attributes.CPUS)) { cpuList.add(ss.getAttributeName(grandParentAttribute)); } else { for (int cpuQuark : ss.getQuarks(Attributes.CPUS, "*", irqs, ss.getAttributeName(quark))) { ITmfStateInterval interval = full.get(cpuQuark); if (interval.getValue() != null) { Object object = full.get(cpuQuark).getValue(); if (object instanceof Integer) { int objectStatus = (int) object; if (objectStatus == status) { String cpu = ss.getAttributeName(ss.getParentAttributeQuark(ss.getParentAttributeQuark(cpuQuark))); cpuList.add(cpu); } } } } } if (!cpuList.isEmpty()) { Collections.sort(cpuList, (s1, s2) -> Integer.compare(Integer.parseInt(s1), Integer.parseInt(s2))); retMap.put(Messages.ResourcesStatusDataProvider_attributeCpuName, String.join(", ", cpuList)); } }
Source:
<code>public Object performOperation(List<Object> input, Map<String, String> parameters) throws TransformationOperationException { <START> if (input.size() != getOperationInputCount()) { <END> throw new TransformationOperationException( "The input values are not matching with the operation input count."); } Object sourceObject = input.get(0); String targetType = parameters.get(typeParam); String targetTypeInit = parameters.get(initFuncParam); Object targetObject = null; Class<?> targetClass = null; try { targetClass = this.getClass().getClassLoader().loadClass(targetType); } catch (Exception e) { String message = "The class %s can't be found. The instantiate operation will be ignored."; message = String.format(message, targetType); LOGGER.error(message); throw new TransformationOperationException(message, e); } try { if (targetTypeInit == null) { Constructor<?> constr = targetClass.getConstructor(sourceObject.getClass()); targetObject = constr.newInstance(sourceObject); } else { Method method = targetClass.getMethod(targetTypeInit, sourceObject.getClass()); if (Modifier.isStatic(method.getModifiers())) { targetObject = method.invoke(null, sourceObject); } else { targetObject = method.invoke(targetClass.newInstance(), sourceObject); } } } catch (Exception e) { String message = "Unable to create the desired object. The instantiate operation will be ignored."; message = String.format(message, targetType); LOGGER.error(message); throw new TransformationOperationException(message, e); } return targetObject; }</code><technical_language>method</technical_language>

Target:
public Object performOperation(List<Object> input, Map<String, String> parameters) throws TransformationOperationException { checkInputSize(input); String targetType = getParameterOrException(parameters, typeParam); String initMethodName = getParameterOrDefault(parameters, initFuncParam, null); return tryInitiatingObject(targetType, initMethodName, input.get(0)); }
Source:
<code>public static WeightedReservoirSampleStateStrategy deserialize(SliceInput input) { <START> WeightedDoubleReservoirSample reservoir = WeightedDoubleReservoirSample.deserialize(input); <END> return new WeightedReservoirSampleStateStrategy(reservoir); }</code><technical_language>inline this variable: return new WeightedReservoirSampleStateStrategy(WeightedDoubleReservoirSample.deserialize(input));</technical_language>

Target:
public static WeightedReservoirSampleStateStrategy deserialize(SliceInput input) { return new WeightedReservoirSampleStateStrategy(WeightedDoubleReservoirSample.deserialize(input)); }
Source:
<code>private Concept mapConcept(org.openmrs.Concept openmrsConcept) { ConceptName fullySpecifiedName = openmrsConcept.getFullySpecifiedName(Context.getLocale()); <START> Concept concept = new Concept(); <END> if (fullySpecifiedName == null) { fullySpecifiedName = openmrsConcept.getFullySpecifiedName(getDefaultLocale()); } if (fullySpecifiedName != null) { concept = new Concept(openmrsConcept.getUuid(), fullySpecifiedName.getName()); } ConceptName shortName = openmrsConcept.getShortNameInLocale(Context.getLocale()); if (shortName != null) { concept.setShortName(shortName.getName()); } return concept; }</code><technical_language>is reason changing this method? working changes</technical_language>

Target:
private Concept mapConcept(org.openmrs.Concept openmrsConcept) { ConceptName fullySpecifiedName = openmrsConcept.getFullySpecifiedName(Context.getLocale()); if(fullySpecifiedName == null){ fullySpecifiedName = openmrsConcept.getFullySpecifiedName(getDefaultLocale()); } Concept concept = new Concept(openmrsConcept.getUuid(), fullySpecifiedName.getName()); ConceptName shortName = openmrsConcept.getShortNameInLocale(Context.getLocale()); if (shortName != null) { concept.setShortName(shortName.getName()); } return concept; }
Source:
<code>public T convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { for (T t : type_.getEnumConstants()) { if (t.toString().equals(value)) { return t; } } String choices = TextHelper.concat(type_.getEnumConstants(), 0, ",", "{", "}"); throw new ArgumentParserException(String.format( TextHelper.LOCALE_ROOT, "could not convert '%s' (choose from %s)", value, choices), <START> null, parser, arg); <END> }</code><technical_language>omit null here, overload</technical_language>

Target:
public T convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { for (T t : type_.getEnumConstants()) { if (t.toString().equals(value)) { return t; } } String choices = TextHelper.concat(type_.getEnumConstants(), 0, ",", "{", "}"); throw new ArgumentParserException(String.format( TextHelper.LOCALE_ROOT, "could not convert '%s' (choose from %s)", value, choices), parser, arg); }
Source:
<code>public void onAsyncPlayerPreLoginEventHighest(AsyncPlayerPreLoginEvent event) { if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) { return; } final String name = event.getName(); if (validationService.isUnrestricted(name)) { return; } try { final PlayerAuth auth = dataSource.getAuth(name); final boolean isAuthAvailable = auth != null; onJoinVerifier.checkKickNonRegistered(isAuthAvailable); <START> final JoiningPlayer joiningPlayer = JoiningPlayer.fromName(name); <END> onJoinVerifier.checkAntibot(joiningPlayer, isAuthAvailable); onJoinVerifier.checkNameCasing(name, auth); final String ip = event.getAddress().getHostAddress(); onJoinVerifier.checkPlayerCountry(joiningPlayer, ip, isAuthAvailable); } catch (FailedVerificationException e) { event.setKickMessage(messages.retrieveSingle(name, e.getReason(), e.getArgs())); event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); } }</code><technical_language>JoiningPlayer#fromPlayer is longer (except in a test) drop class methods player name permissions with</technical_language>

Target:
public void onAsyncPlayerPreLoginEventHighest(AsyncPlayerPreLoginEvent event) { if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) { return; } final String name = event.getName(); if (validationService.isUnrestricted(name)) { return; } try { final PlayerAuth auth = dataSource.getAuth(name); final boolean isAuthAvailable = auth != null; onJoinVerifier.checkKickNonRegistered(isAuthAvailable); onJoinVerifier.checkAntibot(name, isAuthAvailable); onJoinVerifier.checkNameCasing(name, auth); final String ip = event.getAddress().getHostAddress(); onJoinVerifier.checkPlayerCountry(name, ip, isAuthAvailable); } catch (FailedVerificationException e) { event.setKickMessage(messages.retrieveSingle(name, e.getReason(), e.getArgs())); event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); } }
Source:
<code>public boolean isExist(KEY key) throws IOException { <START> return cache.get(new CacheKey<>(key)) != null || <END> rawTable.isExist(codecRegistry.asRawData(key)); }</code><technical_language>Here, need check key. A case createBucket, DeleteBucket, key in cache for bucket, null. is this isExist called lock? modify key while checks happening</technical_language>

Target:
public boolean isExist(KEY key) throws IOException { CacheValue<VALUE> cacheValue= cache.get(new CacheKey<>(key)); return (cacheValue != null && cacheValue.getValue() != null) || rawTable.isExist(codecRegistry.asRawData(key)); }
Source:
<code>public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (methodNode.name.startsWith("lambda$")) { return; } <START> if (methodNode.name.endsWith(KotlinDefaultArgumentsFilter.SUFFIX) <END> && context.getClassAnnotations() .contains(KotlinGeneratedFilter.KOTLIN_METADATA_DESC)) { return; } output.ignore(methodNode.instructions.getFirst(), methodNode.instructions.getLast()); }</code><technical_language>Instead of duplicating logic I prefer encapsulate in respective filters, i.e. * KotlinGeneratedFilter.isKotlinClass(IFilterContext cts) * KotlinDefaultArgumentsFilter.isDefaultArgumentMethod(String name)</technical_language>

Target:
public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (methodNode.name.startsWith("lambda$")) { return; } if (KotlinDefaultArgumentsFilter .isDefaultArgumentsMethodName(methodNode.name) && KotlinGeneratedFilter.isKotlinClass(context)) { return; } output.ignore(methodNode.instructions.getFirst(), methodNode.instructions.getLast()); }
Source:
<code>@Override public byte[] next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (isEmpty()) throw new NoSuchElementException(); try { Element current = readElement(nextElementPosition); byte[] buffer = new byte[current.length]; nextElementPosition = wrapPosition(current.position + Element.HEADER_LENGTH); ringRead(nextElementPosition, buffer, 0, current.length); nextElementPosition = wrapPosition(current.position + Element.HEADER_LENGTH + current.length); nextElementIndex++; return buffer; } catch (IOException e) { <START> throw new RuntimeException("todo: throw a proper error", e); <END> } }</code><technical_language>I 2. do that. I 2 if a BufferedSource a length Okio. later</technical_language>

Target:
@Override public byte[] next() { checkForComodification(); if (isEmpty()) throw new NoSuchElementException(); if (nextElementIndex >= elementCount) throw new NoSuchElementException(); try { Element current = readElement(nextElementPosition); byte[] buffer = new byte[current.length]; nextElementPosition = wrapPosition(current.position + Element.HEADER_LENGTH); ringRead(nextElementPosition, buffer, 0, current.length); nextElementPosition = wrapPosition(current.position + Element.HEADER_LENGTH + current.length); nextElementIndex++; return buffer; } catch (IOException e) { throw new RuntimeException("todo: throw a proper error", e); } }
Source:
<code>public XBeePacket sendXBeePacket(final XBeePacket packet) throws InterfaceNotOpenException, InvalidOperatingModeException, IOException, TimeoutException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet); return null; } } else { sendXBeePacketAsync(packet); return null; } insertFrameID(packet); IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); dataReader.addPacketReceiveListener(packetReceiveListener); <START> logger.debug("Sending XBee packet: \n{}", packet.toPrettyString()); <END> writePacket(packet); try { synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) } if (responseList.size() < 1) throw new TimeoutException(); return responseList.get(0); } finally { dataReader.removePacketReceiveListener(packetReceiveListener); } } }</code><technical_language>move debug traces of sending XBee packets writePacket() method. is method called in instance this avoid adding more debug traces new send packets methods implemented</technical_language>

Target:
public XBeePacket sendXBeePacket(final XBeePacket packet) throws InterfaceNotOpenException, InvalidOperatingModeException, TimeoutException, IOException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet); return null; } } else { sendXBeePacketAsync(packet); return null; } insertFrameID(packet); IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); dataReader.addPacketReceiveListener(packetReceiveListener); writePacket(packet); try { synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) } if (responseList.size() < 1) throw new TimeoutException(); return responseList.get(0); } finally { dataReader.removePacketReceiveListener(packetReceiveListener); } } }
Source:
<code>public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); EnvVars envVars = run.getEnvironment(listener); FilePath buildStepWorkspace = getBuildStepWorkspace(workspace); try { buildStepWorkspace.mkdirs(); } catch (IOException ex) { <START> logger.println(ex.getMessage() + " : Permission denied"); <END> run.setResult(Result.FAILURE); return; } boolean isVirtualenvInstallation = false; if (isGlobalBztInstalled(buildStepWorkspace, logger, launcher, envVars) || (isVirtualenvInstallation = installBztAndCheck(buildStepWorkspace, logger, launcher, envVars))) { int testExitCode = runPerformanceTest(buildStepWorkspace, logger, launcher, envVars, isVirtualenvInstallation); run.setResult(useBztExitCode ? getBztJobResult(testExitCode) : getJobResult(testExitCode) ); if (generatePerformanceTrend && run.getResult().isBetterThan(Result.FAILURE)) { generatePerformanceTrend(run, buildStepWorkspace, launcher, listener); } return; } run.setResult(Result.FAILURE); }</code><technical_language>necessarily permission denied. Right is "Cannot create directory <dir> of error: <exception message>"</technical_language>

Target:
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); EnvVars envVars = run.getEnvironment(listener); FilePath buildStepWorkspace = getBuildStepWorkspace(workspace); try { buildStepWorkspace.mkdirs(); } catch (IOException ex) { logger.println("Cannot create directory because of error: " + ex.getMessage()); run.setResult(Result.FAILURE); return; } boolean isVirtualenvInstallation = false; if (isGlobalBztInstalled(buildStepWorkspace, logger, launcher, envVars) || (isVirtualenvInstallation = installBztAndCheck(buildStepWorkspace, logger, launcher, envVars))) { int testExitCode = runPerformanceTest(buildStepWorkspace, logger, launcher, envVars, isVirtualenvInstallation); run.setResult(useBztExitCode ? getBztJobResult(testExitCode) : getJobResult(testExitCode) ); if (generatePerformanceTrend && run.getResult().isBetterThan(Result.FAILURE)) { generatePerformanceTrend(run, buildStepWorkspace, launcher, listener); } return; } run.setResult(Result.FAILURE); }
Source:
<code>public Configuration getConfiguration(HdfsContext context, URI uri) { @SuppressWarnings("resource") Configuration config = new CachingJobConf((factoryConfig, factoryUri) -> { try { FileSystem fileSystem = (new Path(factoryUri)).getFileSystem(hiveHdfsConfiguration.getConfiguration(context, factoryUri)); checkState(fileSystem instanceof ExtendedFileSystem); <START> return cacheFactory.createCachingFileSystem(factoryConfig, factoryUri, <END> (ExtendedFileSystem) fileSystem, cacheManager, cacheConfig.getCacheType(), cacheConfig.isValidationEnabled()); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create caching file system", e); } }); Configuration defaultConfig = hiveHdfsConfiguration.getConfiguration(context, uri); copy(defaultConfig, config); return config; }</code><technical_language>param line leaving line empty</technical_language>

Target:
public Configuration getConfiguration(HdfsContext context, URI uri) { @SuppressWarnings("resource") Configuration config = new CachingJobConf((factoryConfig, factoryUri) -> { try { FileSystem fileSystem = (new Path(factoryUri)).getFileSystem(hiveHdfsConfiguration.getConfiguration(context, factoryUri)); checkState(fileSystem instanceof ExtendedFileSystem); return cacheFactory.createCachingFileSystem( factoryConfig, factoryUri, (ExtendedFileSystem) fileSystem, cacheManager, cacheConfig.isCachingEnabled(), cacheConfig.getCacheType(), cacheConfig.isValidationEnabled()); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create caching file system", e); } }); Configuration defaultConfig = hiveHdfsConfiguration.getConfiguration(context, uri); copy(defaultConfig, config); return config; }
Source:
<code>public RelDistribution apply(Mappings.TargetMapping mapping) { if (keys.isEmpty()) { return this; } List<Integer> mapList = Mappings.asList(mapping); <START> for (Integer key : keys) { <END> if (mapList.get(key) == null) { return RANDOM_DISTRIBUTED; } } List<Integer> mappedKeys0 = Mappings.apply2((Mapping) mapping, keys); ImmutableIntList mappedKeys = normalizeKeys(mappedKeys0); RelDistribution newDistribution = new RelDistributionImpl(type, mappedKeys); return getTraitDef().canonize(newDistribution); }</code><technical_language>Is int OK here</technical_language>

Target:
public RelDistribution apply(Mappings.TargetMapping mapping) { if (keys.isEmpty()) { return this; } for (int key : keys) { if (mapping.getTargetOpt(key) == -1) { return ANY; } } List<Integer> mappedKeys0 = Mappings.apply2((Mapping) mapping, keys); ImmutableIntList mappedKeys = normalizeKeys(mappedKeys0); return of(type, mappedKeys); }
Source:
<code><START> public InMemoryStore getStore(PartitionId partitionId) { <END> return storesByPartition.get(partitionId); }</code><technical_language>here, package private</technical_language>

Target:
InMemoryStore getStore(PartitionId partitionId) { return storesByPartition.get(partitionId); }
Source:
<code>private Organization getOrganization(final MultivaluedMap<String, String> data) { Organization organization = null; Sid organizationSid = null; String organizationId = null; if (data.containsKey("Organization")) { organizationId = data.getFirst("Organization"); } else { return null; } organization = organizationsDao.getOrganizationByDomainName(organizationId); if (organization != null) { return organization; } else { try { <START> organizationSid = new Sid(organizationId); <END> organization = organizationsDao.getOrganization(organizationSid); return organization; } catch (IllegalArgumentException e) { if (logger.isDebugEnabled()) { logger.debug("Exception while tried to match organizationId to organizationSid"); } } } return organization; }</code><technical_language>Suggestion:can do this check this is domain Sid. If create a Sid form it, for Sid, if not, assume is a domain (which validation is more opened). This optimize number of queries required...</technical_language>

Target:
private Organization getOrganization(final MultivaluedMap<String, String> data) { Organization organization = null; Sid organizationSid = null; String organizationId = null; if (data.containsKey("Organization")) { organizationId = data.getFirst("Organization"); } else { return null; } if (Sid.pattern.matcher(organizationId).matches()) { organization = organizationsDao.getOrganization(new Sid(organizationId)); return organization; } else { organization = organizationsDao.getOrganizationByDomainName(organizationId); return organization; } }
Source:
<code>protected boolean validateImages() { List<DiskImage> imagesToValidate = getDiskImagesToValidate(); DiskImagesValidator diskImagesValidator = new DiskImagesValidator(imagesToValidate); boolean isVmQualifiedForLMOrImagesNotIllegal = getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal()); return getParameters().isNeedsLocking() ? isVmQualifiedForLMOrImagesNotIllegal && validate(diskImagesValidator.diskImagesNotLocked()) <START> : isVmQualifiedForLMOrImagesNotIllegal; <END> }</code><technical_language>return (!getParameters().isNeedsLocking() || validate(diskImagesValidator.diskImagesNotLocked())) && (getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal()));</technical_language>

Target:
protected boolean validateImages() { List<DiskImage> imagesToValidate = getDiskImagesToValidate(); DiskImagesValidator diskImagesValidator = new DiskImagesValidator(imagesToValidate); return (!getParameters().isNeedsLocking() || validate(diskImagesValidator.diskImagesNotLocked())) && (getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal())); }
Source:
<code>public static <T> com.azure.search.documents.implementation.models.IndexAction map(IndexAction<T> obj) { if (obj == null) { return null; } com.azure.search.documents.implementation.models.IndexAction indexAction = new com.azure.search.documents.implementation.models.IndexAction(); if (obj.getActionType() != null) { com.azure.search.documents.implementation.models.IndexActionType actionType = IndexActionTypeConverter.map(obj.getActionType()); indexAction.setActionType(actionType); } ObjectMapper mapper = new JacksonAdapter().serializer(); SerializationUtil.configureMapper(mapper); Map<String, Object> additionalProperties; if (obj.getParamMap() != null) { Map<String, Object> properties = obj.getParamMap(); <START> additionalProperties = mapper.convertValue(properties, Map.class); <END> } else { T properties = obj.getDocument(); additionalProperties = mapper.convertValue(properties, Map.class); } indexAction.setAdditionalProperties(additionalProperties); return indexAction; }</code><technical_language>good for generic Map.class do need a JavaType explicitly determines Map<String, Object></technical_language>

Target:
public static <T> com.azure.search.documents.implementation.models.IndexAction map(IndexAction<T> obj) { if (obj == null) { return null; } com.azure.search.documents.implementation.models.IndexAction indexAction = new com.azure.search.documents.implementation.models.IndexAction(); if (obj.getActionType() != null) { com.azure.search.documents.implementation.models.IndexActionType actionType = IndexActionTypeConverter.map(obj.getActionType()); indexAction.setActionType(actionType); } ObjectMapper mapper = new JacksonAdapter().serializer(); SerializationUtil.configureMapper(mapper); Map<String, Object> additionalProperties; TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {}; if (obj.getParamMap() != null) { Map<String, Object> properties = obj.getParamMap(); mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); additionalProperties = mapper.convertValue(properties, typeRef); } else { T properties = obj.getDocument(); additionalProperties = mapper.convertValue(properties, typeRef); } indexAction.setAdditionalProperties(additionalProperties); return indexAction; }
Source:
<code><START> private CipherFactory(String instanceId, byte[] symmetricKeyBytes) throws CryptoException { <END> symmetricKey = new SecretKeySpec(symmetricKeyBytes, "AES/CFB/PKCS5Padding"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(instanceId.getBytes("UTF-8")); md.update(symmetricKeyBytes); byte[] messageDigest = md.digest(); ivSeedArray = new byte[IV_BYTE_LENGTH]; for (int i = 0; i < IV_BYTE_LENGTH; ++i) { ivSeedArray[i] = messageDigest[(i % messageDigest.length)]; } } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { String msg = "Error constructing ivSeedArray"; log.error(msg, e); throw new CryptoException(msg + " Cause: " + e); } }</code><technical_language>I consistency in throws CryptoException clause methods in this class throw it</technical_language>

Target:
private CipherFactory(String instanceId, byte[] symmetricKeyBytes) { symmetricKey = new SecretKeySpec(symmetricKeyBytes, "AES/CFB/PKCS5Padding"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(instanceId.getBytes("UTF-8")); md.update(symmetricKeyBytes); byte[] messageDigest = md.digest(); ivSeedArray = new byte[IV_BYTE_LENGTH]; for (int i = 0; i < IV_BYTE_LENGTH; ++i) { ivSeedArray[i] = messageDigest[(i % messageDigest.length)]; } } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { String msg = "Error constructing ivSeedArray"; log.error(msg, e); throw new CryptoException(msg + " Cause: " + e); } }