auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
synchronized boolean update() { if(numberOfCommandsInHistory < commands.size()) { if(tabs == null) return true; final Command c = commands.get(numberOfCommandsInHistory++); TabForm form = init(c); final TabForm finalForm = form; Display display = PlatformUI.getWorkbench().getDisplay(); Runnable run = new Runnable() { public void run() { Activator.log("redraw after adding "+c.text); int j=0; for(int i=0;i<NENTRIES-1;i++) { if(finalForm.rows[i].check.getSelection()) { if(i > j) { finalForm.swap(i,j); } j++; } } for(int i=NENTRIES-1;i > j;i--) { if(!finalForm.rows[i-1].txt.getText().equals("")) { finalForm.swap(i,i-1); } } if(numberOfCommandsInHistory > 1) finalForm.rows[j].txt.setText(c.text.trim()); tabs.pack(); tabs.redraw(); } }; display.syncExec(run); return true; } else { return false; } }

Target:
private synchronized void update() { if(fTabs == null || !fTabs.isEnabled() || fTabs.isDisposed()) return; while(numberOfCommandsInHistory < commands.size()) { Command c = commands.get(numberOfCommandsInHistory++); TabForm form = init(c); int j=0; for(int i=0;i<NENTRIES-1;i++) { if(form.rows[i].fCheck.getSelection()) { if(i > j) { form.swap(i,j); } j++; } } for(int i=NENTRIES-1;i > j;i--) { if(!form.rows[i-1].fText.getText().equals("")) { form.swap(i,i-1); } } if(numberOfCommandsInHistory > 1) form.rows[j].fText.setText(c.text.trim()); } fTabs.pack(); fTabs.redraw(); }
Source:
public static ErlangExpression getFunctionCallArgument(@NotNull ErlangFunctionCallExpression call, @Nullable PsiElement child) { ErlangExpression argument = PsiTreeUtil.getParentOfType(child, ErlangExpression.class, false); while (argument != null && !(argument.getParent() instanceof ErlangArgumentList)) { argument = ObjectUtils.tryCast(argument.getParent(), ErlangExpression.class); } return argument != null && call.getArgumentList() != argument.getParent() ? getFunctionCallArgument(call, argument.getParent()) : argument; }

Target:
public static ErlangExpression getFunctionCallArgument(@NotNull ErlangFunctionCallExpression call, @Nullable PsiElement child) { ErlangArgumentList argumentList = call.getArgumentList(); PsiElement argument = child; PsiElement parent; while (argument != null && (parent = argument.getParent()) != argumentList) { argument = parent; } return ObjectUtils.tryCast(argument, ErlangExpression.class); }
Source:
protected final boolean perform(BuildStep bs, BuildListener listener) throws InterruptedException, IOException { BuildStepMonitor mon; try { mon = bs.getRequiredMonitorService(); } catch (AbstractMethodError e) { mon = BuildStepMonitor.BUILD; } Result oldResult = AbstractBuild.this.getResult(); for (BuildStepListener bsl : BuildStepListener.all()) { bsl.started(AbstractBuild.this, bs, listener); } boolean canContinue = false; try { canContinue = mon.perform(bs, AbstractBuild.this, launcher, listener); } catch (RequestAbortedException ex) { listener.error("Slave went offline during the build."); final OfflineCause offlineCause = getCurrentNode().toComputer().getOfflineCause(); if (offlineCause != null) { listener.error(offlineCause.toString()); } } catch (RuntimeException ex) { ex.printStackTrace(listener.error("Build step failed with excepiton")); } for (BuildStepListener bsl : BuildStepListener.all()) { bsl.finished(AbstractBuild.this, bs, listener, canContinue); } Result newResult = AbstractBuild.this.getResult(); if (newResult != oldResult) { String buildStepName = getBuildStepName(bs); listener.getLogger().format("Build step '%s' changed build result to %s%n", buildStepName, newResult); } if (!canContinue) { String buildStepName = getBuildStepName(bs); listener.getLogger().format("Build step '%s' marked build as failure%n", buildStepName); } return canContinue; }

Target:
protected final boolean perform(BuildStep bs, BuildListener listener) throws InterruptedException, IOException { BuildStepMonitor mon; try { mon = bs.getRequiredMonitorService(); } catch (AbstractMethodError e) { mon = BuildStepMonitor.BUILD; } Result oldResult = AbstractBuild.this.getResult(); for (BuildStepListener bsl : BuildStepListener.all()) { bsl.started(AbstractBuild.this, bs, listener); } boolean canContinue = false; try { canContinue = mon.perform(bs, AbstractBuild.this, launcher, listener); } catch (RequestAbortedException ex) { reportBrokenChannel(listener); } catch (ChannelClosedException ex) { reportBrokenChannel(listener); } catch (RuntimeException ex) { ex.printStackTrace(listener.error("Build step failed with exception")); } for (BuildStepListener bsl : BuildStepListener.all()) { bsl.finished(AbstractBuild.this, bs, listener, canContinue); } Result newResult = AbstractBuild.this.getResult(); if (newResult != oldResult) { String buildStepName = getBuildStepName(bs); listener.getLogger().format("Build step '%s' changed build result to %s%n", buildStepName, newResult); } if (!canContinue) { String buildStepName = getBuildStepName(bs); listener.getLogger().format("Build step '%s' marked build as failure%n", buildStepName); } return canContinue; }
Source:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.sleep(500); } m_reinsertExecutor.shutdown(); m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); }

Target:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.yield(); } if (m_reinsertExecutor != null) { m_reinsertExecutor.shutdown(); m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); } }
Source:
public void default_threshold() throws Exception { SourceFile file = PythonAstScanner.scanSingleFile("src/test/resources/checks/fileComplexity.py", check); CheckMessagesVerifier.verify(file.getCheckMessages()) .noMore(); }

