auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void sendsConfirmationEmail() throws Exception { final Postman postman = Mockito.mock(Postman.class); final Alias alias = new EmAlias(new MkBase().randomAlias(), postman); alias.email("mihai@test.com", "netbout.com/test/verification/link"); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getFrom().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo("Netbout email verification") ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.containsString("mihai@test") ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); final String content = new String(baos.toByteArray()); MatcherAssert.assertThat( content, Matchers.containsString( "<p>Hi,<br />Your notification e-mail address" ) ); MatcherAssert.assertThat( content, Matchers.containsString( "<a href=\"netbout.com/test/verification/link\">here</a>" ) ); }

Target:
public void sendsConfirmationEmail() throws Exception { final Postman postman = Mockito.mock(Postman.class); final Alias alias = new EmAlias(new MkBase().randomAlias(), postman); alias.email("mihai@test.com", "netbout.com/test/verification/link"); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getFrom().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo("Netbout email verification") ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.containsString("mihai@test") ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); final String content = new String(baos.toByteArray(), "UTF-8"); MatcherAssert.assertThat( content, Matchers.containsString( "<p>Hi,<br />Your notification e-mail address" ) ); MatcherAssert.assertThat( content, Matchers.containsString( "<a href=\"netbout.com/test/verification/link\">here</a>" ) ); }
Source:
private void setCompression(String compression) throws StandardException { if (compression != null) { compression = compression.trim().toUpperCase(); } if (compression != null && compression.length() > 0) { if (compression.compareTo("BZ2") == 0 || compression.compareTo("BZIP2") == 0) { this.compression = COMPRESSION.BZ2; } else if (compression.compareTo("GZ") == 0 || compression.compareTo("GZIP") == 0) { this.compression = COMPRESSION.GZ; } else if (compression.compareTo("NONE") == 0) { this.compression = COMPRESSION.NONE; } else { throw StandardException.newException(SQLState.UNSUPPORTED_COMPRESSION_FORMAT, compression); } } else { this.compression = COMPRESSION.NONE; } }

Target:
private void setCompression(String compression) throws StandardException { if (compression != null) { compression = compression.trim().toUpperCase(); } if (compression!= null && compression.length() > 0) { String f = format.trim().toUpperCase(); if (f.compareTo("PARQUET") == 0) { if (compression.compareTo("SNAPPY") == 0 || compression.compareTo("TRUE") == 0) { this.compression = COMPRESSION.SNAPPY; } else if (compression.compareTo("NONE") == 0 || compression.compareTo("FALSE") == 0) { this.compression = COMPRESSION.NONE; } else throw StandardException.newException(SQLState.UNSUPPORTED_COMPRESSION_FORMAT, compression); } else if (f.compareTo("CSV") == 0) { if (compression.compareTo("BZ2") == 0 || compression.compareTo("BZIP2") == 0) { this.compression = COMPRESSION.BZ2; } else if (compression.compareTo("GZ") == 0 || compression.compareTo("GZIP") == 0 || compression.compareTo("TRUE") == 0) { this.compression = COMPRESSION.GZ; } else if (compression.compareTo("NONE") == 0 || compression.compareTo("FALSE") == 0) { this.compression = COMPRESSION.NONE; } else throw StandardException.newException(SQLState.UNSUPPORTED_COMPRESSION_FORMAT, compression); } } else this.compression = COMPRESSION.NONE; }
Source:
private void setValues(Properties properties) { String cacheLevel = properties.getProperty(JMSConstants.PARAM_CACHE_LEVEL); if (null != cacheLevel && !"".equals(cacheLevel)) { this.cacheLevel = Integer.parseInt(cacheLevel); } else { this.cacheLevel = JMSConstants.CACHE_NONE; } }

Target:
private void setValues(Properties properties) { String cacheLevel = properties.getProperty(JMSConstants.PARAM_CACHE_LEVEL); if (null != cacheLevel && !cacheLevel.isEmpty()) { this.cacheLevel = Integer.parseInt(cacheLevel); } else { this.cacheLevel = JMSConstants.CACHE_NONE; } }
Source:
public void validateThatRemoveIsCalledOnTombstoneInRegionThatIsInitialized() { RegionVersionVector regionVersionVector = mock(RegionVersionVector.class); when(region.isInitialized()).thenReturn(true); when(region.getRegionMap()).thenReturn(regionMap); when(region.getVersionVector()).thenReturn(regionVersionVector); when(region.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_REPLICATE); when(region.getDiskRegion()).thenReturn(mock(DiskRegion.class)); TombstoneService.ReplicateTombstoneSweeper replicateTombstoneSweeper = new TombstoneService.ReplicateTombstoneSweeper(cacheTime, stats, cancelCriterion, executor); TombstoneService.Tombstone tombstone = new TombstoneService.Tombstone(entry, region, destroyedVersion); tombstone.entry = entry; replicateTombstoneSweeper.expireTombstone(tombstone); replicateTombstoneSweeper.expireBatch(); verify(region, Mockito.atLeastOnce()).getVersionVector(); verify(regionVersionVector, Mockito.atLeastOnce()).recordGCVersion(tombstone.getMemberID(), tombstone.getRegionVersion()); }

