auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void buildVmData() { builder.buildVmProperties(); builder.buildVmVideoCards(); builder.buildVmCD(); builder.buildVmFloppy(); builder.buildVmDrives(); builder.buildVmNetworkInterfaces(); builder.buildVmNetworkCluster(); builder.buildVmBootSequence(); builder.buildVmBootOptions(); builder.buildVmSoundDevices(); builder.buildVmConsoleDevice(); builder.buildVmTimeZone(); builder.buildVmUsbDevices(); builder.buildVmMemoryBalloon(); builder.buildVmWatchdog(); builder.buildVmVirtioScsi(); builder.buildVmRngDevice(); builder.buildUnmanagedDevices(); builder.buildVmSerialNumber(); builder.buildVmNumaProperties(getParameters().getVdsId()); }

Target:
private void buildVmData() { builder.buildVmProperties(); builder.buildVmVideoCards(); builder.buildVmCD(); builder.buildVmFloppy(); builder.buildVmDrives(); builder.buildVmNetworkInterfaces(); builder.buildVmNetworkCluster(); builder.buildVmBootSequence(); builder.buildVmBootOptions(); builder.buildVmSoundDevices(); builder.buildVmConsoleDevice(); builder.buildVmTimeZone(); builder.buildVmUsbDevices(); builder.buildVmMemoryBalloon(); builder.buildVmWatchdog(); builder.buildVmVirtioScsi(); builder.buildVmRngDevice(); builder.buildUnmanagedDevices(); builder.buildVmSerialNumber(); builder.buildVmNumaProperties(); }
Source:
private void updateDiskVmSnapshotId() { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); DiskImage diskImage = ((DiskImage) disk); getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), snapshotId); diskImage.setvm_snapshot_id(snapshotId); } }

Target:
private void updateDiskVmSnapshotId() { Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = ((DiskImage) disk); getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), snapshotId); diskImage.setvm_snapshot_id(snapshotId); } else { throw new VdcBLLException(VdcBllErrors.StorageException, "update of snapshot id was initiated for unsupported disk type"); } }
Source:
public void setAsCopy(byte[] data, int offset) { clear(); int count = Marshal.getInt(data, offset); offset += HEADER_SIZE; for (int i = 0; i < count; i++) { byte activeFields = data[offset]; offset++; long uuid = Marshal.getLong(data, offset); ReadHeadInfo curInfo = new ReadHeadInfo(uuid, null, null); offset += ReadHeadInfo.ITEM_SIZE; if ((activeFields & READHEADINFO_FIELDS.THIS_READSEQUENCE) != 0) { curInfo.getThisReadSequence().setAsCopy(data, offset); offset += curInfo.getThisReadSequence().getLength(); } if ((activeFields & READHEADINFO_FIELDS.MATE_READSEQUENCE) != 0) { curInfo.getMateReadSequence().setAsCopy(data, offset); offset += curInfo.getMateReadSequence().getLength(); } add(curInfo); } }

Target:
public int setAsCopy(byte[] data, int offset) { clear(); int count = Marshal.getInt(data, offset); offset += HEADER_SIZE; for (int i = 0; i < count; i++) { ReadHeadInfo curInfo = new ReadHeadInfo(data, offset); offset += curInfo.getLengthInBytes(); add(curInfo); } return offset; }
Source:
private PhoenixSequence resolveSequence(String name) { try { SequenceManager manager = new SequenceManager((PhoenixStatement)pc.createStatement()); manager.newSequenceReference(pc.getTenantId(), TableName.createNormalized(schemaName, name) , null, SequenceValueParseNode.Op.NEXT_VALUE); manager.validateSequences(Sequence.ValueOp.VALIDATE_SEQUENCE); } catch (SQLException e){ return null; } return new PhoenixSequence(schemaName, name, pc); }

Target:
private PhoenixSequence resolveSequence(String name) { try { SequenceManager manager = new SequenceManager(statement); manager.newSequenceReference(pc.getTenantId(), TableName.createNormalized(schemaName, name) , null, SequenceValueParseNode.Op.NEXT_VALUE); manager.validateSequences(Sequence.ValueOp.VALIDATE_SEQUENCE); } catch (SQLException e){ return null; } return new PhoenixSequence(schemaName, name, pc); }
Source:
private void AES_CCM_Decrypt(AlgorithmID alg, byte[] rgbKey) throws CoseException, IllegalStateException { if (rgbKey.length != alg.getKeySize() / 8) { throw new CoseException("Key Size is incorrect"); } final int ivLen = getAES_CCM_IVSize(alg); CBORObject iv = findAttribute(HeaderKeys.IV); if (iv == null) { throw new CoseException("Missing IV during decryption"); } if (iv.getType() != CBORType.ByteString) { throw new CoseException("IV is incorrectly formed"); } if (iv.GetByteString().length != ivLen) { throw new CoseException("IV size is incorrect"); } try { rgbContent = CCMBlockCipher.decrypt(rgbKey, iv.GetByteString(), getExternal(), getEncryptedContent(), 0); } catch (NoSuchAlgorithmException ex) { throw new CoseException("Algorithm not supported", ex); } catch (InvalidKeyException ex) { if (ex.getMessage() == "Illegal key size") { throw new CoseException("Unsupported key size", ex); } throw new CoseException("Decryption failure", ex); } catch (Exception ex) { ex.printStackTrace(); throw new CoseException("Decryption failure", ex); } }

Target:
private void AES_CCM_Decrypt(AlgorithmID alg, byte[] rgbKey) throws CoseException, IllegalStateException { if (rgbKey.length != alg.getKeySize() / 8) { throw new CoseException("Key Size is incorrect"); } final int ivLen = getAES_CCM_IVSize(alg); CBORObject iv = findAttribute(HeaderKeys.IV); if (iv == null) { throw new CoseException("Missing IV during decryption"); } if (iv.getType() != CBORType.ByteString) { throw new CoseException("IV is incorrectly formed"); } if (iv.GetByteString().length != ivLen) { throw new CoseException("IV size is incorrect"); } try { rgbContent = CCMBlockCipher.decrypt(rgbKey, iv.GetByteString(), getExternal(), getEncryptedContent(), 0); } catch (NoSuchAlgorithmException ex) { throw new CoseException("Algorithm not supported", ex); } catch (InvalidKeyException ex) { if (ex.getMessage().equals("Illegal key size")) { throw new CoseException("Unsupported key size", ex); } throw new CoseException("Decryption failure", ex); } catch (Exception ex) { ex.printStackTrace(); throw new CoseException("Decryption failure", ex); } }
Source:
public Iterable<AccountGroup> all() { final List<AccountGroup> groups = new LinkedList<AccountGroup>(); for (final AccountGroup.NameKey groupName : list.get(ListKey.ALL)) { final AccountGroup group = get(groupName); if (group != null) { groups.add(group); } } return Collections.unmodifiableList(groups); }