Target:
public void default_threshold() throws Exception { PythonCheckVerifier.verify("src/test/resources/checks/cognitiveComplexityFunctionDefault.py", check); }
Source:
public boolean checkForCloudProfileFacts(Map<String, String> incomingFacts) { if (incomingFacts == null) { return false; } if (this.facts != null && incomingFacts != null && this.facts.equals(incomingFacts)) { return false; } for (Entry<String, String> entry : incomingFacts.entrySet()) { if (CloudProfileFacts.containsFact(entry.getKey())) { if (this.facts == null) { return true; } else if (!this.facts.containsKey(entry.getKey())) { return true; } else if (this.facts.containsKey(entry.getKey()) && !this.facts.get(entry.getKey()).equals(entry.getValue())) { return true; } } } return false; }

Target:
public boolean checkForCloudProfileFacts(Map<String, String> incomingFacts) { if (incomingFacts == null) { return false; } if (this.facts != null && this.facts.equals(incomingFacts)) { return false; } for (CloudProfileFacts profileFact : CloudProfileFacts.values()) { if (incomingFacts.containsKey(profileFact.getFact())) { if (this.facts == null || !this.facts.containsKey(profileFact.getFact()) || !this.facts.get(profileFact.getFact()).equals(incomingFacts.get(profileFact.getFact()))) { return true; } } } return false; }
Source:
public void onResponseReceived(Request req, Response res) { String text = res.getText(); if (text.startsWith("token=")) { RestApi.this.sendPost(cb, text); return; } RpcStatus.INSTANCE.onRpcComplete(); int status = res.getStatusCode(); if (status != 200) { if ((400 <= status && status < 500) && isTextBody(res)) { cb.onFailure(new RemoteJsonException(res.getText(), status, null)); } else { cb.onFailure(new StatusCodeException(status, res.getStatusText())); } return; } if (!isJsonBody(res)) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } String json = res.getText(); if (!json.startsWith(JSON_MAGIC)) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } T data; try { data = Natives.<T> parseJSON(json.substring(JSON_MAGIC.length())); } catch (RuntimeException e) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } cb.onSuccess(data); }

Target:
public void onResponseReceived(Request req, Response res) { int status = res.getStatusCode(); if (status != 200) { RpcStatus.INSTANCE.onRpcComplete(); if ((400 <= status && status < 500) && isTextBody(res)) { cb.onFailure(new RemoteJsonException(res.getText(), status, null)); } else { cb.onFailure(new StatusCodeException(status, res.getStatusText())); } return; } String text = res.getText(); if (text.startsWith("_token=")) { RestApi.this.sendPost(cb, text); return; } RpcStatus.INSTANCE.onRpcComplete(); if (!isJsonBody(res)) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } String json = res.getText(); if (!json.startsWith(JSON_MAGIC)) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } T data; try { data = Natives.<T> parseJSON(json.substring(JSON_MAGIC.length())); } catch (RuntimeException e) { cb.onFailure(new RemoteJsonException("Invalid JSON")); return; } cb.onSuccess(data); }
Source:
public void scanQrCode() { try { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, REQUEST_CODE_QR_CODE); } catch(ActivityNotFoundException e) { Log.i(TAG, "scanQrCode() exception", e); Toast.makeText(this, "Please install QR-code scanner", Toast.LENGTH_LONG).show(); Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android"); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); } catch(Exception e) { Log.e(TAG, "scanQrCode() exception", e); } }

Target:
private void scanQrCode() { try { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, REQUEST_CODE_QR_CODE); } catch(ActivityNotFoundException e) { Log.i(TAG, "scanQrCode() exception", e); Toast.makeText(this, R.string.connectionWizard_misc_installQrCodeScanner, Toast.LENGTH_LONG).show(); Uri marketUri = Uri.parse("market://details?id=de.markusfisch.android.binaryeye"); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); } catch(Exception e) { Log.w(TAG, "scanQrCode() exception", e); } }
Source:
private CompletionStage<BeamFnApi.StateResponse.Builder> handleMapGetRequest(BeamFnApi.StateRequest request) throws Exception { byte[] getRequest = request.getGet().getContinuationToken().toByteArray(); byte getFlag = getRequest[0]; if (reuseByteArrayWrapper == null) { reuseByteArrayWrapper = new ByteArrayWrapper(getRequest, 1); } else { reuseByteArrayWrapper.setData(getRequest); reuseByteArrayWrapper.setOffset(1); reuseByteArrayWrapper.setLimit(getRequest.length); } MapState<ByteArrayWrapper, byte[]> mapState = getMapState(request); BeamFnApi.StateGetResponse.Builder response; switch (getFlag) { case GET_FLAG: response = handleMapGetValueRequest(reuseByteArrayWrapper, mapState); break; case CHECK_EMPTY_FLAG: response = handleMapCheckEmptyRequest(mapState); break; default: throw new RuntimeException(String.format( "Unsupported get request type: '%d' for map state.", getFlag)); } return CompletableFuture.completedFuture( BeamFnApi.StateResponse.newBuilder() .setId(request.getId()) .setGet(response)); }