Target:
public void validateThatRemoveIsCalledOnTombstoneInRegionThatIsInitialized() { RegionVersionVector regionVersionVector = mock(RegionVersionVector.class); when(region.isInitialized()).thenReturn(true); when(region.getRegionMap()).thenReturn(regionMap); when(region.getVersionVector()).thenReturn(regionVersionVector); when(region.getDataPolicy()).thenReturn(DataPolicy.PERSISTENT_REPLICATE); when(region.getDiskRegion()).thenReturn(mock(DiskRegion.class)); replicateTombstoneSweeper.expireTombstone(tombstone); replicateTombstoneSweeper.expireBatch(); verify(regionMap, Mockito.times(1)).removeTombstone(tombstone.entry, tombstone, false, true); }
Source:
public static final Component[] filterOutShadows(Component[] shadows) { if (shadows == null || shadows.length == 0) return shadows; int length = shadows.length; doBindChildrenInFilter(shadows); if (length == 1) { if (shadows[0] instanceof ShadowElement) { ShadowElement se = ((ShadowElement) shadows[0]); return se.getDistributedChildren().toArray(new Component[0]); } } else { Component parent = null; Component start = null; if (shadows[0] instanceof ShadowElementCtrl) { ShadowElementCtrl se = ((ShadowElementCtrl) shadows[0]); start = se.getFirstInsertion(); } else { start = shadows[0]; parent = start.getParent(); } if (parent instanceof ComponentCtrl) { ComponentCtrl pCtrl = (ComponentCtrl) parent; if (pCtrl.getShadowRoots().isEmpty()) return shadows; } LinkedList<Component> list = new LinkedList<Component>(); for (Component comp : shadows) { if (comp instanceof HtmlShadowElement) { HtmlShadowElement hse = (HtmlShadowElement) comp; list.addAll(hse.getDistributedChildren()); } else { list.add(comp); } } return list.toArray(new Component[0]); } return shadows; }

Target:
public static final Component[] filterOutShadows(Component[] shadows) { if (shadows == null || shadows.length == 0) return shadows; int length = shadows.length; doBindChildrenInFilter(shadows); if (length == 1) { if (shadows[0] instanceof ShadowElement) { ShadowElement se = ((ShadowElement) shadows[0]); return se.getDistributedChildren().toArray(new Component[0]); } } else { Component parent = null; if (!(shadows[0] instanceof ShadowElementCtrl)) { parent = shadows[0].getParent(); } if (parent instanceof ComponentCtrl) { ComponentCtrl pCtrl = (ComponentCtrl) parent; if (pCtrl.getShadowRoots().isEmpty()) return shadows; } LinkedList<Component> list = new LinkedList<Component>(); for (Component comp : shadows) { if (comp instanceof HtmlShadowElement) { HtmlShadowElement hse = (HtmlShadowElement) comp; list.addAll(hse.getDistributedChildren()); } else { list.add(comp); } } return list.toArray(new Component[0]); } return shadows; }
Source:
public void verifyPinNotExist(String pinTitle) { Integer pinSize = pinCollection.size() - 1; while (pinSize >= 0) { if (pinCollection.get(pinSize).getText().contains(pinTitle)) { break; } pinSize--; } Assertion.assertEquals(pinSize.intValue(), -1, "Pin was deleted correctly"); }

Target:
public void verifyPinNotExist(String pinTitle) { int pinSize = pinCollection.size() - 1; while (pinSize >= 0) { if (pinCollection.get(pinSize).getText().contains(pinTitle)) { break; } pinSize--; } Assertion.assertEquals(pinSize, -1, "Pin was deleted correctly"); }
Source:
public static int checkAccountExist(String email) { int rv = 0; try { Xclient = new XmlRpcClient(); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL(friendUrl)); Xclient.setTransportFactory(new XmlRpcSun15HttpTransportFactory(Xclient)); Xclient.setConfig(config); Object[] params = new Object[]{new String[] {email}}; Object[] results = (Object[]) Xclient.execute("doAccountsExist", params); if (results != null && results.length == 1) { rv = ((Integer) results[0]).intValue(); } } catch (Exception e) { M_log.warn("Friend checkAccountExist(): email address " + email + " " + e.getMessage()); e.printStackTrace(); } return rv; }

Target:
public CheckAccountExistsResponse checkAccountExist(String email) { M_log.debug("Friend checkAccountExists() called"); CheckAccountExistsResponse response = CheckAccountExistsResponse.FRIEND_ACCOUNT_DOES_NOT_EXIST; int rv = 0; try { Object[] params = new Object[]{new String[] {email}}; Object[] results = (Object[]) Xclient.execute(DO_ACCOUNT_EXIST_WS, params); if (results != null && results.length == 1) { rv = ((Integer) results[0]).intValue(); } } catch (Exception e) { M_log.warn("Friend checkAccountExist(): email address " + email + " " + e.getMessage()); } if(rv == -1){ response = CheckAccountExistsResponse.INVALID_EMAIL; } if(rv == 0){ response = CheckAccountExistsResponse.FRIEND_ACCOUNT_DOES_NOT_EXIST; } if(rv == 1){ response = CheckAccountExistsResponse.FRIEND_ACCOUNT_ALREADY_EXISTS; } return response; }
Source:
public Map<String, String> toNormalizedQueryMap() { Map<String, String> query = Maps.newTreeMap(); for (Map.Entry<String, Predicate> entry : constraints.entrySet()) { String name = entry.getKey(); Schema fieldSchema = SchemaUtil.fieldSchema(schema, strategy, name); query.put(name, Predicates.toNormalizedString(entry.getValue(), fieldSchema)); } return query; }

Target:
public Map<String, String> toNormalizedQueryMap() { Map<String, String> query = Maps.newTreeMap(); return toQueryMap(query, true); }
Source:
protected void addVmNumaNodes() { List<VmNumaNode> vmList = DbFacade.getInstance().getVmNumaNodeDAO().getAllVmNumaNodeByVmId(getVmId()); if (vmList != null && vmList.size() > 0) { List<VmNumaNode> templateList = new ArrayList<>(); for (VmNumaNode vnode : vmList) { List<Pair<Guid, Pair<Boolean, Integer>>> pairs = vnode.getVdsNumaNodeList(); if (pairs != null && pairs.size() > 0) { for (Pair<Guid, Pair<Boolean, Integer>> pair : pairs) { pair.setFirst(null); pair.getSecond().setFirst(false); } } templateList.add(vnode); } VmNumaNodeOperationParameters params = new VmNumaNodeOperationParameters(getVmTemplateId(), templateList); getBackend().runInternalAction(VdcActionType.AddVmNumaNodes, params); } }