Target:
public Iterable<AccountGroup> all() { final List<AccountGroup> groups = new ArrayList<AccountGroup>(); for (final AccountGroup.NameKey groupName : list.get(ListKey.ALL)) { final AccountGroup group = get(groupName); if (group != null) { groups.add(group); } } return Collections.unmodifiableList(groups); }
Source:
public void prepareForNextRead(int positionCount, int[] positions) throws IOException { lengthIndex = 0; outputPositionCount = 0; int totalPositions = positions[positionCount - 1] + 1; int nullValues = 0; if (presentStream != null) { isNullVector = new boolean[totalPositions]; nullValues = presentStream.getUnsetBits(totalPositions, isNullVector); } lengthVector = new int[totalPositions - nullValues]; if (isNullVector == null) { lengthStream.nextIntVector(totalPositions, lengthVector, 0); totalLength = Arrays.stream(lengthVector).sum(); } else { int lengths = 0; for (int i = 0; i < totalPositions; i++) { if (!isNullVector[i]) { int currentLength = toIntExact(lengthStream.next()); lengthVector[lengths++] = currentLength; totalLength += currentLength; } } } data = new byte[totalLength]; slice = Slices.wrappedBuffer(data); }

Target:
private void prepareForNextRead(int positionCount, int[] positions) throws IOException { lengthIndex = 0; outputPositionCount = 0; int totalLength = 0; int maxLength = 0; int totalPositions = positions[positionCount - 1] + 1; int nullCount = 0; if (presentStream != null) { isNullVector = ensureCapacity(isNullVector, totalPositions); nullCount = presentStream.getUnsetBits(totalPositions, isNullVector); } if (lengthStream != null) { int nonNullCount = totalPositions - nullCount; lengthVector = ensureCapacity(lengthVector, nonNullCount); lengthStream.nextIntVector(nonNullCount, lengthVector, 0); for (int i = 0; i < nonNullCount; i++) { totalLength += lengthVector[i]; maxLength = Math.max(maxLength, lengthVector[i]); } if (totalLength > ONE_GIGABYTE) { throw new PrestoException( GENERIC_INTERNAL_ERROR, format("Values in column \"%s\" are too large to process for Presto. %s column values are larger than 1GB [%s]", streamDescriptor.getFieldName(), positionCount, streamDescriptor.getOrcDataSourceId())); } } if (outputRequired) { if (presentStream != null && nullsAllowed) { nulls = ensureCapacity(nulls, positionCount); } data = ensureCapacity(data, totalLength); offsets = ensureCapacity(offsets, totalPositions + 1); } else { data = ensureCapacity(data, maxLength); } dataAsSlice = Slices.wrappedBuffer(data); }
Source:
public void dump(ReadBuffer readBuffer, PrintStream out, int depth) { out.print(" type: "); out.print(getClass().getSimpleName()); out.print(" name: "); out.print(name()); out.print(" decoded: ["); out.print(decode(readBuffer)); out.print("]"); }

Target:
public void dump(ReadBuffer readBuffer, PrintStream out, int depth) { out.append(" type: ").append(getClass().getSimpleName()); out.append(" name: ").append(name()); T decoded = decode(readBuffer); out.append(" decoded: [").append(decoded == null ? null : decoded.toString()).append("]"); }
Source:
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) { if ("Push Hook".equals(headers.getFirst("x-git-oschina-event"))) { if (request.get("commits") instanceof Collection && ((Collection<Map<String, Object>>) request.get("commits")).size() > 0) { return new PropertyPathNotification("application.yml"); } } return null; }