Target:
private CompletionStage<BeamFnApi.StateResponse.Builder> handleMapGetRequest(BeamFnApi.StateRequest request) throws Exception { byte[] getRequest = request.getGet().getContinuationToken().toByteArray(); byte getFlag = getRequest[0]; reuseByteArrayWrapper.setData(getRequest); reuseByteArrayWrapper.setOffset(1); reuseByteArrayWrapper.setLimit(getRequest.length); MapState<ByteArrayWrapper, byte[]> mapState = getMapState(request); BeamFnApi.StateGetResponse.Builder response; switch (getFlag) { case GET_FLAG: response = handleMapGetValueRequest(reuseByteArrayWrapper, mapState); break; case CHECK_EMPTY_FLAG: response = handleMapCheckEmptyRequest(mapState); break; default: throw new RuntimeException(String.format( "Unsupported get request type: '%d' for map state.", getFlag)); } return CompletableFuture.completedFuture( BeamFnApi.StateResponse.newBuilder() .setId(request.getId()) .setGet(response)); }
Source:
public void testResolveFromWorkDirYamlAndYaml() throws Exception { helper.givenYamlClientFailoverConfigFileInWorkDir(42); helper.givenYmlClientFailoverConfigFileInWorkDir(42); ClientFailoverConfig config = new YamlClientFailoverConfigBuilder().build(); assertEquals(42, config.getTryCount()); }

Target:
public void testResolveFromWorkDirYamlAndYaml() throws Exception { helper.givenYamlClientFailoverConfigFileInWorkDir(42); helper.givenYmlClientFailoverConfigFileInWorkDir(24); ClientFailoverConfig config = new YamlClientFailoverConfigBuilder().build(); assertEquals(42, config.getTryCount()); }
Source:
public AggregationDataStoreTestHarness(EntityManagerFactory entityManagerFactory, DataSource defaultDataSource) { this(entityManagerFactory, defaultDataSource, Collections.emptyMap(), SQLDialectFactory.getDefaultDialect().getDialectType(), Collections.emptyMap()); }

Target:
public AggregationDataStoreTestHarness(EntityManagerFactory entityManagerFactory, DataSource defaultDataSource) { this(entityManagerFactory, new ConnectionDetails(defaultDataSource, SQLDialectFactory.getDefaultDialect().getClass().getName())); }
Source:
public void saveNewSanStorage() { StorageModel model = (StorageModel) getWindow(); SanStorageModelBase sanModel = (SanStorageModelBase) model.getCurrentStorageItem(); VDS host = model.getHost().getSelectedItem(); boolean force = sanModel.isForce(); HashSet<String> lunIds = new HashSet<>(); for (LunModel lun : sanModel.getAddedLuns()) { lunIds.add(lun.getLunId()); } AddSANStorageDomainParameters params = new AddSANStorageDomainParameters(storageDomain); params.setVdsId(host.getId()); params.setLunIds(new HashSet<>(lunIds)); params.setForce(force); Frontend.getInstance().runAction(VdcActionType.AddSANStorageDomain, params, result -> { StorageListModel storageListModel = (StorageListModel) result.getState(); StorageModel storageModel = (StorageModel) storageListModel.getWindow(); storageListModel.storageModel = storageModel.getCurrentStorageItem(); if (!result.getReturnValue().getSucceeded()) { storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel); return; } StoragePool dataCenter = storageModel.getDataCenter().getSelectedItem(); if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) { VdcReturnValueBase returnValue = result.getReturnValue(); Guid storageId = returnValue.getActionReturnValue(); storageListModel.attachStorageToDataCenter(storageId, dataCenter.getId(), storageModel.getActivateDomain().getEntity()); } storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel); }, this); }

Target:
public void saveNewSanStorage() { StorageModel model = (StorageModel) getWindow(); SanStorageModelBase sanModel = (SanStorageModelBase) model.getCurrentStorageItem(); VDS host = model.getHost().getSelectedItem(); boolean force = sanModel.isForce(); HashSet<String> lunIds = new HashSet<>(); for (LunModel lun : sanModel.getAddedLuns()) { lunIds.add(lun.getLunId()); } AddSANStorageDomainParameters params = new AddSANStorageDomainParameters(storageDomain); params.setVdsId(host.getId()); params.setLunIds(lunIds); params.setForce(force); Frontend.getInstance().runAction(VdcActionType.AddSANStorageDomain, params, result -> { StorageListModel storageListModel = (StorageListModel) result.getState(); StorageModel storageModel = (StorageModel) storageListModel.getWindow(); storageListModel.storageModel = storageModel.getCurrentStorageItem(); if (!result.getReturnValue().getSucceeded()) { storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel); return; } StoragePool dataCenter = storageModel.getDataCenter().getSelectedItem(); if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) { VdcReturnValueBase returnValue = result.getReturnValue(); Guid storageId = returnValue.getActionReturnValue(); storageListModel.attachStorageToDataCenter(storageId, dataCenter.getId(), storageModel.getActivateDomain().getEntity()); } storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel); }, this); }
Source:
public boolean isRetryableException(Exception exception) { return !isNonRetryableServiceException(exception); }

Target:
public boolean isRetryableException(Exception exception) { if (exception instanceof AmazonServiceException) { AmazonServiceException ase = (AmazonServiceException) exception; return !NONRETRYABLE_STATUS_CODES.contains(ase.getStatusCode()) && !NONRETRYABLE_ERROR_CODES.contains(ase.getErrorCode()); } return true; }
Source:
public void stressTest() { TestableTimelockServer nonLeader = Iterables.getFirst(cluster.nonLeaders(client.namespace()).values(), null); int startingNumThreads = ManagementFactory.getThreadMXBean().getThreadCount(); try { for (int i = 0; i < 10_000; i++) { client.getFreshTimestamp(); assertThat(ManagementFactory.getThreadMXBean().getThreadCount()) .as("should not additionally spin up too many threads") .isLessThanOrEqualTo(startingNumThreads + 200); if (i == 1_000) { nonLeader.serverHolder().wireMock().register( WireMock.any(WireMock.anyUrl()) .atPriority(Integer.MAX_VALUE - 1) .willReturn(WireMock.serviceUnavailable().withFixedDelay( Ints.checkedCast(Duration.ofSeconds(2).toMillis()))).build()); } } } finally { nonLeader.serverHolder().resetWireMock(); } }