Target:
protected void addVmNumaNodes() { List<VmNumaNode> vmNumaList = DbFacade.getInstance().getVmNumaNodeDAO().getAllVmNumaNodeByVmId(getVmId()); if (vmNumaList != null && vmNumaList.size() > 0) { List<VmNumaNode> templateList = new ArrayList<>(); for (VmNumaNode vnode : vmNumaList) { List<Pair<Guid, Pair<Boolean, Integer>>> pairs = vnode.getVdsNumaNodeList(); if (pairs != null && pairs.size() > 0) { for (Pair<Guid, Pair<Boolean, Integer>> pair : pairs) { pair.setFirst(null); } } templateList.add(vnode); } VmNumaNodeOperationParameters params = new VmNumaNodeOperationParameters(getVmTemplateId(), templateList); getBackend().runInternalAction(VdcActionType.AddVmNumaNodes, params); } }
Source:
private boolean buildingPlowThroughRequired(Entity entity, MovementType relevantMovementType, Coords coords) { IBoard board = entity.getGame().getBoard(); IHex hex = board.getHex(coords); if (!hex.containsTerrain(Terrains.BLDG_CF) && !hex.containsExit(Terrains.FUEL_TANK_CF)) { return false; } else if (relevantMovementType == MovementType.Walker) { int buildingCF = board.getBuildingAt(coords).getCurrentCF(coords); return entity.getWeight() > buildingCF; } else if (relevantMovementType != MovementType.Flyer && relevantMovementType != MovementType.Jump && relevantMovementType != MovementType.None && relevantMovementType != MovementType.Water) { return true; } else { return false; } }

Target:
private boolean buildingPlowThroughRequired(Entity entity, MovementType relevantMovementType, Coords coords) { IBoard board = entity.getGame().getBoard(); IHex hex = board.getHex(coords); if (!hex.containsTerrain(Terrains.BLDG_CF) && !hex.containsExit(Terrains.FUEL_TANK_CF)) { return false; } else if (relevantMovementType == MovementType.Walker) { int buildingCF = board.getBuildingAt(coords).getCurrentCF(coords); return entity.getWeight() > buildingCF; } else if ((relevantMovementType != MovementType.Flyer) && (relevantMovementType != MovementType.Jump) && (relevantMovementType != MovementType.None) && (relevantMovementType != MovementType.Water)) { return true; } else { return false; } }
Source:
protected boolean isSafeMethod(String method) { return GET.equals(method) || HEAD.equals(method) || OPTIONS.equals(method) || TRACE.equals(method); }

Target:
protected boolean isSafeMethod(String method) { return SAFE_METHODS.contains(method); }
Source:
protected abstract void test() throws IOException; public void runTest() { try { final File input = createInputFile(); output = new File(outputDir, "output.sam"); args.add("INPUT=" + input.getAbsoluteFile()); args.add("OUTPUT=" + output.getAbsoluteFile()); Assert.assertEquals(runPicardCommandLine(args), 0); test(); } catch (IOException ex) { ex.printStackTrace(); } }

Target:
protected abstract void test() throws IOException; public void runTest() { try { final File input = createInputFile(); output = new File(outputDir, "output.sam"); args.add("INPUT=" + input.getAbsoluteFile()); args.add("OUTPUT=" + output.getAbsoluteFile()); Assert.assertEquals(runPicardCommandLine(args), 0); test(); } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { IFD ifd = new IFD(); if (!sequential) { TiffParser parser = new TiffParser(currentId); try { long[] ifdOffsets = parser.getIFDOffsets(); if (no < ifdOffsets.length) { ifd = parser.getIFD(ifdOffsets[no]); } saveBytes(no, buf, ifd, x, y, w, h); } finally { RandomAccessInputStream tiffParserStream = parser.getStream(); if (tiffParserStream != null) { tiffParserStream.close(); } } } }

Target:
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { IFD ifd = new IFD(); if (!sequential) { TiffParser parser = new TiffParser(currentId); try { long[] ifdOffsets = parser.getIFDOffsets(); if (no < ifdOffsets.length) { ifd = parser.getIFD(ifdOffsets[no]); } saveBytes(no, buf, ifd, x, y, w, h); } finally { RandomAccessInputStream tiffParserStream = parser.getStream(); if (tiffParserStream != null) { tiffParserStream.close(); } } } else { saveBytes(no, buf, ifd, x, y, w, h); } }
Source:
public void changePasswordAsync_nonLooperThreadThrows() { SyncUser user = createTestUser(); thrown.expect(IllegalArgumentException.class); user.changePasswordAsync(null, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { fail(); } }); }

Target:
public void changePasswordAsync_nonLooperThreadThrows() { SyncUser user = createTestUser(); thrown.expect(IllegalStateException.class); user.changePasswordAsync(null, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { fail(); } }); }
Source:
char[] getExplorerTheme() { String enableDarkScrollBar = System.getProperty("org.eclipse.swt.internal.win32.enableDarkScrollbars"); if (enableDarkScrollBar != null && Boolean.valueOf(enableDarkScrollBar)) { return DARKMODE_EXPLORER; } return EXPLORER; }

Target:
char[] getExplorerTheme() { String enableDarkScrollBar = System.getProperty(ENABLE_DARK_SCROLLBARS); if (enableDarkScrollBar != null && Boolean.valueOf(enableDarkScrollBar)) { return DARKMODE_EXPLORER; } return EXPLORER; }
Source:
private boolean parseCustomFormat(Object customFormat) { if (customFormat == null) { return false; } if (customFormat instanceof Boolean) { return (Boolean) customFormat; } if (customFormat instanceof String) { return Boolean.parseBoolean((String) customFormat); } throw new RuntimeException("Unexpected customFormat in property file."); }