Target:
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) { if (HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY))) { if (request.get("commits") instanceof Collection && ((Collection<Map<String, Object>>) request.get("commits")).size() > 0) { return new PropertyPathNotification("application.yml"); } } return null; }
Source:
private void prepareData() throws IOException { Cipher cipher = null; try { cipher = (Cipher)ReflectionUtils.newInstance( ReflectionUtils.getClassByName(jceCipherClass), props, transformation); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto cipher!"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = new CryptoOutputStream(baos, cipher, defaultBufferSize, key, iv); out.write(data); out.flush(); out.close(); encData = baos.toByteArray(); try { testDataFilepath = Files.createTempFile("encData", ".tmp"); SeekableByteChannel sbc = Files.newByteChannel(testDataFilepath, StandardOpenOption.APPEND); ByteBuffer bfSrc = ByteBuffer.wrap(encData); sbc.write(bfSrc); sbc.close(); } catch (IOException ioe) { LOG.error("Error when prepare file with encryption data.", ioe); } }

Target:
private void prepareData() throws IOException { Cipher cipher = null; try { cipher = (Cipher)ReflectionUtils.newInstance( ReflectionUtils.getClassByName(jceCipherClass), props, transformation); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto cipher!"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = new CryptoOutputStream(baos, cipher, bufferSize, key, iv); out.write(testData); out.flush(); out.close(); encData = baos.toByteArray(); }
Source:
public Object getProperty(Object object, QName name) throws Exception { if ("geometryMember".equals(name.getLocalPart())) { GeometryCollection multiGeometry = (GeometryCollection) object; Geometry[] members = new Geometry[multiGeometry.getNumGeometries()]; for (int i = 0; i < members.length; i++) { members[i] = (Geometry) multiGeometry.getGeometryN(i); } GML3EncodingUtils.setChildIDs(multiGeometry); return members; } return null; }

Target:
public Object getProperty(Object object, QName name) throws Exception { if (GML.geometryMember.getLocalPart().equals(name.getLocalPart())) { GeometryCollection multiGeometry = (GeometryCollection) object; Geometry[] members = new Geometry[multiGeometry.getNumGeometries()]; for (int i = 0; i < members.length; i++) { members[i] = (Geometry) multiGeometry.getGeometryN(i); } GML3EncodingUtils.setChildIDs(multiGeometry); return members; } return null; }
Source:
public static String getDefaultLintVersion(Project project) { Optional<ResolvedArtifact> lintArtifact = project.getBuildscript() .getConfigurations() .getByName("classpath") .getResolvedConfiguration() .getResolvedArtifacts() .stream() .filter(LintUtil::findLint) .findFirst(); return lintArtifact.map(r -> r.getModuleVersion().getId().getVersion()).orElse(null); }

Target:
public static String getDefaultLintVersion(Project project) { return project.getBuildscript() .getConfigurations() .getByName("classpath") .getResolvedConfiguration() .getResolvedArtifacts() .parallelStream() .filter(LintUtil::findLint) .findFirst() .map(r -> r.getModuleVersion().getId().getVersion()) .orElse(null); }
Source:
public SchemaRepository<JsonSchema> provide() { jsonSchemaFactory = JsonSchemaFactory.byDefault(); return new SchemaRepository<>(schemaSourceProvider, Executors.newFixedThreadPool(2), source -> { try { return jsonSchemaFactory.getJsonSchema(objectMapper.readTree(source.value())); } catch (IOException | ProcessingException e) { throw new RuntimeException(e); } }); }

Target:
public SchemaRepository<JsonSchema> provide() { return new SchemaRepository<>(configFactory, schemaSourceProvider, createSchemaReloadExecutorService(configFactory, "json"), source -> { try { return jsonSchemaFactory.getJsonSchema(objectMapper.readTree(source.value())); } catch (IOException | ProcessingException e) { throw new JsonSchemaCompilationFailed(e); } }); }
Source:
public NodePresentation getPresentation(boolean update) { if (nodePresentation == null) { nodePresentation = new NodePresentation(); updatePresentation(nodePresentation); } if (update) { updatePresentation(nodePresentation); } return nodePresentation; }

Target:
public NodePresentation getPresentation(boolean update) { if (nodePresentation == null) { nodePresentation = new NodePresentation(); updatePresentation(nodePresentation); return nodePresentation; } if (update) { updatePresentation(nodePresentation); } return nodePresentation; }
Source:
private void maybeBackFillToNewStore() { if (!config.backFillAccountsToNewZNode) { return; } logger.trace("starting backfilling the new state to new store"); if (backFillStore.updateAccounts( accountInfoMapRef.get().getAccounts())) { logger.trace("Finish backfilling the new state to new store"); } else { logger.error("Fail to backfill the new state to new store, just skip this one"); } }

Target:
private void maybeBackFillToNewStore() { if (!config.backFillAccountsToNewZNode) { return; } logger.info("Starting backfilling the new state to new store"); if (backFillStore.updateAccounts(accountInfoMapRef.get().getAccounts())) { logger.info("Finish backfilling the new state to new store"); } else { logger.error("Fail to backfill the new state to new store, just skip this one"); } }
Source:
private static Pair<Integer, Integer> getRoughDimensImposedByContainer(int originalHeight, int originalWidth, int boundingHeight, int boundingWidth) { if (originalHeight < boundingHeight || originalWidth < boundingWidth) { return new Pair<>(originalWidth, originalHeight); } double heightScaleDownFactor = (double)boundingHeight / originalHeight; double widthScaleDownFactor = (double)boundingWidth / originalWidth; double dominantScaleDownFactor = Math.min(widthScaleDownFactor, heightScaleDownFactor); int widthImposedByContainer = (int)Math.round(originalWidth * dominantScaleDownFactor); int heightImposedByContainer = (int)Math.round(originalHeight * dominantScaleDownFactor); return new Pair<>(widthImposedByContainer, heightImposedByContainer); }

Target:
private static Pair<Integer, Integer> getRoughDimensImposedByContainer(int originalHeight, int originalWidth, int boundingHeight, int boundingWidth) { if (originalHeight < boundingHeight || originalWidth < boundingWidth) { return new Pair<>(originalWidth, originalHeight); } double heightScaleDownFactor = (double)boundingHeight / originalHeight; double widthScaleDownFactor = (double)boundingWidth / originalWidth; double dominantScaleDownFactor = Math.max(widthScaleDownFactor, heightScaleDownFactor); int widthImposedByContainer = (int)Math.round(originalWidth * dominantScaleDownFactor); int heightImposedByContainer = (int)Math.round(originalHeight * dominantScaleDownFactor); return new Pair<>(widthImposedByContainer, heightImposedByContainer); }
Source:
public void testVacuumDoesNotBreakStuff() throws Exception { Connection connection = spliceClassWatcher.getOrCreateConnection(); long[] conglomerateNumber = SpliceAdmin.getConglomNumbers(connection, CLASS_NAME, TABLE); String conglomerateString = Long.toString(conglomerateNumber[0]); try(PreparedStatement ps = methodWatcher.prepareStatement(String.format("drop table %s.%s", CLASS_NAME, TABLE))){ ps.execute(); } try(HBaseAdmin admin=new HBaseAdmin(new Configuration())){ Set<String> beforeTables=getConglomerateSet(admin.listTables()); try(CallableStatement callableStatement=methodRule.prepareCall("call SYSCS_UTIL.VACUUM()")){ callableStatement.execute(); } Set<String> afterTables=getConglomerateSet(admin.listTables()); Assert.assertTrue(beforeTables.contains(conglomerateString)); Assert.assertFalse(afterTables.contains(conglomerateString)); Set<String> deletedTables=getDeletedTables(beforeTables,afterTables); for(String t : deletedTables){ long conglom=new Long(t); Assert.assertTrue(BasicDatabase.isSystemConglomerate(conglom)); } } }

Target:
public void testVacuumDoesNotBreakStuff() throws Exception { Connection connection = spliceClassWatcher.getOrCreateConnection(); long[] conglomerateNumber = SpliceAdmin.getConglomNumbers(connection, CLASS_NAME, TABLE); String conglomerateString = Long.toString(conglomerateNumber[0]); try(PreparedStatement ps = methodWatcher.prepareStatement(String.format("drop table %s.%s", CLASS_NAME, TABLE))){ ps.execute(); } try(HBaseAdmin admin=new HBaseAdmin(new Configuration())){ Set<String> beforeTables=getConglomerateSet(admin.listTables()); try(CallableStatement callableStatement=methodRule.prepareCall("call SYSCS_UTIL.VACUUM()")){ callableStatement.execute(); } Set<String> afterTables=getConglomerateSet(admin.listTables()); Assert.assertTrue(beforeTables.contains(conglomerateString)); Assert.assertFalse(afterTables.contains(conglomerateString)); Set<String> deletedTables=getDeletedTables(beforeTables,afterTables); Set<String> systemConglomerates = getSystemConglomerateSet(); for(String t : deletedTables){ long conglom=new Long(t); Assert.assertTrue(!systemConglomerates.contains(conglom)); } } }
Source:
public int visit(IASTExpression expression) { if (!ctorDtorStack.empty() && ctorDtorStack.peek()) { if (expression instanceof IASTFunctionCallExpression) { IASTFunctionCallExpression fCall = (IASTFunctionCallExpression) expression; IASTExpression fNameExp = fCall.getFunctionNameExpression(); IBinding fBinding = null; IASTNode problemNode = expression; boolean isQualified = false; if (fNameExp instanceof IASTIdExpression) { IASTIdExpression fName = (IASTIdExpression) fNameExp; isQualified = fName.getName() instanceof ICPPASTQualifiedName; fBinding = fName.getName().resolveBinding(); } else if (fNameExp instanceof IASTFieldReference) { IASTFieldReference fName = (IASTFieldReference) fNameExp; problemNode = fName.getFieldName(); if (referencesThis(fName.getFieldOwner())) fBinding = fName.getFieldName().resolveBinding(); } if (fBinding instanceof ICPPMethod) { ICPPMethod method = (ICPPMethod) fBinding; if (method.isPureVirtual() || (!isQualified && ClassTypeHelper.isVirtual(method))) { reportProblem(VIRTUAL_CALL_ID, problemNode); } } } } return PROCESS_CONTINUE; }

Target:
public int visit(IASTExpression expression) { if (!ctorDtorStack.empty() && ctorDtorStack.peek()) { if (expression instanceof IASTFunctionCallExpression) { IASTFunctionCallExpression fCall = (IASTFunctionCallExpression) expression; IASTExpression fNameExp = fCall.getFunctionNameExpression(); IBinding fBinding = null; IASTNode problemNode = expression; boolean isQualified = false; if (fNameExp instanceof IASTIdExpression) { IASTIdExpression fName = (IASTIdExpression) fNameExp; isQualified = fName.getName() instanceof ICPPASTQualifiedName; fBinding = fName.getName().resolveBinding(); } else if (fNameExp instanceof IASTFieldReference) { IASTFieldReference fName = (IASTFieldReference) fNameExp; problemNode = fName.getFieldName(); if (referencesThis(fName.getFieldOwner())) { isQualified = fName.getFieldName() instanceof ICPPASTQualifiedName; fBinding = fName.getFieldName().resolveBinding(); } } if (fBinding instanceof ICPPMethod) { ICPPMethod method = (ICPPMethod) fBinding; if (method.isPureVirtual() || (!isQualified && ClassTypeHelper.isVirtual(method))) { reportProblem(VIRTUAL_CALL_ID, problemNode); } } } } return PROCESS_CONTINUE; }
Source:
public boolean normalize(List<Artifact> pluginArtifacts, File file, File packFile, boolean fork) throws IOException { JarFile jarFile = new JarFile(file); try { EclipseInf eclipseInf = EclipseInf.readEclipseInf(jarFile); assertSupportedEclipseInf(eclipseInf); if (eclipseInf == null || (eclipseInf.shouldPack() && !eclipseInf.isPackNormalized())) { if (isSigned(jarFile)) { throw new IOException("pack200:normalize cannot be called for signed jar " + file); } log.info("Pack200 normalizing jar " + file.getAbsolutePath()); File tmpFile = null; if (eclipseInf != null) { eclipseInf.setPackNormalized(); tmpFile = File.createTempFile(file.getName(), ".prepack"); updateEclipseInf(jarFile, eclipseInf, tmpFile); } try { getPackWrapper(fork).pack(pluginArtifacts, tmpFile != null ? tmpFile : file, packFile); } finally { if (tmpFile != null) { if (!tmpFile.delete()) { throw new IOException("Could not delete temporary file " + tmpFile.getAbsolutePath()); } } } return true; } } finally { try { jarFile.close(); } catch (IOException e) { } } return false; }

Target:
public boolean normalize(List<Artifact> pluginArtifacts, File file, File packFile, boolean fork) throws IOException { File jarToBePacked = file; boolean shouldNormalize = false; boolean jarToBePackedIsTempFile = false; try (JarFile jarFile = new JarFile(file)) { EclipseInf eclipseInf = EclipseInf.readEclipseInf(jarFile); assertSupportedEclipseInf(eclipseInf); if (eclipseInf == null || (eclipseInf.shouldPack() && !eclipseInf.isPackNormalized())) { if (isSigned(jarFile)) { throw new IOException("pack200:normalize cannot be called for signed jar " + file); } shouldNormalize = true; if (eclipseInf != null) { eclipseInf.setPackNormalized(); jarToBePacked = File.createTempFile(file.getName(), ".prepack"); jarToBePackedIsTempFile = true; updateEclipseInf(jarFile, eclipseInf, jarToBePacked); } } } if (shouldNormalize) { try { log.info("Pack200 normalizing jar " + file.getAbsolutePath()); getPackWrapper(fork).pack(pluginArtifacts, jarToBePacked, packFile); } finally { if (jarToBePackedIsTempFile) { if (!jarToBePacked.delete()) { throw new IOException("Could not delete temporary file " + jarToBePacked.getAbsolutePath()); } } } return true; } return false; }
Source:
public void sampleConfiguration() { String property = System.getProperty("java.version"); System.out.println(property); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableRabbitSampleConfig.class, SampleBean.class); testSampleConfiguration(context); }

Target:
public void sampleConfiguration() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( EnableRabbitSampleConfig.class, SampleBean.class); testSampleConfiguration(context); }
Source:
private void addRTSPProperties(RTPSession rtpSession, HashMap<String, Object> hashMapInstance, String entryId){ HashMap<String,Object> RTSPropertiesHash = new HashMap<String,Object>(); String RTSPUrl, encoder,IP, sessionId; IP = rtpSession.getIp(); sessionId = rtpSession.getSessionId(); RTSPUrl = rtpSession.getUri() + rtpSession.getQueryStr(); double timeRunningSeconds = rtpSession.getTimeRunningSeconds(); RTSPropertiesHash.put("IP", IP); RTSPropertiesHash.put("sessionId", sessionId); RTSPropertiesHash.put("RTSPUrl", RTSPUrl); RTSPropertiesHash.put("timeRunningSeconds" , timeRunningSeconds); hashMapInstance.put("RTPSProperties", RTSPropertiesHash); }

Target:
private void addRTSPProperties(RTPSession rtpSession, HashMap<String, Object> hashMapInstance, String entryId){ HashMap<String,Object> propertiesHash = new HashMap<String,Object>(); String RTSPUrl, encoder,IP, sessionId; IP = rtpSession.getIp(); sessionId = rtpSession.getSessionId(); RTSPUrl = rtpSession.getUri() + rtpSession.getQueryStr(); WMSProperties clientProps = rtpSession.getProperties(); encoder = clientProps.getPropertyStr(Constants.CLIENT_PROPERTY_ENCODER); double timeRunningSeconds = rtpSession.getTimeRunningSeconds(); propertiesHash.put("timeRunningSeconds" , timeRunningSeconds); propertiesHash.put("ConnectionUrl", RTSPUrl); propertiesHash.put("encoder" , encoder); propertiesHash.put("IP", IP); propertiesHash.put("Id", sessionId); hashMapInstance.put("Properties", propertiesHash); }
Source:
private void setHeartRateMeasurementValue(int heartRateMeasurementValue, int expendedEnergy) { Log.d(TAG, Arrays.toString(mHeartRateMeasurementCharacteristic.getValue())); mHeartRateMeasurementCharacteristic.setValue(new byte[]{1 << 3, 0, 0, 0}); mHeartRateMeasurementCharacteristic.setValue(heartRateMeasurementValue, BluetoothGattCharacteristic.FORMAT_UINT8, 1); mEditTextHeartRateMeasurement.setText(Integer.toString(heartRateMeasurementValue)); mHeartRateMeasurementCharacteristic.setValue(expendedEnergy, BluetoothGattCharacteristic.FORMAT_UINT16, 2); mEditTextEnergyExpended.setText(Integer.toString(expendedEnergy)); }

Target:
private void setHeartRateMeasurementValue(int heartRateMeasurementValue, int expendedEnergy) { Log.d(TAG, Arrays.toString(mHeartRateMeasurementCharacteristic.getValue())); mHeartRateMeasurementCharacteristic.setValue(new byte[]{0b00001000, 0, 0, 0}); mHeartRateMeasurementCharacteristic.setValue(heartRateMeasurementValue, HEART_RATE_MEASUREMENT_VALUE_FORMAT, 1); mEditTextHeartRateMeasurement.setText(Integer.toString(heartRateMeasurementValue)); mHeartRateMeasurementCharacteristic.setValue(expendedEnergy, EXPENDED_ENERGY_FORMAT, 2); mEditTextEnergyExpended.setText(Integer.toString(expendedEnergy)); }
Source:
public boolean validate() { if (backingFile == null) { getInvalidityReasons().add(constants.uploadImageFileNotExist()); return false; } if (backingFile) { getInvalidityReasons().add(constants.uploadImageBackingFileUnsupported()); return false; } return true; }

Target:
public boolean validate() { if (!Boolean.TRUE.equals(fileLoaded)) { getInvalidityReasons().add(constants.uploadImageFileNotExist()); return false; } if (backingFile) { getInvalidityReasons().add(constants.uploadImageBackingFileUnsupported()); return false; } return true; }
Source:
private String getTopListFeed(OkHttpClient client, String country, int limit) throws IOException { String url = "<LINK_0>"+limit+"/explicit=true/json"; Log.d(LOG, "Feed URL "+String.format(url, country)); Request.Builder httpReq = new Request.Builder() .header("User-Agent", ClientConfig.USER_AGENT) .url(String.format(url, country)); try (Response response = client.newCall(httpReq.build()).execute()) { if (response.isSuccessful()) { return response.body().string(); } String prefix = context.getString(R.string.error_msg_prefix); throw new IOException(prefix + response); } }

Target:
private String getTopListFeed(OkHttpClient client, String country, int limit) throws IOException { String url = "<LINK_0>"+limit+"/explicit=true/json"; Log.d(TAG, "Feed URL " + String.format(url, country)); Request.Builder httpReq = new Request.Builder() .header("User-Agent", ClientConfig.USER_AGENT) .url(String.format(url, country)); try (Response response = client.newCall(httpReq.build()).execute()) { if (response.isSuccessful()) { return response.body().string(); } String prefix = context.getString(R.string.error_msg_prefix); throw new IOException(prefix + response); } }
Source:
private void createParameterNameRow(Composite parent, IWidgetValueProperty textProp) { { Label l = new Label(parent, SWT.NONE); l.setText( Messages.ParameterEditor_Name); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); t.setLayoutData(gd); TextPasteHandler.createFor(t); IEMFEditValueProperty modelProp = EMFEditProperties.value(getEditingDomain(), CommandsPackageImpl.Literals.PARAMETER__NAME); context.bindValue(textProp.observeDelayed(200, t), modelProp.observeDetail(getMaster())); } Button chooseParameterButton = new Button(parent, SWT.PUSH | SWT.FLAT); chooseParameterButton.setText(Messages.ModelTooling_Common_FindEllipsis); chooseParameterButton.setImage(createImage(ResourceProvider.IMG_Obj16_zoom)); chooseParameterButton.addSelectionListener(new ChooseParameterButtonSelectionListener()); chooseParameterButton.setLayoutData(new GridData()); }

Target:
private void createParameterNameRow(Composite parent, IWidgetValueProperty textProp) { { Label commandParameterIdLabel = new Label(parent, SWT.NONE); commandParameterIdLabel.setText(Messages.ParameterEditor_Command_Parameter_ID); commandParameterIdLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text commandParameterIdValue = new Text(parent, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); commandParameterIdValue.setLayoutData(gd); TextPasteHandler.createFor(commandParameterIdValue); IEMFEditValueProperty modelProp = EMFEditProperties.value(getEditingDomain(), CommandsPackageImpl.Literals.PARAMETER__NAME); context.bindValue(textProp.observeDelayed(200, commandParameterIdValue), modelProp.observeDetail(getMaster())); } Button chooseParameterButton = new Button(parent, SWT.PUSH | SWT.FLAT); chooseParameterButton.setText(Messages.ModelTooling_Common_FindEllipsis); chooseParameterButton.setImage(createImage(ResourceProvider.IMG_Obj16_zoom)); chooseParameterButton.addSelectionListener(new ChooseParameterButtonSelectionListener()); chooseParameterButton.setLayoutData(new GridData()); }
Source:
public LogicalPlan load(final String queryId){ final File storedPlanFile = new File(planFolderPath + queryId + ".plan"); try { final DataFileReader<LogicalPlan> dataFileReader = new DataFileReader<LogicalPlan>(storedPlanFile, datumReader); LogicalPlan plan = null; plan = dataFileReader.next(plan); return plan; } catch (final IOException e) { e.printStackTrace(); return null; } }

Target:
public LogicalPlan load(final String queryId) throws IOException { final File storedPlanFile = new File(planStorePath, queryId + ".plan"); final DataFileReader<LogicalPlan> dataFileReader = new DataFileReader<LogicalPlan>(storedPlanFile, datumReader); LogicalPlan plan = null; plan = dataFileReader.next(plan); return plan; }
Source:
private OvfDataUpdater(){ ovfManager = new OvfManager(); proccessedIdsInfo = new LinkedList<Guid>(); proccessedOvfGenerationsInfo = new LinkedList<Long>(); }

Target:
private OvfDataUpdater() { ovfManager = new OvfManager(); }
Source:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { onManualSetup(); return; } final String email = mEmailView.getText().toString(); String[] emailParts = splitEmail(email); String domain = emailParts[1]; mProvider = findProviderForDomain(domain); if (mProvider == null) { new AccountDiscovery().discover(email, new Function1<AccountDiscovery.DiscoveredSettings, Unit>() { @Override public Unit invoke(AccountDiscovery.DiscoveredSettings settings) { if (settings == null) { onManualSetup(); } else { onSetupWithSettings(email, mPasswordView.getText().toString(), settings.getIncoming(), settings.getOutgoing()); } return null; } }); return; } if (mProvider.note != null) { showDialog(DIALOG_NOTE); } else { finishAutoSetup(); } }