Target:
public void stressTest() { TestableTimelockServer nonLeader = Iterables.getFirst(cluster.nonLeaders(client.namespace()).values(), null); int startingNumThreads = ManagementFactory.getThreadMXBean().getThreadCount(); boolean isNonLeaderTakenOut = false; try { for (int i = 0; i < 10_000; i++) { client.getFreshTimestamp(); assertNumberOfThreadsReasonable( startingNumThreads, ManagementFactory.getThreadMXBean().getThreadCount(), isNonLeaderTakenOut); if (i == 1_000) { makeServerWaitTwoSecondsAndThenReturn503s(nonLeader); isNonLeaderTakenOut = true; } } } finally { nonLeader.serverHolder().resetWireMock(); } }
Source:
public void evaluate(final Node node, final RuleContext data) { initXPathRuleQuery(); final List<Node> nodesWithViolation = xpathRuleQuery.evaluate(node, data); for (final Node nodeWithViolation : nodesWithViolation) { addViolation(data, nodeWithViolation, nodeWithViolation.getImage()); } }

Target:
public void evaluate(final Node node, final RuleContext data) { if (xPathRuleQueryNeedsInitialization()) { initXPathRuleQuery(); } List<Node> nodesWithViolation = xpathRuleQuery.evaluate(node, data); for (Node nodeWithViolation : nodesWithViolation) { addViolation(data, nodeWithViolation, nodeWithViolation.getImage()); } }
Source:
public Object get(Object key) { try { return (getRegion().get(key)); } catch (IOException ex) { LOG.info("error getting object ", ex); return null; } }

Target:
public Object get(Object key) { try { return (getRegion().get(key)); } catch (IOException ex) { throw new RuntimeException("Exception while getting the object", ex); } }
Source:
public static String encodeBase64URLSafeString(byte[] binaryData) { if(binaryData == null){ return null; } return com.google.common.io.BaseEncoding.base64Url().omitPadding().encode(binaryData); }

Target:
public static String encodeBase64URLSafeString(byte[] binaryData) { if (binaryData == null) { return null; } return BaseEncoding.base64Url().omitPadding().encode(binaryData); }
Source:
private void printUsage(ParametersParser parser) { logger.info( String.format( "usage: %s%n%n%s%n%n%s", parser.getPrefixUsage().replace("@PROGRAM_NAME@", (String)getContext().get(PROGRAM_NAME)), parser.getPrefixHelp(), parser.getPrefixUnderlinetext() ) ); }

Target:
private void printUsage(ParametersParser parser) { System.out.format( "usage: %s", parser.getUsage().replace("@PROGRAM_NAME@", (String) context.get(PROGRAM_NAME)) ); }
Source:
public float getBlockLocalityIndexForSsd(String host) { return (float) getBlocksLocalityWeightInternal(host, e -> e.weightForSsd) / (float) uniqueBlocksTotalWeight; }

Target:
public float getBlockLocalityIndexForSsd(String host) { if (uniqueBlocksTotalWeight == 0) { return 0.0f; } else { return (float) getBlocksLocalityWeightInternal(host, HostAndWeight::getWeightForSsd) / (float) uniqueBlocksTotalWeight; } }
Source:
public void rebuild() { buildGraph(); }

Target:
public Graph rebuild() { return buildGraph(); }
Source:
public static <K, V> CompletionStage<Void> handleEviction(InternalCacheEntry<K, V> entry, DataOperationOrderer orderer, PassivationManager passivator, EvictionManager<K, V> evictionManager, DataContainer<K, V> dataContainer, CompletionStage<Void> selfDelay) { K key = entry.getKey(); CompletableFuture<Operation> future = new CompletableFuture<>(); CompletionStage<Operation> ordererStage = orderer != null ? orderer.orderOn(key, future) : null; if (ordererStage != null) { return ordererStage.thenCompose(operation -> { switch (operation) { case REMOVE: return skipPassivation(orderer, key, future, operation); case WRITE: if (dataContainer.containsKey(key)) { if (selfDelay != null) { if (trace) { log.tracef("Delaying check for %s verify if passivation should occur as there was a" + " concurrent write", key); } return selfDelay.thenCompose(ignore -> { if (dataContainer.containsKey(key)) { return skipPassivation(orderer, key, future, operation); } else { return handleNotificationAndOrderer(key, entry, passivator.passivateAsync(entry), orderer, evictionManager, future); } }); } return skipPassivation(orderer, key, future, operation); } default: CompletionStage<Void> passivatedStage = passivator.passivateAsync(entry); return handleNotificationAndOrderer(key, entry, passivatedStage, orderer, evictionManager, future); } }); } return handleNotificationAndOrderer(key, entry, passivator.passivateAsync(entry), orderer, evictionManager, future); }

Target:
public static <K, V> CompletionStage<Void> handleEviction(InternalCacheEntry<K, V> entry, DataOperationOrderer orderer, PassivationManager passivator, EvictionManager<K, V> evictionManager, DataContainer<K, V> dataContainer, CompletionStage<Void> selfDelay) { K key = entry.getKey(); CompletableFuture<Operation> future = new CompletableFuture<>(); CompletionStage<Operation> ordererStage = orderer != null ? orderer.orderOn(key, future) : null; if (ordererStage != null) { if (trace) { log.tracef("Encountered concurrent operation during eviction of %s", key); } return ordererStage.thenCompose(operation -> { if (trace) { log.tracef("Concurrent operation during eviction of %s was %s", key, operation); } switch (operation) { case REMOVE: return skipPassivation(orderer, key, future, operation); case WRITE: if (dataContainer.containsKey(key)) { if (selfDelay != null) { if (trace) { log.tracef("Delaying check for %s verify if passivation should occur as there was a" + " concurrent write", key); } return selfDelay.thenCompose(ignore -> { if (dataContainer.containsKey(key)) { return skipPassivation(orderer, key, future, operation); } else { return handleNotificationAndOrderer(key, entry, passivator.passivateAsync(entry), orderer, evictionManager, future); } }); } return skipPassivation(orderer, key, future, operation); } default: CompletionStage<Void> passivatedStage = passivator.passivateAsync(entry); return handleNotificationAndOrderer(key, entry, passivatedStage, orderer, evictionManager, future); } }); } return handleNotificationAndOrderer(key, entry, passivator.passivateAsync(entry), orderer, evictionManager, future); }
Source:
public static String validateQuery(String query, ValidationType validationType) { final QueryValidator validator = QueryValidatorFactory.createValidator(validationType); if ((query == null) || "".equals(query) || validator.isValid(query)) { return query; } throw TalendRuntimeException.createUnexpectedException( "Please check your sql as we only allow the query which don't do write or lock action."); }