Target:
private boolean parseCustomFormat(Object customFormat) { if (customFormat == null) { return false; } if (customFormat instanceof Boolean) { return (Boolean) customFormat; } if (customFormat instanceof String) { return Boolean.parseBoolean((String) customFormat); } throw new RuntimeException("Unexpected customFormat in property file: " + customFormat); }
Source:
public void testDisabledByDefault() throws Exception { DisabledBaseTargetPreparer preparer = new DisabledBaseTargetPreparer(); assertTrue(preparer.isDisabled()); IConfiguration config = new Configuration("test", "test"); config.setTargetPreparer(preparer); File configFile = FileUtil.createTempFile("base-target-prep-config", ".xml"); try (PrintWriter pw = new PrintWriter(configFile)) { config.dumpXml(pw, new ArrayList<>(), false, true); String value = FileUtil.readStringFromFile(configFile); CLog.e("%s", value); assertTrue(value.contains("<option name=\"disable\" value=\"true\" />")); assertTrue(value.contains("<option name=\"disable-tear-down\" value=\"false\" />")); } finally { FileUtil.deleteFile(configFile); } }

Target:
public void testDisabledByDefault() throws Exception { DisabledBaseTargetPreparer preparer = new DisabledBaseTargetPreparer(); assertTrue(preparer.isDisabled()); IConfiguration config = new Configuration("test", "test"); config.setTargetPreparer(preparer); File configFile = FileUtil.createTempFile("base-target-prep-config", ".xml"); try (PrintWriter pw = new PrintWriter(configFile)) { config.dumpXml(pw, new ArrayList<>(), false, true); String value = FileUtil.readStringFromFile(configFile); assertTrue(value.contains("<option name=\"disable\" value=\"true\" />")); assertTrue(value.contains("<option name=\"disable-tear-down\" value=\"false\" />")); } finally { FileUtil.deleteFile(configFile); } }
Source:
public Range setCellValue(final int rowIndex, final int columnIndex, final GridCellValue<?> value) { return doSetCell(rowIndex, columnIndex, (p) -> { final Optional<BaseGridCell> cell = Optional.ofNullable((BaseGridCell) getCell(p.getK1(), p.getK2())); final BaseGridCell c = cell.orElse(new BaseGridCell<>(value)); c.setValue(value); return c; }); }

Target:
public Range setCellValue(final int rowIndex, final int columnIndex, final GridCellValue<?> value) { return doSetCell(rowIndex, columnIndex, (pair) -> { final Optional<BaseGridCell> cell = Optional.ofNullable((BaseGridCell) getCell(pair.getK1(), pair.getK2())); final BaseGridCell c = cell.orElse(new BaseGridCell<>(value)); c.setValue(value); return c; }); }
Source:
private BayeuxClient makeClient() throws Exception { httpClient.setConnectTimeout(connectionTimeout); httpClient.setTimeout(readTimeout); httpClient.start(); SoapLoginUtil.login(httpClient, userName, password); final String sessionId = SoapLoginUtil.getSessionId(); String endpoint = SoapLoginUtil.getEndpoint(); log.info("Login successful! to Salesforce Streaming Endpoint: " + endpoint); Map<String, Object> options = new HashMap<String, Object>(); options.put(ClientTransport.TIMEOUT_OPTION, readTimeout); LongPollingTransport transport = new LongPollingTransport(options, httpClient) { @Override protected void customize(ContentExchange exchange) { super.customize(exchange); exchange.addRequestHeader("Authorization", "OAuth " + sessionId); } }; BayeuxClient client = new BayeuxClient(salesforceStreamingEndpoint(endpoint), transport); if (useCookies) establishCookies(client, userName, sessionId); return client; }

Target:
private BayeuxClient makeClient() throws MalformedURLException { httpClient.setConnectTimeout(connectionTimeout); httpClient.setTimeout(readTimeout); try { httpClient.start(); SoapLoginUtil.login(httpClient, userName, password); final String sessionId = SoapLoginUtil.getSessionId(); String endpoint = SoapLoginUtil.getEndpoint(); log.info("Login to Salesforce Streaming Endpoint: " + endpoint); Map<String, Object> options = new HashMap<String, Object>(); options.put(ClientTransport.TIMEOUT_OPTION, readTimeout); LongPollingTransport transport = new LongPollingTransport(options, httpClient) { @Override protected void customize(ContentExchange exchange) { super.customize(exchange); exchange.addRequestHeader("Authorization", "OAuth " + sessionId); } }; BayeuxClient client = new BayeuxClient(salesforceStreamingEndpoint(endpoint), transport); if (useCookies) establishCookies(client, userName, sessionId); return client; } catch (MalformedURLException e) { handleException("Error while building URL: " + e.getMessage(), e); } catch (Exception e) { handleException("Error while starting the Http Client" + e.getMessage(), e); } return null; }
Source:
protected TaskProcessingTask( TaskStore taskStore, TaskProcessor processor, DestinationType destinationType, TelescopeReporterName reporterName ) { this.taskStore = checkNotNull(taskStore); this.processor = checkNotNull(processor); this.destinationType = checkNotNull(destinationType); this.telescope = FeedsTelescopeReporterFactory.getInstance() .getTelescopeReporter(reporterName); }

Target:
TaskProcessingTask( TaskStore taskStore, TaskProcessor processor, DestinationType destinationType, TelescopeReporterName reporterName ) { this( taskStore, processor, destinationType, FeedsTelescopeReporterFactory.getInstance().getTelescopeReporter(reporterName) ); }
Source:
public static String getMessage(final String key, final Locale locale) { String result = ""; if (key != null && key.startsWith(BRAND_PREFIX + ".")) { String[] splitString = key.split("\\."); String prefix = null; if (splitString.length >= 2) { prefix = key.split("\\.")[1]; } if (prefix != null && prefix.length() > 0) { result = getInstance().getMessageMap(prefix, locale). get(key.substring(key.indexOf(prefix) + prefix.length() + 1)); } } return result; }