Target:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { onManualSetup(); return; } final String email = mEmailView.getText().toString(); new AutoDiscoveryTask().execute(email); }
Source:
public void incompatibleLockFile() throws IOException { File lockFile = new File(realmConfig.getPath() + ".lock"); assertTrue(lockFile.exists()); FileOutputStream fooStream = new FileOutputStream(lockFile, false); fooStream.write("Boom".getBytes()); fooStream.close(); try { DynamicRealm.getInstance(realm.getConfiguration()); fail(); } catch (RealmError e) { assertTrue(e.getMessage().contains("Info size doesn't match")); } finally { lockFile.delete(); } }

Target:
public void incompatibleLockFile() throws IOException { File lockFile = new File(realmConfig.getPath() + ".lock"); assertTrue(lockFile.exists()); FileOutputStream fooStream = new FileOutputStream(lockFile, false); fooStream.write("Boom".getBytes()); fooStream.close(); try { DynamicRealm.getInstance(realm.getConfiguration()); fail(); } catch (RealmError expected) { assertTrue(expected.getMessage().contains("Info size doesn't match")); } finally { lockFile.delete(); } }
Source:
public void clientReset_manualTriggerAllowSessionToRestart() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/~/myrealm"; final AtomicReference<SyncConfiguration> configRef = new AtomicReference<>(null); final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { final ClientResetRequiredError handler = (ClientResetRequiredError) error; looperThread.closeTestRealms(); handler.executeClientReset(); assertFalse(handler.getOriginalFile().exists()); assertTrue(handler.getBackupFile().exists()); looperThread.postRunnable(new Runnable() { @Override public void run() { SyncConfiguration config = configRef.get(); Realm instance = Realm.getInstance(config); looperThread.addTestRealm(instance); try { SyncManager.getSession(config).downloadAllServerChanges(); looperThread.testComplete(); } catch (InterruptedException e) { fail(e.toString()); } } }); } }) .build(); configRef.set(config); Realm realm = Realm.getInstance(config); looperThread.addTestRealm(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }

Target:
public void clientReset_manualTriggerAllowSessionToRestart() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/~/myrealm"; final AtomicReference<SyncConfiguration> configRef = new AtomicReference<>(null); final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { final ClientResetRequiredError handler = (ClientResetRequiredError) error; looperThread.closeTestRealms(); handler.executeClientReset(); looperThread.postRunnable(new Runnable() { @Override public void run() { assertFalse(handler.getOriginalFile().exists()); assertTrue(handler.getBackupFile().exists()); SyncConfiguration config = configRef.get(); Realm instance = Realm.getInstance(config); looperThread.addTestRealm(instance); try { SyncManager.getSession(config).downloadAllServerChanges(); looperThread.testComplete(); } catch (InterruptedException e) { fail(e.toString()); } } }); } }) .build(); configRef.set(config); Realm realm = Realm.getInstance(config); looperThread.addTestRealm(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }
Source:
private static boolean getReadPermission(int permission) { return permission / 4 % 2 == 1; }

Target:
private static boolean getReadPermission(int permission) { return (permission & 4) == 4; }
Source:
private void checkIdentifier(IdentifierTree identifier) { if (identifier.symbol().enclosingClass() != null && identifier.symbol().enclosingClass().type().is("java.lang.System") && identifier.symbolType().is("java.io.InputStream") && identifier.name().equals("in") && !isClosingStream(identifier.parent())) { reportIssue(identifier); } }

Target:
private void checkIdentifier(IdentifierTree identifier) { Symbol.TypeSymbol enclosingClass = identifier.symbol().enclosingClass(); if (enclosingClass != null && enclosingClass.type().is("java.lang.System") && identifier.symbolType().is("java.io.InputStream") && identifier.name().equals("in") && !isClosingStream(identifier.parent())) { reportIssue(identifier); } }
Source:
public boolean isTap() { return this.isTap; }

Target:
public boolean isTap() { return this.tapSource != null; }
Source:
private final Object createValue() { if (getType() == BOOLEAN) { return random.nextBoolean(); } if (getType() == BIGINT) { return random.nextLong(); } if (getType() == INTEGER) { return random.nextInt(); } if (getType() == SMALLINT) { return (short) random.nextInt(); } if (getType() == TINYINT) { return (byte) random.nextInt(); } if (getType() == DATE) { return new SqlDate(random.nextInt()); } if (getType() == TIMESTAMP) { return new SqlTimestamp(random.nextLong(), TimeZoneKey.UTC_KEY); } if (getType() == REAL) { return random.nextFloat(); } if (getType() == DOUBLE) { return random.nextDouble(); } if (getType() instanceof DecimalType) { if (Decimals.isShortDecimal(getType())) { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), SHORT_DECIMAL_TYPE.getPrecision(), SHORT_DECIMAL_TYPE.getScale()); } else { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), LONG_DECIMAL_TYPE.getPrecision(), LONG_DECIMAL_TYPE.getScale()); } } if (getType() == VARCHAR) { if (typeSignature.equals("varchar_dictionary")) { return Strings.repeat("0", MAX_STRING); } return randomAsciiString(random); } throw new UnsupportedOperationException("Unsupported type: " + getType()); }