Target:
public static String validateQuery(String query, ValidationType validationType) { final QueryValidator validator = QueryValidatorFactory.createValidator(validationType); if ((query == null) || query.isEmpty() || validator.isValid(query)) { return query; } throw TalendRuntimeException.createUnexpectedException( "Please check your sql as we only allow the query which don't do write or lock action."); }
Source:
private void clearHeaders() { try { responseMetadataChangeLock.lock(); responseMetadata.headers().clear(); logger.trace("Headers cleared for response in channel {}", ctx.channel()); } finally { responseMetadataChangeLock.unlock(); } }

Target:
private void clearHeaders() { responseMetadataChangeLock.lock(); try { responseMetadata.headers().clear(); logger.trace("Headers cleared for response in channel {}", ctx.channel()); } finally { responseMetadataChangeLock.unlock(); } }
Source:
public void dropRole(String role) { synchronized (rolesLock) { Set<String> roles = new HashSet<>(listRoles()); roles.remove(role); writeFile("roles", getRolesFile(), rolesCodec, ImmutableList.copyOf(roles), true); } }

Target:
public void dropRole(String role) { synchronized (rolesLock) { Set<String> roles = new HashSet<>(listRoles()); roles.remove(role); writeFile("roles", getRolesFile(), rolesCodec, ImmutableList.copyOf(roles), true); Set<RoleGrant> grants = listRoleGrantsSanitized(); writeRoleGrantsFile(grants); } }
Source:
public AdsBaseObject verifyAdImage(String slotName, String src, String imageUrl) { WebElement element = getWebElement(slotName); boolean isMobile = src.toUpperCase().equals("MOBILE"); Assertion.assertTrue(new AdsComparison().compareImageWithScreenshot(imageUrl, element, driver, isMobile)); PageObjectLogging.log("verifyAdImage", "Ad looks good", true, driver); return this; }

Target:
public AdsBaseObject verifyAdImage(String slotName, String src, String imageUrl) { WebElement element = getWebElement(slotName); boolean isMobile = "MOBILE".equalsIgnoreCase(src); Assertion.assertTrue(new AdsComparison().compareImageWithScreenshot(imageUrl, element, driver, isMobile)); PageObjectLogging.log("verifyAdImage", "Ad looks good", true, driver); return this; }
Source:
public static IdentifierTree getArgumentIdentifier(MethodInvocationTree mit, int index) { Arguments arguments = mit.arguments(); if (index < 0 || index > arguments.size()) { return null; } ExpressionTree expr = ExpressionUtils.skipParentheses(arguments.get(index)); switch (expr.kind()) { case MEMBER_SELECT: return ((MemberSelectExpressionTree) expr).identifier(); case IDENTIFIER: return ((IdentifierTree) expr); default: return null; } }

Target:
public static IdentifierTree getArgumentIdentifier(MethodInvocationTree mit, int index) { Arguments arguments = mit.arguments(); if (index < 0 || index > arguments.size()) { throw new IllegalArgumentException("index must be within arguments range."); } ExpressionTree expr = ExpressionUtils.skipParentheses(arguments.get(index)); switch (expr.kind()) { case MEMBER_SELECT: return ((MemberSelectExpressionTree) expr).identifier(); case IDENTIFIER: return ((IdentifierTree) expr); default: return null; } }
Source:
public void initialize(ByteSize constraintAnnotation) { try { charset = Charset.forName(constraintAnnotation.charset()); } catch (IllegalArgumentException e) { throw reportFailedToInitialize(e); } min = constraintAnnotation.min(); max = constraintAnnotation.max(); if (max < min) { throw reportFailedToInitialize(new IllegalArgumentException("max[" + max + "] must be higher or equal to min[" + min + "].")); } }

Target:
public void initialize(ByteSize constraintAnnotation) { try { charset = Charset.forName(constraintAnnotation.charset()); } catch (IllegalArgumentException e) { throw reportFailedToInitialize(e); } min = constraintAnnotation.min(); max = constraintAnnotation.max(); if (min < 0) { throw reportFailedToInitialize(new IllegalArgumentException("min[" + min + "] must not be negative value.")); } if (max < 0) { throw reportFailedToInitialize(new IllegalArgumentException("max[" + max + "] must not be negative value.")); } if (max < min) { throw reportFailedToInitialize(new IllegalArgumentException("max[" + max + "] must be higher or equal to min[" + min + "].")); } }
Source:
public TimeBasedDirectoryScanner() { lastModifiedTimes = Maps.newHashMap(); recursive = true; scanIntervalMillis = DEF_SCAN_INTERVAL_MILLIS; files = Sets.newLinkedHashSet(); scanService = Executors.newSingleThreadExecutor(); discoveredFiles = new LinkedBlockingDeque<FileInfo>(); atomicThrowable = new AtomicReference<Throwable>(); ignoredFiles = Sets.newHashSet(); lock = new Lock(); }

Target:
public TimeBasedDirectoryScanner() { lastModifiedTimes = Maps.newHashMap(); recursive = true; scanIntervalMillis = DEF_SCAN_INTERVAL_MILLIS; files = Sets.newLinkedHashSet(); scanService = Executors.newSingleThreadExecutor(); discoveredFiles = new LinkedBlockingDeque<FileInfo>(); atomicThrowable = new AtomicReference<Throwable>(); ignoredFiles = Sets.newHashSet(); }
Source:
public void sendRequest(Exchange exchange, final Request request) { if (request.getToken() != null) { KeyToken idByToken = Exchange.KeyToken.fromOutboundMessage(request); if (!(exchange.getFailedTransmissionCount() > 0 || request.getOptions().hasBlock1() || request.getOptions().hasBlock2() || request.getOptions().hasObserve()) && exchangeStore.get(idByToken) != null) { LOGGER.log(Level.WARNING, "Manual token overrides existing open request: {0}", idByToken); } } exchange.setObserver(exchangeObserver); exchangeStore.registerOutboundRequestWithTokenOnly(exchange); LOGGER.log(Level.FINE, "Tracking open request using {0}", new Object[] { request.getTokenString() }); if (request.getOptions().hasObserve() && request.getOptions().getObserve() == 0) { startObserve(request); } }

Target:
public void sendRequest(Exchange exchange, final Request request) { exchange.setObserver(exchangeObserver); exchangeStore.registerOutboundRequestWithTokenOnly(exchange); LOGGER.log(Level.FINE, "Tracking open request using {0}", new Object[] { request.getTokenString() }); if (request.getOptions().hasObserve() && request.getOptions().getObserve() == 0) { registerObserve(request); } }
Source:
public String toString() { return "Dashboard{" + "uid='" + uid + '\'' + ", title='" + title + '\'' + ", uri='" + uri + '\'' + ", url='" + url + '\'' + ", panels=" + panels + ", tags=" + tags + ", meta=" + meta + '}'; }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("uid", uid) .add("title", title) .add("uri", uri) .add("url", url) .add("panels", panels) .add("tags", tags) .add("meta", meta) .toString(); }
Source:
public void testFederateGetEmptyResults() throws Exception { List<String> sourceIds = ImmutableList.of("1"); QueryRequest fedQueryRequest = new QueryRequestImpl(mockQuery, false, sourceIds, properties); List<Source> sourceList = ImmutableList.of(); when(mockResponse.getHits()).thenReturn((long) sourceList.size()); QueryResponse federateResponse = federateStrategy.federate(sourceList, fedQueryRequest); assertThat(federateResponse.getResults().size(), is(0)); }

Target:
public void testFederateGetEmptyResults() throws Exception { QueryRequest fedQueryRequest = new QueryRequestImpl(mockQuery, false, null, properties); List<Source> sourceList = ImmutableList.of(); QueryResponse federateResponse = federateStrategy.federate(sourceList, fedQueryRequest); assertThat(federateResponse.getResults().size(), is(0)); }
Source:
private static int tableSize(final DfsBlockCacheConfig cfg) { final int wsz = cfg.getBlockSize(); final long limit = cfg.getBlockLimit(); if (wsz <= 0) throw new IllegalArgumentException(JGitText.get().invalidWindowSize); if (limit < wsz) throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit); return (int) Math.min(5 * (limit / wsz) / 2, 2000000000); }

Target:
private static int tableSize(final DfsBlockCacheConfig cfg) { final int wsz = cfg.getBlockSize(); final long limit = cfg.getBlockLimit(); if (wsz <= 0) throw new IllegalArgumentException(JGitText.get().invalidWindowSize); if (limit < wsz) throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit); return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE); }
Source:
public static ITmfTimestampTransform createLinearFast(BigDecimal factor, BigDecimal offset) { return new TmfTimestampTransformLinearFast(new TmfTimestampTransformLinear(factor, offset)); }

Target:
public static ITmfTimestampTransform createLinearFast(BigDecimal factor, BigDecimal offset) { return new TmfTimestampTransformLinearFast(factor, offset); }
Source:
protected void finalize() throws Throwable { Task faultedTask = this.task; if (faultedTask != null) { Task.UnobservedExceptionHandler ueh = Task.getUnobservedExceptionHandler(); if (ueh != null) { ueh.unobservedException(faultedTask, new UnobservedTaskException(faultedTask.getError())); } } }

Target:
protected void finalize() throws Throwable { try { Task faultedTask = this.task; if (faultedTask != null) { Task.UnobservedExceptionHandler ueh = Task.getUnobservedExceptionHandler(); if (ueh != null) { ueh.unobservedException(faultedTask, new UnobservedTaskException(faultedTask.getError())); } } } finally { super.finalize(); } }
Source:
public void changeCourseIdInForm(int instrNum, String newCourseId) { String selector = "$('#edit-" + instrNum + "').find('[name=\"" + Const.ParamsNames.COURSE_ID + "\"]')"; String action = ".val('" + newCourseId + "')"; ((JavascriptExecutor) browser.driver).executeScript(selector + action); }

Target:
public void changeCourseIdInForm(int instrNum, String newCourseId) { String selector = "$('#edit-" + instrNum + " input[name=\"" + Const.ParamsNames.COURSE_ID + "\"]')"; String action = ".val('" + newCourseId + "')"; ((JavascriptExecutor) browser.driver).executeScript(selector + action); }
Source:
public void makeButton(FormEntryPrompt prompt){ setOrientation(LinearLayout.VERTICAL); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); launchIntentButton = new Button(getContext()); setButtonLabel(); launchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); launchIntentButton.setPadding(20, 20, 20, 20); launchIntentButton.setEnabled(!prompt.isReadOnly()); launchIntentButton.setLayoutParams(params); String s = prompt.getAnswerText(); if (s != null) { launchIntentButton.setText(StringUtils.getStringSpannableRobust(getContext(), R.string.intent_callout_button_update)); } launchIntentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performCallout(); } }); addView(launchIntentButton); }