Target:
public String getMessage(final String key, final Locale locale) { String result = ""; if (key != null && key.startsWith(BRAND_PREFIX + ".")) { String[] splitString = key.split("\\."); String prefix = (splitString.length >= 2) ? splitString[1] : ""; if (prefix.length() > 0) { result = getMessageMap(prefix, locale).get(key.substring(key.indexOf(prefix) + prefix.length() + 1)); } } return result; }
Source:
public Number nextValue(NextValueRequest request) { if ( returnTheInitialValue.compareAndSet( true, false ) ) { return request.getInitialValue(); } try { return counter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { throw new HibernateException( "Interrupting Operation " + e.getMessage(), e ); } }

Target:
public Number nextValue(NextValueRequest request) { if ( returnTheInitialValue.compareAndSet( true, false ) ) { return request.getInitialValue(); } try { return counter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { LOG.exceptionGeneratingValueForCounter( counter.getName() ); return null; } }
Source:
private void populateNestedPositions(ColumnarArray columnarArray) { valuesBuffers.resetPositions(); if (positionCount == 0) { return; } offsets = ensureCapacity(offsets, positionCount + 1, SMALL, NONE, bufferAllocator); offsets[0] = 0; int[] positions = getPositions(); for (int i = 0; i < positionCount; i++) { offsets[i + 1] = offsets[i] + columnarArray.getLength(positions[i]); } valuesBuffers.setPositions(ensureCapacity(valuesBuffers.getPositions(), offsets[positionCount], SMALL, NONE, bufferAllocator)); for (int i = 0; i < positionCount; i++) { valuesBuffers.appendPositionRange(columnarArray.getOffset(positions[i]), offsets[i + 1] - offsets[i]); } }

Target:
private void populateNestedPositions(ColumnarArray columnarArray) { valuesBuffers.resetPositions(); if (positionCount == 0) { return; } offsets = ensureCapacity(offsets, positionCount + 1, SMALL, NONE, bufferAllocator); offsets[0] = 0; int[] positions = getPositions(); for (int i = 0; i < positionCount; i++) { offsets[i + 1] = offsets[i] + columnarArray.getLength(positions[i]); } valuesBuffers.ensurePositionsCapacity(offsets[positionCount]); for (int i = 0; i < positionCount; i++) { valuesBuffers.appendPositionRange(columnarArray.getOffset(positions[i]), offsets[i + 1] - offsets[i]); } }
Source:
public Map<String, Set<String>> readPluginsStorages() { log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storages for plugin '{}'", pluginId); final Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = ((PluginClassLoader) plugin.getPluginClassLoader()).findResources(getExtensionsResource()); if (urls == null || !urls.hasMoreElements()) { log.debug("Cannot find '{}'", getExtensionsResource()); } else { while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (url != null) { Path extensionPath; if (url.toURI().getScheme().equals("jar")) { extensionPath = FileUtils.getPath(url.toURI(), getExtensionsResource()); } else { extensionPath = Paths.get(url.toURI()); } bucket.addAll(readExtensions(extensionPath)); } else { log.debug("Cannot find '{}'", getExtensionsResource()); } } } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException | URISyntaxException e) { log.error(e.getMessage(), e); } } return result; }

Target:
public Map<String, Set<String>> readPluginsStorages() { log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storages for plugin '{}'", pluginId); final Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = ((PluginClassLoader) plugin.getPluginClassLoader()).findResources(getExtensionsResource()); if (urls == null || !urls.hasMoreElements()) { log.debug("Cannot find '{}'", getExtensionsResource()); } else { while (urls.hasMoreElements()) { URL url = urls.nextElement(); Path extensionPath; if (url.toURI().getScheme().equals("jar")) { extensionPath = FileUtils.getPath(url.toURI(), getExtensionsResource()); } else { extensionPath = Paths.get(url.toURI()); } bucket.addAll(readExtensions(extensionPath)); } } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException | URISyntaxException e) { log.error(e.getMessage(), e); } } return result; }
Source:
long getTotalBufferedSize() { long bloomBufferSize = bloomFilter == null ? 0 : bloomFilter.getBitsetSize(); return repetitionLevelColumn.getBufferedSize() + definitionLevelColumn.getBufferedSize() + dataColumn.getBufferedSize() + pageWriter.getMemSize() + bloomBufferSize; }

Target:
long getTotalBufferedSize() { return repetitionLevelColumn.getBufferedSize() + definitionLevelColumn.getBufferedSize() + dataColumn.getBufferedSize() + pageWriter.getMemSize(); }
Source:
private static void updateRequiredPlugins(IJavaProject javaProject, IProgressMonitor monitor, IPluginModelBase model) throws CoreException { IClasspathEntry[] entries = javaProject.getRawClasspath(); List<IClasspathEntry> classpath = new ArrayList<>(); List<IClasspathEntry> requiredProjects = new ArrayList<>(); for (int i = 0; i < entries.length; i++) { if (isPluginProjectEntry(entries[i])) { requiredProjects.add(entries[i]); } else { classpath.add(entries[i]); } } if (requiredProjects.size() <= 0) return; IFile file = PDEProject.getManifest(javaProject.getProject()); try { Manifest manifest = new Manifest(file.getContents()); String value = manifest.getMainAttributes().getValue(Constants.REQUIRE_BUNDLE); StringBuffer sb = value != null ? new StringBuffer(value) : new StringBuffer(); if (sb.length() > 0) sb.append(","); for (int i = 0; i < requiredProjects.size(); i++) { IClasspathEntry entry = requiredProjects.get(i); if (i > 0) sb.append(","); sb.append(entry.getPath().segment(0)); if (entry.isExported()) sb.append(";visibility:=reexport"); } manifest.getMainAttributes().putValue(Constants.REQUIRE_BUNDLE, sb.toString()); ByteArrayOutputStream content = new ByteArrayOutputStream(); manifest.write(content); file.setContents(new ByteArrayInputStream(content.toByteArray()), true, false, monitor); javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), monitor); } catch (IOException e) { } catch (CoreException e) { } }

Target:
private static void updateRequiredPlugins(IJavaProject javaProject, IProgressMonitor monitor, IPluginModelBase model) throws CoreException { IClasspathEntry[] entries = javaProject.getRawClasspath(); List<IClasspathEntry> classpath = new ArrayList<>(); List<IClasspathEntry> requiredProjects = new ArrayList<>(); for (int i = 0; i < entries.length; i++) { if (isPluginProjectEntry(entries[i])) { requiredProjects.add(entries[i]); } else { classpath.add(entries[i]); } } if (requiredProjects.size() <= 0) return; IFile file = PDEProject.getManifest(javaProject.getProject()); try { Manifest manifest = new Manifest(file.getContents()); String value = manifest.getMainAttributes().getValue(Constants.REQUIRE_BUNDLE); StringBuffer sb = value != null ? new StringBuffer(value) : new StringBuffer(); if (sb.length() > 0) sb.append(","); for (int i = 0; i < requiredProjects.size(); i++) { IClasspathEntry entry = requiredProjects.get(i); if (i > 0) sb.append(","); sb.append(entry.getPath().segment(0)); if (entry.isExported()) sb.append(";visibility:=reexport"); } manifest.getMainAttributes().putValue(Constants.REQUIRE_BUNDLE, sb.toString()); ByteArrayOutputStream content = new ByteArrayOutputStream(); manifest.write(content); SubMonitor subMonitor = SubMonitor.convert(monitor, 2); file.setContents(new ByteArrayInputStream(content.toByteArray()), true, false, subMonitor.newChild(1)); javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), subMonitor.newChild(1)); } catch (IOException e) { } catch (CoreException e) { } }
Source:
public TkFailure(final Scalar<IOException> err) { super( new Take() { @Override public Response act(final Request request) throws Exception { throw err.value(); } } ); }