Target:
private final Object createValue() { if (getType() == BOOLEAN) { return random.nextBoolean(); } if (getType() == BIGINT) { return random.nextLong(); } if (getType() == INTEGER) { return random.nextInt(); } if (getType() == SMALLINT) { return (short) random.nextInt(); } if (getType() == TINYINT) { return (byte) random.nextInt(); } if (getType() == DATE) { return new SqlDate(random.nextInt()); } if (getType() == TIMESTAMP) { return new SqlTimestamp(random.nextLong(), TimeZoneKey.UTC_KEY); } if (getType() == REAL) { return random.nextFloat(); } if (getType() == DOUBLE) { return random.nextDouble(); } if (getType() instanceof DecimalType) { if (Decimals.isShortDecimal(getType())) { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), SHORT_DECIMAL_TYPE.getPrecision(), SHORT_DECIMAL_TYPE.getScale()); } else { return new SqlDecimal(BigInteger.valueOf(random.nextLong() % 10_000_000_000L), LONG_DECIMAL_TYPE.getPrecision(), LONG_DECIMAL_TYPE.getScale()); } } if (getType() == VARCHAR) { if (typeSignature.equals("varchar_dictionary")) { return Strings.repeat("0", MAX_STRING_LENGTH); } return randomAsciiString(random, MAX_STRING_LENGTH); } throw new UnsupportedOperationException("Unsupported type: " + getType()); }
Source:
public void testReplicationFailure() throws Exception { Cache<?, ?> cache = cache(0); ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(cache); Future<Void> future = fork(() -> { controlledRpcManager.expectCommand(VersionedPrepareCommand.class).fail(); controlledRpcManager.expectCommand(RollbackCommand.class).send().receiveAll(); }); try { TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); cache(0).put("k0", "v"); Exceptions.expectException(RollbackException.class, tm::commit); } finally { future.get(30, TimeUnit.SECONDS); controlledRpcManager.revertRpcManager(); } }

Target:
public void testReplicationFailure() throws Exception { Cache<?, ?> cache = cache(0); ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(cache); try { Future<Void> future = fork(() -> { controlledRpcManager.expectCommand(VersionedPrepareCommand.class).fail(); controlledRpcManager.expectCommand(RollbackCommand.class).send().receiveAll(); }); TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); cache(0).put("k0", "v"); Exceptions.expectException(RollbackException.class, tm::commit); future.get(30, TimeUnit.SECONDS); } finally { controlledRpcManager.revertRpcManager(); } }
Source:
private AppiumDriver getDriverSafe() { WebDriver driver = getDriver(); if (driver instanceof EventFiringWebDriver) { driver = ((EventFiringWebDriver) driver).getWrappedDriver(); if (driver instanceof AppiumDriver) { return (AppiumDriver) driver; } } throw new ClassCastException("Appium Driver can not be casted from the actual driver."); }

Target:
private WebDriver getDriverSafe() { WebDriver driver = getDriver(); if (driver instanceof EventFiringWebDriver) { driver = ((EventFiringWebDriver) driver).getWrappedDriver(); } return driver; }
Source:
public static ConfigParser parse() { LOGGER.entering(); if (parser == null) { parser = new ConfigParser(); } LOGGER.exiting(parser.toString()); return parser; }

Target:
public static ConfigParser parse() { LOGGER.entering(); if (configuration == null) { try { readConfigFileContents(); } catch (IOException e) { throw new ConfigParserException(e); } } LOGGER.exiting(parser.toString()); return parser; }
Source:
protected void dropCycle(Integer cycle) { WireStore store = queue.storeForCycle(cycle, queue.epoch(), false); if (store == null) { return; } File file = store.file(); if (file == null || !file.exists()) { return; } log.info("Deleting Chronicle file: according to retention: {}", file::getAbsolutePath, () -> retention); try { queue.release(store); if (IS_WIN) { try { Thread.sleep(1000); } catch (InterruptedException ie) } Files.delete(file.toPath()); queue.refreshDirectlyListing(); log.debug(file + " deleted"); } catch (IOException | SecurityException e) { log.warn("Unable to delete Chronicle file: {}, {}", file::getAbsolutePath, e::getMessage); } }

Target:
protected void dropCycle(Integer cycle) { WireStore store = queue.storeForCycle(cycle, queue.epoch(), false); if (store == null) { return; } File file = store.file(); if (file == null || !file.exists()) { return; } log.info("Deleting Chronicle file: according to retention: {}", file::getAbsolutePath, () -> retention); try { queue.release(store); if (IS_WIN) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } Files.delete(file.toPath()); queue.refreshDirectlyListing(); log.debug(file + " deleted"); } catch (IOException | SecurityException e) { log.warn("Unable to delete Chronicle file: {}, {}", file::getAbsolutePath, e::getMessage); } }
Source:
private void launchWithNoteId() { if (isFinishing() || getIntent() == null) return; if (getIntent().hasExtra(NotificationsUtils.ARG_PUSH_AUTH_TOKEN)) { Bundle extras = getIntent().getExtras(); String token = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_TOKEN, ""); String title = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_TITLE, ""); String message = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_MESSAGE, ""); long expires = extras.getLong(NotificationsUtils.ARG_PUSH_AUTH_EXPIRES, 0); long now = System.currentTimeMillis() / 1000; if (expires > 0 && now > expires) { ToastUtils.showToast(this, R.string.push_auth_expired, ToastUtils.Duration.LONG); AnalyticsTracker.track(AnalyticsTracker.Stat.PUSH_AUTHENTICATION_EXPIRED); } else { NotificationsUtils.showPushAuthAlert(this, token, title, message); } } mViewPager.setCurrentItem(WPMainTabAdapter.TAB_NOTIFS); boolean shouldShowKeyboard = getIntent().getBooleanExtra(NotificationsListFragment.NOTE_INSTANT_REPLY_EXTRA, false); if (GCMIntentService.getNotificationsMap().size() == 1) { String noteId = getIntent().getStringExtra(NotificationsListFragment.NOTE_ID_EXTRA); if (!TextUtils.isEmpty(noteId)) { NotificationsListFragment.openNote(this, noteId, shouldShowKeyboard, false); } } GCMIntentService.clearNotificationsMap(); }

Target:
private void launchWithNoteId() { if (isFinishing() || getIntent() == null) return; if (getIntent().hasExtra(NotificationsUtils.ARG_PUSH_AUTH_TOKEN)) { Bundle extras = getIntent().getExtras(); String token = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_TOKEN, ""); String title = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_TITLE, ""); String message = extras.getString(NotificationsUtils.ARG_PUSH_AUTH_MESSAGE, ""); long expires = extras.getLong(NotificationsUtils.ARG_PUSH_AUTH_EXPIRES, 0); long now = System.currentTimeMillis() / 1000; if (expires > 0 && now > expires) { ToastUtils.showToast(this, R.string.push_auth_expired, ToastUtils.Duration.LONG); AnalyticsTracker.track(AnalyticsTracker.Stat.PUSH_AUTHENTICATION_EXPIRED); } else { NotificationsUtils.showPushAuthAlert(this, token, title, message); } } mViewPager.setCurrentItem(WPMainTabAdapter.TAB_NOTIFS); boolean shouldShowKeyboard = getIntent().getBooleanExtra(NotificationsListFragment.NOTE_INSTANT_REPLY_EXTRA, false); if (GCMIntentService.getNotificationsCount() == 1) { String noteId = getIntent().getStringExtra(NotificationsListFragment.NOTE_ID_EXTRA); if (!TextUtils.isEmpty(noteId)) { NotificationsListFragment.openNote(this, noteId, shouldShowKeyboard, false); } } GCMIntentService.clearNotifications(); }
Source:
private synchronized void addSockets(int numberOfNewSocket) { int n = numberOfNewSocket; if (n > activeFactories.holder.size()) { n = activeFactories.holder.size(); logger.debug("addSockets({}) restricted by the number of factories, i.e. addSockets({})", numberOfNewSocket, n); } Random rng = ThreadLocalRandom.current(); while (n > 0) { int size = activeFactories.holder.size(); if (size == 1) { ReactiveSocketClient factory = activeFactories.holder.get(0); if (factory.availability() > 0.0) { activeFactories.remove(0); pendingSockets++; factory.connect().subscribe(new SocketAdder(factory)); } break; } ReactiveSocketClient factory0 = null; ReactiveSocketClient factory1 = null; int i0 = 0; int i1 = 0; for (int i = 0; i < EFFORT; i++) { i0 = rng.nextInt(size); i1 = rng.nextInt(size - 1); if (i1 >= i0) { i1++; } factory0 = activeFactories.holder.get(i0); factory1 = activeFactories.holder.get(i1); if (factory0.availability() > 0.0 && factory1.availability() > 0.0) { break; } } if (factory0.availability() < factory1.availability()) { n--; pendingSockets++; if (i1 < size - 1) { activeFactories.set(i1, activeFactories.holder.get(size - 1)); } activeFactories.remove(size - 1); factory1.connect().subscribe(new SocketAdder(factory1)); } else { n--; pendingSockets++; if (i0 < size - 1) { activeFactories.set(i0, activeFactories.holder.get(size - 1)); } activeFactories.remove(size - 1); factory0.connect().subscribe(new SocketAdder(factory0)); } } }

Target:
private synchronized void addSockets(int numberOfNewSocket) { int n = numberOfNewSocket; if (n > activeFactories.size()) { n = activeFactories.size(); logger.debug("addSockets({}) restricted by the number of factories, i.e. addSockets({})", numberOfNewSocket, n); } Random rng = ThreadLocalRandom.current(); while (n > 0) { int size = activeFactories.size(); if (size == 1) { ReactiveSocketClient factory = activeFactories.holder.get(0); if (factory.availability() > 0.0) { activeFactories.remove(0); pendingSockets++; factory.connect().subscribe(new SocketAdder(factory)); } break; } ReactiveSocketClient factory0 = null; ReactiveSocketClient factory1 = null; int i0 = 0; int i1 = 0; for (int i = 0; i < EFFORT; i++) { i0 = rng.nextInt(size); i1 = rng.nextInt(size - 1); if (i1 >= i0) { i1++; } factory0 = activeFactories.holder.get(i0); factory1 = activeFactories.holder.get(i1); if (factory0.availability() > 0.0 && factory1.availability() > 0.0) { break; } } if (factory0.availability() < factory1.availability()) { n--; pendingSockets++; if (i1 < size - 1) { activeFactories.set(i1, activeFactories.holder.get(size - 1)); } activeFactories.remove(size - 1); factory1.connect().subscribe(new SocketAdder(factory1)); } else { n--; pendingSockets++; if (i0 < size - 1) { activeFactories.set(i0, activeFactories.holder.get(size - 1)); } activeFactories.remove(size - 1); factory0.connect().subscribe(new SocketAdder(factory0)); } } }