Target:
public void makeButton(FormEntryPrompt prompt){ setOrientation(LinearLayout.VERTICAL); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); launchIntentButton = new Button(getContext()); String s = prompt.getAnswerText(); Spannable label; if (s != null) { label = StringUtils.getStringSpannableRobust(getContext(), R.string.intent_callout_button_update); } else{ label = StringUtils.getStringSpannableRobust(getContext(), R.string.intent_callout_button); } WidgetUtils.setupButton(launchIntentButton, label, mAnswerFontsize, !prompt.isReadOnly()); launchIntentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performCallout(); } }); addView(launchIntentButton); }
Source:
public void testBackgroundLatencyUnSleep() throws Exception { server.stop(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); ((CuratorFrameworkImpl)client).sleepAndQueueOperationSeconds = Integer.MAX_VALUE; final CountDownLatch latch = new CountDownLatch(1); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; client.create().inBackground(callback).forPath("/test"); server.restart(); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(client); } }

Target:
public void testBackgroundLatencyUnSleep() throws Exception { server.stop(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); ((CuratorFrameworkImpl)client).sleepAndQueueOperationSeconds = Integer.MAX_VALUE; final CountDownLatch latch = new CountDownLatch(3); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if ( (event.getType() == CuratorEventType.CREATE) && (event.getResultCode() == KeeperException.Code.OK.intValue()) ) { latch.countDown(); } } }; client.create().inBackground(callback).forPath("/test"); client.create().inBackground(callback).forPath("/test/one"); client.create().inBackground(callback).forPath("/test/two"); server.restart(); Assert.assertTrue(timing.awaitLatch(latch)); } finally { CloseableUtils.closeQuietly(client); } }
Source:
public LogViewerController(Map conf) { port = Optional.fromNullable((Number) conf.get(Config.LOGVIEWER_PORT)).or(8000).intValue(); setUrlDetector(new SocketUrlDetection(port)); logdir = System.getenv("MESOS_SANDBOX") + "/logs"; if (conf.containsKey(STORM_LOG_DIR_CONF)) { logdir = (String) conf.get(STORM_LOG_DIR_CONF); } }

Target:
public LogViewerController(Map conf) { port = Optional.fromNullable((Number) conf.get(Config.LOGVIEWER_PORT)).or(8000).intValue(); setUrlDetector(new SocketUrlDetection(port)); logDir = MesosCommon.getStormLogDir(conf, System.getenv("MESOS_SANDBOX") + "/logs"); }
Source:
private static void encodeV1(HAProxyMessage msg, ByteBuf out) { final String protocol = msg.proxiedProtocol().name(); StringBuilder sb = new StringBuilder(108) .append("PROXY ").append(protocol).append(' ') .append(msg.sourceAddress()).append(' ') .append(msg.destinationAddress()).append(' ') .append(msg.sourcePort()).append(' ').append(msg.destinationPort()).append("\r\n"); out.writeBytes(sb.toString().getBytes(CharsetUtil.US_ASCII)); }

Target:
private static void encodeV1(HAProxyMessage msg, ByteBuf out) { out.writeBytes(TEXT_PREFIX); out.writeByte((byte) ' '); out.writeCharSequence(msg.proxiedProtocol().name(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(String.valueOf(msg.sourcePort()), CharsetUtil.US_ASCII); out.writeByte((byte) ' '); out.writeCharSequence(String.valueOf(msg.destinationPort()), CharsetUtil.US_ASCII); out.writeByte((byte) '\r'); out.writeByte((byte) '\n'); }
Source:
protected void setup(Context context) throws IOException, InterruptedException { String moduleClassName = context.getConfiguration().get(EXPORT_ACTION_BUILDER_FACTORY_CLASSNAME); if (StringUtils.isNotBlank(moduleClassName)) { try { Class<?> clazz = Class.forName(moduleClassName); Constructor<?> constructor = clazz.getConstructor(); ActionBuilderFactory<SpecificRecordBase, Oaf> actionBuilderFactory = (ActionBuilderFactory<SpecificRecordBase, Oaf>) constructor.newInstance(); actionBuilder = actionBuilderFactory.instantiate(context.getConfiguration()); objectMapper = new ObjectMapper(); } catch (Exception e) { throw new RuntimeException("unexpected exception ocurred when instantiating " + "builder module: " + moduleClassName, e); } } else { throw new InvalidParameterException("unknown action builder module instance, " + "no " + EXPORT_ACTION_BUILDER_FACTORY_CLASSNAME + " parameter provided!"); } }

Target:
protected void setup(Context context) throws IOException, InterruptedException { String moduleClassName = context.getConfiguration().get(EXPORT_ACTION_BUILDER_FACTORY_CLASSNAME); if (StringUtils.isNotBlank(moduleClassName)) { try { Class<?> clazz = Class.forName(moduleClassName); Constructor<?> constructor = clazz.getConstructor(); ActionBuilderFactory<SpecificRecordBase, Oaf> actionBuilderFactory = (ActionBuilderFactory<SpecificRecordBase, Oaf>) constructor.newInstance(); actionBuilder = actionBuilderFactory.instantiate(context.getConfiguration()); } catch (Exception e) { throw new RuntimeException("unexpected exception ocurred when instantiating " + "builder module: " + moduleClassName, e); } } else { throw new InvalidParameterException("unknown action builder module instance, " + "no " + EXPORT_ACTION_BUILDER_FACTORY_CLASSNAME + " parameter provided!"); } }
Source:
public boolean accepts(ModelNode response) { if (response.hasDefined(RESULT)) { final ModelNode result = response.get(RESULT); if (result.hasDefined(STEP_1)) { final List<Property> steps = result.asPropertyList(); for (Property step : steps) { final ModelNode stepContent = step.getValue(); if (stepContent.hasDefined(RESPONSE_HEADERS) && stepContent.get(RESPONSE_HEADERS).hasDefined(WARNINGS)) { return true; } } } } return false; }

Target:
public boolean accepts(ModelNode response) { if (response.hasDefined(RESPONSE_HEADERS)) { final ModelNode result = response.get(RESPONSE_HEADERS); if (result.hasDefined(WARNINGS)) { return true; } } return false; }
Source:
private static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { Iterable<String> ips = new HashSet<String>(); if(allowedInterfaces.scanPublic){ ips = concat(ips, node.getPublicAddresses()); } if(allowedInterfaces.scanPrivate){ ips = concat(ips, node.getPrivateAddresses()); } checkState(size(ips) > 0, "node does not have IP addresses configured: " + node); return FluentIterable.from(ips); }

Target:
static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); }
Source:
private static String getPackageNameToUse(Context context) { List<String> browserWithCustomTabsSupport = getBrowserWithCustomTabsSupport(context); String defaultBrowser = getDefaultBrowser(context); for (String browser : browserWithCustomTabsSupport) { if (browser.equals(defaultBrowser)) { return browser; } } return browserWithCustomTabsSupport.get(0); }

Target:
private static String getPackageNameToUse(Context context) { List<String> browsersWithCustomTabsSupport = getBrowsersWithCustomTabsSupport(context); String defaultBrowser = getDefaultBrowser(context); for (String browser : browsersWithCustomTabsSupport) { if (TextUtils.equals(browser, defaultBrowser)) { return browser; } } if (browsersWithCustomTabsSupport.isEmpty()) { return null; } return browsersWithCustomTabsSupport.get(0); }
Source:
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { if (value instanceof Map) { Map<?, ?> map = (Map<?, ?>) value; for (Object obj : map.entrySet()) { Entry<?, ?> entry = (Entry<?, ?>) obj; writer.startNode(entry.getKey().toString()); marshal(entry.getValue(), writer, context); writer.endNode(); } } else if (value instanceof List) { List<?> list = (List<?>) value; for (Object obj : list) { marshal(obj, writer, context); } } else if (value instanceof Hyperlink) { Hyperlink hl = (Hyperlink)value; writer.startNode("link"); writer.startNode("rel"); writer.setValue(hl.getRel()); writer.endNode(); writer.startNode("uri"); writer.setValue(hl.getUri()); writer.endNode(); writer.endNode(); } else { writer.setValue(value.toString()); } }

Target:
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { if (value instanceof Map) { Map<?, ?> map = (Map<?, ?>) value; for (Object obj : map.entrySet()) { Entry<?, ?> entry = (Entry<?, ?>) obj; writer.startNode(entry.getKey().toString()); marshal(entry.getValue(), writer, context); writer.endNode(); } } else if (value instanceof List) { List<?> list = (List<?>) value; for (Object obj : list) { if (obj instanceof SimpleObject) { Hyperlink self = getSelfLink((SimpleObject) obj); writer.startNode(self.getResourcePath()); } marshal(obj, writer, context); if (obj instanceof SimpleObject) { writer.endNode(); } } } else if (value instanceof Hyperlink) { writeItem(value, context, writer); } else if (value != null) { writer.setValue(value.toString()); } }
Source:
public void time(Runnable timeable){ Histogram.Timer timer = startTimer(); try { timeable.run(); } finally { timer.observeDuration(); } }

Target:
public double time(Runnable timeable){ return noLabelsChild.time(timeable); }
Source:
public String suggestCountryForUser(Integer userId) { Validate.isTrue(userId != null, "User id must be non null"); String slug = countryDao.findCountryOfLastCreatedSeriesByUser(userId); if (slug != null) { log.info( "Country has been suggested to user #{} from a recently created series", slug, userId ); return slug; } slug = countryDao.findLastCountryCreatedByUser(userId); if (slug != null) { LOG.info( "Country has been suggested to user #{} from a last created country", slug, userId ); return slug; } slug = countryDao.findPopularCountryInCollection(userId); if (slug != null) { log.info( "Country has been suggested to user #{} as popular in his collection", slug, userId ); } return slug; }

Target:
public String suggestCountryForUser(Integer userId) { Validate.isTrue(userId != null, "User id must be non null"); String slug = countryDao.findCountryOfLastCreatedSeriesByUser(userId); if (slug != null) { log.info( "Country has been suggested to user #{} from a recently created series", slug, userId ); return slug; } slug = countryDao.findLastCountryCreatedByUser(userId); if (slug != null) { log.info( "Country has been suggested to user #{} as it was created by him recently", slug, userId ); return slug; } slug = countryDao.findPopularCountryInCollection(userId); if (slug != null) { log.info( "Country has been suggested to user #{} as popular in his collection", slug, userId ); } return slug; }
Source:
public void checkExecuteCommandWithNullVdsId() { parameters.setStorageServerConnection(NFSConnection); parameters.setVdsId(null); doNothing().when(storageServerConnectionDAO).remove(NFSConnection.getid()); command.executeCommand(); }

Target:
public void checkExecuteCommandWithNullVdsId() { parameters.setStorageServerConnection(NFSConnection); parameters.setVdsId(null); doNothing().when(storageServerConnectionDAO).remove(NFSConnection.getid()); command.executeCommand(); verify(command, never()).disconnectStorage(); }