Target:
public TkFailure(final Scalar<IOException> err) { super( new Take() { @Override public Response act(final Request request) throws IOException { throw new IoChecked<>(err).value(); } } ); }
Source:
public synchronized void get() { for (Workload workload : jobs.keySet()) { get(workload); } }

Target:
public void get() { for (Workload workload : jobs.keySet()) { get(workload); } }
Source:
private void initFingerprints() { if (fingerprints == null) { synchronized (this) { if (fingerprints == null) { fingerprints = new LinkedHashSet<List<StackTraceElement>>(); for (String sample : this.samples) { try { this.parser.parse("__dummy", sample, ParsingContext.partial_stream); } catch (Exception exception) { if (this.exceptionClass.isAssignableFrom(exception.getClass())) { computeFingerprint((E) exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } } } } }

Target:
private void initFingerprints() { if (fingerprints.isEmpty()) { for (String sample : this.samples) { try { this.parser.parse("__dummy", sample, ParsingContext.partial_stream); } catch (Exception exception) { if (this.exceptionClass.isAssignableFrom(exception.getClass())) { computeFingerprint((E) exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } } }
Source:
public CompletableFuture<Event> process(CoreEvent event, EventProcessor router) throws MuleException { logger.info("Handling odata enabled request."); HttpRequestAttributes attributes = CoreEventUtils.getHttpRequestAttributes(event); OdataContext oDataContext = getOdataContext(router.getRamlHandler().getRamlV1()); oDataContext.setMethod(attributes.getMethod()); String path = attributes.getRelativePath(); if (path.contains(ODATA_SVC_URI_PREFIX)) { return ODataRouterService.processODataRequest(attributes, router, oDataContext,event); } else { return router.processEvent(event); } }

Target:
public CompletableFuture<Event> process(CoreEvent event, EventProcessor router) throws MuleException { logger.info("Handling odata enabled request."); HttpRequestAttributes attributes = CoreEventUtils.getHttpRequestAttributes(event); OdataContext oDataContext = getOdataContext(router.getRamlHandler().getRootRamlLocationForV2()); oDataContext.setMethod(attributes.getMethod()); String path = attributes.getRelativePath(); if (path.contains(ODATA_SVC_URI_PREFIX)) { return ODataRouterService.processODataRequest(attributes, router, oDataContext,event); } else { return router.processEvent(event); } }
Source:
public void onComplete() { s = SubscriptionHelper.CANCELLED; SingleSource<? extends T> c = other; other = null; c.subscribe(this); }

Target:
public void onComplete() { s = SubscriptionHelper.CANCELLED; SingleSource<? extends T> ss = other; other = null; ss.subscribe(this); }
Source:
public synchronized void deletePerPartitionCustomizedState(String customizedStateName, String resourceName, String partitionName) { PropertyKey.Builder keyBuilder = _helixDataAccessor.keyBuilder(); PropertyKey propertyKey = keyBuilder.customizedState(_instanceName, customizedStateName, resourceName); CustomizedState existingState = getCustomizedState(customizedStateName, resourceName); _helixDataAccessor.updateProperty(propertyKey, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord current) { current.getMapFields().remove(partitionName); return current; } }, existingState); }

Target:
public void deletePerPartitionCustomizedState(String customizedStateName, String resourceName, String partitionName) { PropertyKey.Builder keyBuilder = _helixDataAccessor.keyBuilder(); PropertyKey propertyKey = keyBuilder.customizedState(_instanceName, customizedStateName, resourceName); CustomizedState existingState = getCustomizedState(customizedStateName, resourceName); _helixDataAccessor.updateProperty(propertyKey, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord current) { current.getMapFields().remove(partitionName); return current; } }, existingState); }
Source:
public boolean isNextAllowed() { if (isMovingToForward) { return false; } QuestionNode currentQuestionNode = getCurrentNode(); if (currentQuestionNode == null) { return true; } QuestionDB currentQuestionDB = getCurrentQuestion(); ValueDB currentValueDB = currentQuestionDB.getValueBySession(); if (currentValueDB == null) { Log.d(TAG, "isNextAllowed()->You must answer first"); return false; } OptionDB currentOptionDB = currentValueDB == null ? null : currentValueDB.getOptionDB(); boolean isAllowed = findNext(currentOptionDB) != null; if (!isAllowed && !hasNext(null) && !hasNext(currentValueDB.getOptionDB())) { return true; } Log.d(TAG, String.format("isNextAllowed()->%b", isAllowed)); return isAllowed; }

Target:
public boolean isNextAllowed() { if (isMovingToForward) { return false; } QuestionNode currentQuestionNode = getCurrentNode(); if (currentQuestionNode == null) { return true; } QuestionDB currentQuestionDB = getCurrentQuestion(); ValueDB currentValueDB = currentQuestionDB.getValueBySession(); if (currentValueDB == null) { Log.d(TAG, "isNextAllowed()->You must answer first"); return false; } OptionDB currentOptionDB = currentValueDB == null ? null : currentValueDB.getOptionDB(); boolean isAllowed = findNext(currentOptionDB) != null; Log.d(TAG, String.format("isNextAllowed()->%b", isAllowed)); return isAllowed; }
Source:
public char[] reqPassword(Resource<?> resource) { if (console == null) { return null; } return console.readPassword("Enter passphrase for %s:", resource.toString()); }

Target:
public char[] reqPassword(Resource<?> resource) { numTries++; if (console == null) { return null; } return console.readPassword(promptFormat, resource.toString()); }
Source:
public boolean matches(String theLeftString, String theRightString) { try { return myStringEncoder.encode(theLeftString).equals(myStringEncoder.encode(theRightString)); } catch (EncoderException e) { ourLog.error("Failed to match strings '" + theLeftString + "' and '" + theRightString + "' using encoder " + myStringEncoder.getClass().getName(), e); } return false; }

Target:
public boolean matches(String theLeftString, String theRightString) { try { return myStringEncoder.encode(theLeftString).equals(myStringEncoder.encode(theRightString)); } catch (EncoderException e) { ourLog.error("Failed to match strings '{}' and '{}' using encoder {}", theLeftString, theRightString, myStringEncoder.getClass().getName(), e); } return false; }
Source:
public void increaseEventProcessors(final int delta) { synchronized (eventProcessors) { final int currNum = eventProcessors.size(); final int increaseNum = Math.min(delta, eventProcessorUpperBound - currNum); if (increaseNum != 0) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Increase event processors from {0} to {1}", new Object[]{currNum, currNum + increaseNum}); } addNewThreadsToSet(increaseNum); } } }

Target:
public void increaseEventProcessors(final int delta) { if (delta < 0) { throw new RuntimeException("The delta value should be greater than zero, but " + delta); } synchronized (eventProcessors) { final int currNum = eventProcessors.size(); final int increaseNum = Math.min(delta, eventProcessorUpperBound - currNum); if (increaseNum != 0) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Increase event processors from {0} to {1}", new Object[]{currNum, currNum + increaseNum}); } addNewThreadsToSet(increaseNum); } } }
Source:
public void call(Subscriber<? super T> observer) { responseSubject.onBackpressureBuffer().subscribe(observer); }

Target:
public void call(Subscriber<? super T> observer) { responseSubject.unsafeSubscribe(observer); }
Source:
public void skip(int n) { if (indexInStream + n > numberOfValues || n < 0) { String errorMessage = String.format( "Cannot skip this many elements. Current index: %d. Skip %d. Total number of elements: %d", indexInStream, n, numberOfValues); throw new ParquetDecodingException(errorMessage); } indexInStream += n; }

Target:
public void skip(int n) { if (n < 0 || indexInStream + n > valuesCount) { String errorMessage = String.format( "Cannot skip this many elements. Current index: %d. Skip %d. Total number of elements: %d", indexInStream, n, valuesCount); throw new ParquetDecodingException(errorMessage); } indexInStream += n; }
Source:
public StringBuilder getBuffer() { return this.buffer; }

Target:
public StringBuffer getBuffer() { return this.buffer; }
Source:
protected void onInit() throws ServletException { LogoutController c = new LogoutController(getConfig()); c.setLogoutInvalidateHttpSession(getConfig().isLogoutInvalidateHttpSession()) .setLogoutNextUri(getConfig().getLogoutControllerConfig().getNextUri()); setController(c); super.onInit(); }

Target:
protected void onInit() throws ServletException { LogoutController c = new LogoutController(getConfig().getLogoutControllerConfig(), getConfig().getProducesMediaTypes()); c.setLogoutInvalidateHttpSession(getConfig().isLogoutInvalidateHttpSession()) .setLogoutNextUri(getConfig().getLogoutControllerConfig().getNextUri()); setController(c); super.onInit(); }
Source:
public ArticleCard(String webUrl) throws CardBuilderException { this.cardType = CardType.ARTICLE; webUrl(webUrl); MetaTagModel metaTagModel = MetaTagExtractor.getMetaTags(this.webUrl); article(new ArticleBuilder(metaTagModel).build()); }

Target:
public ArticleCard(String webUrl) throws CardBuilderException { super(webUrl); this.cardType = CardType.ARTICLE; article(new ArticleBuilder(this.getMetaTagModel()).build()); }
Source:
public JingleS5BTransport build() { StringUtils.requireNotNullOrEmpty(streamId, "sid MUST be neither null, nor empty."); return new JingleS5BTransport(candidates, infos, streamId, dstAddr, mode); }

Target:
public JingleS5BTransport build() { return new JingleS5BTransport(candidates, infos, streamId, dstAddr, mode); }
Source:
public String formatWithConflicts(String message, List<String> conflictingPaths) { StringBuilder sb = new StringBuilder(); String[] lines = message.split("\n"); int firstFooterLine = ChangeIdUtil.findFirstFooterLine(lines); for (int i = 0; i < firstFooterLine; i++) { sb.append(lines[i]).append("\n"); } if (firstFooterLine == lines.length && message.length() != 0) sb.append("\n"); addConflictsMessage(conflictingPaths, sb); if (firstFooterLine < lines.length) sb.append("\n"); for (int i = firstFooterLine; i < lines.length; i++) { sb.append(lines[i]).append("\n"); } return sb.toString(); }

Target:
public String formatWithConflicts(String message, List<String> conflictingPaths) { StringBuilder sb = new StringBuilder(); String[] lines = message.split("\n"); int firstFooterLine = ChangeIdUtil.indexOfFirstFooterLine(lines); for (int i = 0; i < firstFooterLine; i++) sb.append(lines[i]).append('\n'); if (firstFooterLine == lines.length && message.length() != 0) sb.append('\n'); addConflictsMessage(conflictingPaths, sb); if (firstFooterLine < lines.length) sb.append('\n'); for (int i = firstFooterLine; i < lines.length; i++) sb.append(lines[i]).append('\n'); return sb.toString(); }
Source:
public void update(Storable storable) { if (queryExecutor.update(storable) == 0) { log.warn("Update storable '{}' returned 0 rows, possible concurrent update"); throw new ConcurrentUpdateException("Row could not be updated, possible concurrent update"); } }

Target:
public void update(Storable storable) { if (queryExecutor.update(storable) == 0) { log.warn("Update storable '{}' returned 0 rows, possible concurrent update or invalid primary key"); throw new ConcurrentUpdateException("Row could not be updated, possible concurrent update or invalid primary key"); } }
Source:
public FactoryDto createFactoryFromJson(String jsonFileLocation) { if (jsonFileLocation != null) { final String factoryJsonContent = urlFetcher.fetch(jsonFileLocation); if (!Strings.isNullOrEmpty(factoryJsonContent)) { return DtoFactory.getInstance().createDtoFromJson(factoryJsonContent, FactoryDto.class); } } return null; }

Target:
public Optional<FactoryDto> createFactoryFromJson(String jsonFileLocation) { if (jsonFileLocation != null) { final String factoryJsonContent = urlFetcher.fetch(jsonFileLocation); if (!Strings.isNullOrEmpty(factoryJsonContent)) { return Optional.of( DtoFactory.getInstance().createDtoFromJson(factoryJsonContent, FactoryDto.class)); } } return Optional.empty(); }
Source:
public Map<SubscriptionCursor, Boolean> commitCursors(final String streamId, final String subscriptionId, final List<SubscriptionCursor> cursors) throws NakadiException, InvalidCursorException { validateStreamId(cursors, streamId, subscriptionId); LOG.debug("[COMMIT_CURSORS] stream IDs validation finished"); final Iterator<EventTypePartition> distinctPartitions = cursors.stream() .map(c -> new EventTypePartition(c.getEventType(), c.getPartition())) .distinct() .iterator(); final HashMap<EventTypePartition, Iterator<Boolean>> partitionCommits = new HashMap<>(); while (distinctPartitions.hasNext()) { final EventTypePartition etPartition = distinctPartitions.next(); final List<SubscriptionCursor> partitionCursors = cursors.stream() .filter(etPartition::ownsCursor) .collect(Collectors.toList()); final Iterator<Boolean> commitResultIterator = processPartitionCursors(subscriptionId, partitionCursors, etPartition).iterator(); partitionCommits.put(etPartition, commitResultIterator); LOG.debug("[COMMIT_CURSORS] committed cursor(s) for partition {}", partitionCursors.size(), etPartition); } return cursors.stream() .collect(Collectors.toMap( Function.identity(), cursor -> { final EventTypePartition etPartition = new EventTypePartition(cursor.getEventType(), cursor.getPartition()); return partitionCommits.get(etPartition).next(); } )); }

Target:
public List<CursorCommitResult> commitCursors(final String streamId, final String subscriptionId, final List<SubscriptionCursor> cursors) throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException { validateStreamId(cursors, streamId, subscriptionId); LOG.debug("[COMMIT_CURSORS] stream IDs validation finished"); final Map<EventTypePartition, List<SubscriptionCursor>> cursorsByPartition = cursors.stream() .collect(Collectors.groupingBy( cursor -> new EventTypePartition(cursor.getEventType(), cursor.getPartition()))); final HashMap<EventTypePartition, Iterator<Boolean>> partitionCommits = new HashMap<>(); for (final EventTypePartition etPartition : cursorsByPartition.keySet()) { final Iterator<Boolean> commitResultIterator = processPartitionCursors(subscriptionId, cursorsByPartition.get(etPartition), etPartition).iterator(); partitionCommits.put(etPartition, commitResultIterator); LOG.debug("[COMMIT_CURSORS] committed cursor(s) for partition {}", cursorsByPartition.get(etPartition).size(), etPartition); } return cursors.stream() .map(cursor -> { final EventTypePartition etPartition = new EventTypePartition(cursor.getEventType(), cursor.getPartition()); final Boolean committed = partitionCommits.get(etPartition).next(); return new CursorCommitResult(cursor, committed); }) .collect(Collectors.toList()); }
Source:
public static Archive<?> createTestArchive() { return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(WeldInstanceTest.class)) .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }

Target:
public static Archive<?> createTestArchive() { return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(ParallelNotificationModeTest.class)) .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }