auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static <T extends ExecutorService> T notShutdown(final T executorService) { if (executorService.isShutdown()) { throw new IllegalArgumentException("executorService may not be shutdown"); } return executorService; }

Target:
private static <T extends ExecutorService> T notShutdown(final T executorService) { if (executorService.isShutdown()) { final String message = "executorService may not be shutdown"; LOGGER.debug(message); throw new IllegalArgumentException(message); } return executorService; }
Source:
public void showDeleteAlertDialog(final int index) { AlertDialog.Builder openDialog = new AlertDialog.Builder(this); openDialog.setTitle(R.string.action_delete_claim_confirm); openDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(checkFilteredTags()) { ExpenseClaim removedClaim = filteredListModel.getItems().get(index); filteredListModel.remove(index); listModel.remove(removedClaim); } else { listModel.remove(index); } } }); openDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); openDialog.show(); }

Target:
public void showDeleteAlertDialog(final int index) { AlertDialog.Builder openDialog = new AlertDialog.Builder(this); openDialog.setTitle(R.string.action_delete_claim_confirm); openDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!filteredTagsList.isEmpty()) { ExpenseClaim removedClaim = filteredListModel.getItems().get(index); filteredListModel.remove(index); listModel.remove(removedClaim); } else { listModel.remove(index); } } }); openDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); openDialog.show(); }
Source:
public String getHttp(String urlToRead, String username, String password) throws Exception { URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if(username != null) { String userpass = username + ":" + password; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); conn.setRequestProperty ("Authorization", basicAuth); } conn.setRequestMethod("GET"); return IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8.name()); }

Target:
public String getHttp(String urlToRead, String username, String password) throws Exception { URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (username != null) { String userpass; if (StringUtils.isEmpty(password)) { userpass = username; } else { userpass = username + ":" + password; } String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); conn.setRequestProperty("Authorization", basicAuth); } conn.setRequestMethod("GET"); return IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8.name()); }
Source:
private boolean isInSubnet(RedisURI redisURI) { if (LettuceStrings.isEmpty(redisURI.getHost())) { return false; } InetSocketAddress address = SocketUtils.socketAddress(redisURI.getHost(), redisURI.getPort()); for (IpSubnetFilterRule rule : rules) { if (rule.matches(address)) { return true; } } return false; }

Target:
private boolean isInSubnet(RedisURI redisURI) { String host = redisURI.getHost(); if (LettuceStrings.isEmpty(host)) { return false; } LettuceAssert.isTrue(NetUtil.isValidIpV4Address(host) || NetUtil.isValidIpV6Address(host), "ReadFromSubnet supports only IP address-style redisURI. host=" + host); InetSocketAddress address; try { address = new InetSocketAddress(InetAddress.getByName(host), redisURI.getPort()); } catch (UnknownHostException e) { throw new IllegalStateException("Should not reach here. host=" + host, e); } for (IpSubnetFilterRule rule : rules) { if (rule.matches(address)) { return true; } } return false; }
Source:
public PartitionStatistics getTableStatistics(String databaseName, String tableName) { try { Table table = getTable(databaseName, tableName) .orElseThrow(() -> new PrestoException(HIVE_METASTORE_ERROR, String.format("Could not retrieve table %s.%s", databaseName, tableName))); HiveBasicStatistics basicStats = ThriftMetastoreUtil.getHiveBasicStatistics(table.getParameters()); return new PartitionStatistics(basicStats, Collections.emptyMap()); } catch (Exception e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }

Target:
public PartitionStatistics getTableStatistics(String databaseName, String tableName) { try { Table table = getTable(databaseName, tableName).orElseThrow(() -> new PrestoException( HIVE_METASTORE_ERROR, String.format("Could not retrieve table %s.%s", databaseName, tableName))); HiveBasicStatistics basicStats = ThriftMetastoreUtil.getHiveBasicStatistics(table.getParameters()); return new PartitionStatistics(basicStats, ImmutableMap.of()); } catch (Exception e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
private boolean isInsideSelection(ICPPASTCompositeTypeSpecifier node) { IASTFileLocation location = node.getFileLocation(); if (location == null) { return false; } if (fSelection == null) { String elName = new String(node.getName().getSimpleID()); if (elName.equals(fElementName)) return true; return false; } if (location.getNodeOffset() <= fSelection.getOffset() && fSelection.getOffset() <= location.getNodeOffset() + location.getNodeLength() && location.getFileName().contains(fFileName)) { return true; } else { return false; } }

Target:
private boolean isInsideSelection(ICPPASTCompositeTypeSpecifier node) { IASTFileLocation location = node.getFileLocation(); if (location == null) { return false; } if (fSelection == null) { IBinding binding = node.getName().resolveBinding(); if (!(binding instanceof ICPPBinding)) return false; try { String elName = String.join(IQualifiedTypeName.QUALIFIER, ((ICPPBinding) binding).getQualifiedName()); if (elName.equals(fElementName)) return true; } catch (DOMException e) { CUIPlugin.log(e); } return false; } if (location.getNodeOffset() <= fSelection.getOffset() && fSelection.getOffset() <= location.getNodeOffset() + location.getNodeLength() && location.getFileName().contains(fFileName)) { return true; } else { return false; } }
Source:
private List<Circuit> getCircuits(long timeoutValue, TimeUnit timeoutUnit, Set<Router> routers) throws InterruptedException { createThreadPool(routers.size()); try { List<ListenableFuture<Circuit>> circuitFutures = Lists.newArrayList(); final CountDownLatch doneSignal = new CountDownLatch(routers.size()); for (final Router router : routers) { ListenableFuture<Circuit> openCircuit = threadPool.submit(new Callable<Circuit>() { @Override public Circuit call() throws Exception { return torClient.getCircuitManager().openInternalCircuitTo(Lists.newArrayList(router)); } }); Futures.addCallback(openCircuit, new FutureCallback<Circuit>() { public void onSuccess(Circuit circuit) { doneSignal.countDown(); } public void onFailure(Throwable thrown) { doneSignal.countDown(); } }); circuitFutures.add(openCircuit); } boolean countedDown = doneSignal.await(torClient.getConfig().getCircuitBuildTimeout(), TimeUnit.MILLISECONDS); try { List<Circuit> circuits = new ArrayList<Circuit>(Futures.successfulAsList(circuitFutures).get()); circuits.removeAll(singleton(null)); int failures = routers.size() - circuits.size(); if (failures > 0) log.warn("{} failures " + (countedDown ? "" : "(including timeout) ") + "opening DNS lookup circuits", failures); return circuits; } catch (ExecutionException e) { throw new RuntimeException(e); } } finally { shutdownThreadPool(); } }

Target:
private List<Circuit> getCircuits(long timeoutValue, TimeUnit timeoutUnit, Set<Router> routers) throws InterruptedException { checkArgument(routers.size() >= MINIMUM_ROUTER_LOOKUP_COUNT, "Set of routers is smaller than required minimum {}", routers.size(), MINIMUM_ROUTER_LOOKUP_COUNT); createThreadPool(routers.size()); try { List<ListenableFuture<Circuit>> circuitFutures = Lists.newArrayList(); final CountDownLatch doneSignal = new CountDownLatch(MINIMUM_ROUTER_LOOKUP_COUNT); for (final Router router : routers) { ListenableFuture<Circuit> openCircuit = threadPool.submit(new Callable<Circuit>() { @Override public Circuit call() throws Exception { return torClient.getCircuitManager().openInternalCircuitTo(Lists.newArrayList(router)); } }); Futures.addCallback(openCircuit, new FutureCallback<Circuit>() { public void onSuccess(Circuit circuit) { doneSignal.countDown(); } public void onFailure(Throwable thrown) { doneSignal.countDown(); } }); circuitFutures.add(openCircuit); } boolean countedDown = doneSignal.await(timeoutValue, timeoutUnit); try { List<Circuit> circuits = new ArrayList<Circuit>(Futures.successfulAsList(circuitFutures).get()); circuits.removeAll(singleton(null)); int failures = routers.size() - circuits.size(); if (failures > 0) log.warn("{} failures " + (countedDown ? "" : "(including timeout) ") + "opening DNS lookup circuits", failures); return circuits; } catch (ExecutionException e) { throw new RuntimeException(e); } } finally { shutdownThreadPool(); } }
Source:
private static float absSP(float f) { return Math.abs(f); }

Target:
private static float $opt$noinline$absSP(float f) { if (doThrow) { throw new Error("Something to prevent inlining"); } return Math.abs(f); }
Source:
public static ProtoGrade getGrade(final Authenticator authenticator, final DB dbs, final String requesterId, final String userId, final String courseId, final String assignmentId, final String problemId) throws AuthenticationException, DatabaseAccessException { final Authenticator.AuthType auth = new Authenticator.AuthType(); if (requesterId.equals(userId)) { auth.setCheckUser(true); } else { auth.setCheckAdminOrMod(true); } if (!authenticator.isAuthenticated(COURSE_COLLECTION, courseId, requesterId, 0, auth)) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } final DBCollection gradeCollection = dbs.getCollection(GRADE_COLLECTION); final BasicDBObject query = new BasicDBObject(COURSE_ID, courseId).append(USER_ID, userId); if (assignmentId == null) { query.append(ASSIGNMENT_ID, new BasicDBObject(EXISTS, false)); } else { query.append(ASSIGNMENT_ID, assignmentId); } if (problemId == null) { query.append(COURSE_PROBLEM_ID, new BasicDBObject(EXISTS, false)); } else { query.append(COURSE_PROBLEM_ID, problemId); } final DBCursor cursor = gradeCollection.find(query); if (!cursor.hasNext()) { throw new DatabaseAccessException("Did not find a grade matching those parameters for that student in course " + courseId); } return buildProtoGrade(cursor.next()); }

Target:
static ProtoGrade getGrade(final Authenticator authenticator, final DB dbs, final String requesterId, final String userId, final String courseId, final String assignmentId, final String problemId) throws AuthenticationException, DatabaseAccessException { final Authenticator.AuthType auth = new Authenticator.AuthType(); if (requesterId.equals(userId)) { auth.setCheckUser(true); } else { auth.setCheckAdminOrMod(true); } if (!authenticator.isAuthenticated(COURSE_COLLECTION, courseId, requesterId, 0, auth)) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } final DBCollection gradeCollection = dbs.getCollection(GRADE_COLLECTION); final BasicDBObject query = new BasicDBObject(COURSE_ID, courseId).append(USER_ID, userId); if (assignmentId != null) { query.append(ASSIGNMENT_ID, assignmentId); } else { query.append(ASSIGNMENT_ID, new BasicDBObject(EXISTS, false)); } if (problemId != null) { query.append(COURSE_PROBLEM_ID, problemId); } else { query.append(COURSE_PROBLEM_ID, new BasicDBObject(EXISTS, false)); } final DBCursor cursor = gradeCollection.find(query); if (!cursor.hasNext()) { throw new DatabaseAccessException("Did not find a grade matching those parameters for that student in course: " + courseId); } return buildProtoGrade(cursor.next()); }
Source:
public void updateInstanceAssignment(String instance, List<DatastreamTask> assignments) { LOG.info("Updating datastream tasks assigned for instance: " + instance + ", new assignments are: " + tasksToString(assignments)); Set<String> assignmentsNames = new HashSet<>(); Map<String, DatastreamTask> assignmentsMap = new HashMap<>(); assignments.forEach(task -> { String name = task.getDatastreamTaskName(); assignmentsNames.add(name); assignmentsMap.put(name, task); }); Set<String> oldAssignmentNames = new HashSet<>(_zkclient.getChildren(KeyBuilder.instance(_cluster, instance))); Set<String> removed = new HashSet<>(oldAssignmentNames); removed.removeAll(assignmentsNames); if (removed.size() > 0) { removed.forEach(name -> { String path = KeyBuilder.datastreamTask(_cluster, instance, name); _zkclient.delete(path); }); } Set<String> added = new HashSet<>(assignmentsNames); added.removeAll(oldAssignmentNames); if (added.size() > 0) { added.forEach(name -> { DatastreamTask task = assignmentsMap.get(name); String path = KeyBuilder.datastreamTask(_cluster, instance, name); try { _zkclient.create(path, task.toJson(), CreateMode.PERSISTENT); } catch (IOException e) { LOG.error("Failed to assign task [" + name + "] to instance " + instance + ", error: " + e.getMessage()); } }); } }

Target:
public void updateInstanceAssignment(String instance, List<DatastreamTask> assignments) { LOG.info("Updating datastream tasks assigned for instance: " + instance + ", new assignments are: " + tasksToString(assignments)); Set<String> assignmentsNames = new HashSet<>(); Map<String, DatastreamTask> assignmentsMap = new HashMap<>(); assignments.forEach(task -> { String name = task.getDatastreamTaskName(); assignmentsNames.add(name); assignmentsMap.put(name, task); }); Set<String> oldAssignmentNames = new HashSet<>(_zkclient.getChildren(KeyBuilder.instance(_cluster, instance))); Set<String> removed = new HashSet<>(oldAssignmentNames); removed.removeAll(assignmentsNames); if (removed.size() > 0) { LOG.info("Instance: " + instance + ", removing assignments: " + setToString(removed)); removed.forEach(name -> { String path = KeyBuilder.datastreamTask(_cluster, instance, name); _zkclient.delete(path); }); } Set<String> added = new HashSet<>(assignmentsNames); added.removeAll(oldAssignmentNames); if (added.size() > 0) { LOG.info("Instance: " + instance + ", adding assignments: " + setToString(added)); added.forEach(name -> { DatastreamTask task = assignmentsMap.get(name); String path = KeyBuilder.datastreamTask(_cluster, instance, name); try { _zkclient.create(path, task.toJson(), CreateMode.PERSISTENT); } catch (IOException e) { LOG.error("Failed to assign task [" + name + "] to instance " + instance + ", error: " + e.getMessage()); } }); } }
Source:
public double fxRate(Currency baseCurrency, Currency counterCurrency, int scenarioIndex) { if (baseCurrency.equals(counterCurrency)) { return 1d; } if (baseCurrency.equals(pair.getBase()) && counterCurrency.equals(pair.getCounter())) { return rates.get(scenarioIndex); } if (counterCurrency.equals(pair.getBase()) && baseCurrency.equals(pair.getCounter())) { return 1d / rates.get(scenarioIndex); } throw new IllegalArgumentException("Unknown rate: " + baseCurrency + "/" + counterCurrency); }

Target:
public double fxRate(Currency baseCurrency, Currency counterCurrency, int scenarioIndex) { if (baseCurrency.equals(pair.getBase()) && counterCurrency.equals(pair.getCounter())) { return rates.get(scenarioIndex); } if (counterCurrency.equals(pair.getBase()) && baseCurrency.equals(pair.getCounter())) { return 1d / rates.get(scenarioIndex); } throw new IllegalArgumentException("Unknown rate: " + baseCurrency + "/" + counterCurrency); }
Source:
public TenantIdentityMgtClient(String cookie, String backendServerURL, ConfigurationContext configContext) throws Exception { try { stub = new UserIdentityManagementAdminServiceStub(configContext, backendServerURL + "UserIdentityManagementAdminService"); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while creating TenantIdentityMgtClient Object"); } }

Target:
public TenantIdentityMgtClient(String cookie, String backendServerURL, ConfigurationContext configContext) throws Exception { try { stub = new UserIdentityManagementAdminServiceStub(configContext, backendServerURL + "UserIdentityManagementAdminService"); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (Exception e) { throw new Exception("Error occurred while creating TenantIdentityMgtClient Object"); } }
Source:
private Set<DistributedEvent> mapDistributedEvents(Set<DefinitionsEvent> notification) { if (notification == null) { return null; } Set<DistributedEvent> events = new HashSet<>(); for (DefinitionsEvent definitionsEvent : notification) { DistributedEvent.Operation op = null; String tenantId = definitionsEvent.getTargetTenantId(); String triggerId = definitionsEvent.getTargetId(); switch (definitionsEvent.getType()) { case TRIGGER_CREATE: op = DistributedEvent.Operation.ADD; break; case TRIGGER_UPDATE: op = DistributedEvent.Operation.UPDATE; break; case TRIGGER_REMOVE: op = DistributedEvent.Operation.REMOVE; break; case TRIGGER_CONDITION_CHANGE: op = DistributedEvent.Operation.UPDATE; break; } if (op != null) { events.add(new DistributedEvent(op, tenantId, triggerId)); } } return events; }

Target:
private Set<DistributedEvent> mapDistributedEvents(Set<DefinitionsEvent> notification) { if (notification == null) { return null; } Set<DistributedEvent> events = new LinkedHashSet<>(); for (DefinitionsEvent definitionsEvent : notification) { DistributedEvent.Operation op = null; String tenantId = definitionsEvent.getTargetTenantId(); String triggerId = definitionsEvent.getTargetId(); switch (definitionsEvent.getType()) { case TRIGGER_CREATE: op = DistributedEvent.Operation.ADD; break; case TRIGGER_UPDATE: op = DistributedEvent.Operation.UPDATE; break; case TRIGGER_REMOVE: op = DistributedEvent.Operation.REMOVE; break; case TRIGGER_CONDITION_CHANGE: op = DistributedEvent.Operation.UPDATE; break; } if (op != null) { events.add(new DistributedEvent(op, tenantId, triggerId)); } } return events; }
Source:
private void updateTreeViewerToLevel() { fTreeViewer.refresh(); fTreeViewer.expandToLevel(getIndex()); }

Target:
private void updateTreeViewerToLevel() { final Object[] elements = fTreeViewer.getExpandedElements(); fTreeViewer.refresh(); fTreeViewer.setExpandedElements(elements); }
Source:
public TaskResult run() { Config params = request.getConfig(); Config doConfig = request.getConfig().getNested("_do"); int count = params.get("count", int.class, params.get("_command", int.class)); if (count > context.getMaxWorkflowTasks()) { throw new ConfigException("Too many loop subtasks. Limit: " + context.getMaxWorkflowTasks()); } Config generated = doConfig.getFactory().create(); for (int i = 0; i < count; i++) { Config subtask = params.getFactory().create(); subtask.setAll(doConfig); subtask.getNestedOrSetEmpty("_export").set("i", i); generated.set( String.format(ENGLISH, "+loop-%d", i), subtask); } if (ParallelControl.of(params).isParallel()) { generated.set("_parallel", params.get("_parallel", JsonNode.class)); } return TaskResult.defaultBuilder(request) .subtaskConfig(generated) .build(); }

Target:
public TaskResult run() { Config params = request.getConfig(); Config doConfig = request.getConfig().getNested("_do"); int count = params.get("count", int.class, params.get("_command", int.class)); if (count > context.getMaxWorkflowTasks()) { throw new ConfigException("Too many loop subtasks. Limit: " + context.getMaxWorkflowTasks()); } Config generated = doConfig.getFactory().create(); for (int i = 0; i < count; i++) { Config subtask = params.getFactory().create(); subtask.setAll(doConfig); subtask.getNestedOrSetEmpty("_export").set("i", i); generated.set( String.format(ENGLISH, "+loop-%d", i), subtask); } ParallelControl.of(params).copyIfNeeded(generated); return TaskResult.defaultBuilder(request) .subtaskConfig(generated) .build(); }
Source:
public void onSave(ManufacturerDto manufacturerDto) { ErrorHandlerAsyncCallback<GetResult<ManufacturerDto>> callback = new ErrorHandlerAsyncCallback<GetResult<ManufacturerDto>>(this) { @Override public void onSuccess(GetResult<ManufacturerDto> result) { DisplayMessageEvent.fire(EditManufacturerPresenter.this, new Message(messages.manufacturerSaved(), MessageStyle.SUCCESS)); ManufacturerAddedEvent.fire(EditManufacturerPresenter.this, result.getResult()); getView().hide(); } }; Action<GetResult<ManufacturerDto>> action; if (manufacturerDto.isSaved()) { action = manufacturerService.save(manufacturerDto.getId(), manufacturerDto); } else { action = manufacturerService.create(manufacturerDto); } dispatcher.execute(action, callback); }

Target:
public void onSave(ManufacturerDto manufacturerDto) { dispatcher.execute(manufacturerService.saveOrCreate(manufacturerDto), new ErrorHandlerAsyncCallback<GetResult<ManufacturerDto>>(this) { @Override public void onSuccess(GetResult<ManufacturerDto> result) { DisplayMessageEvent.fire(EditManufacturerPresenter.this, new Message(messages.manufacturerSaved(), MessageStyle.SUCCESS)); ManufacturerAddedEvent.fire(EditManufacturerPresenter.this, result.getResult()); getView().hide(); } }); }
Source:
public static void addDeclIfNew(Map<String, String> decls, String prefix, String uri) { if (!decls.containsKey(prefix)) { decls.put(prefix, uri); } else { final String currentUri = decls.get(prefix); if (!currentUri.equals(uri)) { log.warn("Prefix {}: <{}> is already declared, and will not be overwritten with <{}>", prefix, currentUri, uri); } } }

Target:
public static void addDeclIfNew(Map<String, String> decls, String prefix, String uri) { if (!decls.containsKey(prefix)) { decls.put(prefix, uri); } }
Source:
private String getNewVarName(){ String varName = "sd_var_" + _var_id.toString(); while(variableMap.containsKey(varName)){ _var_id++; varName = "sd_var_" + _var_id.toString(); } return varName; }

Target:
private String getNewVarName(){ String varName = "sd_var_" + String.valueOf(_var_id); while(variableMap.containsKey(varName)){ _var_id++; varName = "sd_var_" + String.valueOf(_var_id); } return varName; }
Source:
protected void channelRead0( ChannelHandlerContext channelHandlerContext, PrepareStoreCopyRequest prepareStoreCopyRequest ) throws Exception { CloseablesListener closeablesListener = new CloseablesListener(); try { NeoStoreDataSource neoStoreDataSource = dataSourceSupplier.get(); if ( !storeIdMatchesLocal( prepareStoreCopyRequest.getStoreId(), neoStoreDataSource ) ) { sendStoreIdMismatchMessage( channelHandlerContext ); return; } CheckPointer checkPointer = checkPointerSupplier.get(); closeablesListener.sample( tryCheckpointAndAcquireMutex( checkPointer ) ); PrepareStoreCopyFiles prepareStoreCopyFiles = closeablesListener.sample( prepareStoreCopyFilesProvider.prepareStoreCopyFiles( neoStoreDataSource ) ); StoreResource[] nonReplayable = prepareStoreCopyFiles.getAtomicFilesSnapshot(); for ( StoreResource storeResource : nonReplayable ) { streamingProtocol.stream( channelHandlerContext, storeResource ); } channelHandlerContext.write( ResponseMessageType.PREPARE_STORE_COPY_RESPONSE ); PrepareStoreCopyResponse success = createSuccessfulResponse( checkPointer, prepareStoreCopyFiles ); channelHandlerContext.writeAndFlush( success ).addListener( closeablesListener ); } catch ( Throwable e ) { channelHandlerContext.writeAndFlush( PrepareStoreCopyResponse.error( PrepareStoreCopyResponse.Status.E_LISTING_STORE ) ).addListener( closeablesListener ); } finally { protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }

Target:
protected void channelRead0( ChannelHandlerContext channelHandlerContext, PrepareStoreCopyRequest prepareStoreCopyRequest ) throws IOException { CloseablesListener closeablesListener = new CloseablesListener(); PrepareStoreCopyResponse response = PrepareStoreCopyResponse.error( PrepareStoreCopyResponse.Status.E_LISTING_STORE ); try { NeoStoreDataSource neoStoreDataSource = dataSourceSupplier.get(); if ( !hasSameStoreId( prepareStoreCopyRequest.getStoreId(), neoStoreDataSource ) ) { channelHandlerContext.write( ResponseMessageType.PREPARE_STORE_COPY_RESPONSE ); response = PrepareStoreCopyResponse.error( PrepareStoreCopyResponse.Status.E_STORE_ID_MISMATCH ); } else { CheckPointer checkPointer = checkPointerSupplier.get(); closeablesListener.add( tryCheckpointAndAcquireMutex( checkPointer ) ); PrepareStoreCopyFiles prepareStoreCopyFiles = closeablesListener.add( prepareStoreCopyFilesProvider.prepareStoreCopyFiles( neoStoreDataSource ) ); StoreResource[] nonReplayable = prepareStoreCopyFiles.getAtomicFilesSnapshot(); for ( StoreResource storeResource : nonReplayable ) { streamingProtocol.stream( channelHandlerContext, storeResource ); } channelHandlerContext.write( ResponseMessageType.PREPARE_STORE_COPY_RESPONSE ); response = createSuccessfulResponse( checkPointer, prepareStoreCopyFiles ); } } finally { channelHandlerContext.writeAndFlush( response ).addListener( closeablesListener ); protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }
Source:
private int tryExecute(final Runnable runnable) { QNode tailNext; TaskNode tail = this.tail; TaskNode node = null; for (;;) { tailNext = tail.getNext(); if (tailNext instanceof PoolThreadNode) { final QNode tailNextNext = tailNext.getNext(); if (tail.compareAndSetNext(tailNext, tailNextNext)) { assert tail instanceof TaskNode; PoolThreadNode consumerNode = (PoolThreadNode) tailNext; if (consumerNode.compareAndSetTask(WAITING, runnable)) { consumerNode.compareAndSetNext(tailNextNext, null); consumerNode.unpark(); return EXE_OK; } } } else if (tailNext == null) { int tr = tryAllocateThread(growthResistance); if (tr == AT_YES) { return EXE_CREATE_THREAD; } if (tr == AT_SHUTDOWN) { return EXE_REJECT_SHUTDOWN; } assert tr == AT_NO; if (!NO_QUEUE_LIMIT && !increaseQueueSize()) { tr = tryAllocateThread(0.0f); if (tr == AT_YES) { return EXE_CREATE_THREAD; } if (tr == AT_SHUTDOWN) { return EXE_REJECT_SHUTDOWN; } assert tr == AT_NO; return EXE_REJECT_QUEUE_FULL; } if (node == null) { node = new TaskNode(runnable); } if (tail.compareAndSetNext(null, node)) { compareAndSetTail(tail, node); return EXE_OK; } if (!NO_QUEUE_LIMIT) decreaseQueueSize(); } else if (tailNext == tail) { } else if (tailNext instanceof TaskNode) { TaskNode tailNextTaskNode = (TaskNode) tailNext; if (compareAndSetTail(tail, tailNextTaskNode)) { tail = tailNextTaskNode; continue; } } else { assert tailNext instanceof TerminateWaiterNode; return EXE_REJECT_SHUTDOWN; } if (UPDATE_STATISTICS) spinMisses.increment(); tail = this.tail; } }

Target:
private int tryExecute(final Runnable runnable) { QNode tailNext; TaskNode tail = this.tail; TaskNode node = null; for (;;) { tailNext = tail.getNext(); if (tailNext == tail) { } else if (tailNext == null) { int tr = tryAllocateThread(growthResistance); if (tr == AT_YES) { return EXE_CREATE_THREAD; } if (tr == AT_SHUTDOWN) { return EXE_REJECT_SHUTDOWN; } assert tr == AT_NO; if (!NO_QUEUE_LIMIT && !increaseQueueSize()) { tr = tryAllocateThread(0.0f); if (tr == AT_YES) { return EXE_CREATE_THREAD; } if (tr == AT_SHUTDOWN) { return EXE_REJECT_SHUTDOWN; } assert tr == AT_NO; return EXE_REJECT_QUEUE_FULL; } if (node == null) { node = new TaskNode(runnable); } if (tail.compareAndSetNext(null, node)) { compareAndSetTail(tail, node); return EXE_OK; } if (!NO_QUEUE_LIMIT) decreaseQueueSize(); } else if (tailNext instanceof PoolThreadNode) { final QNode tailNextNext = tailNext.getNext(); if (tail.compareAndSetNext(tailNext, tailNextNext)) { assert tail instanceof TaskNode; PoolThreadNode consumerNode = (PoolThreadNode) tailNext; if (consumerNode.compareAndSetTask(WAITING, runnable)) { consumerNode.compareAndSetNext(tailNextNext, null); consumerNode.unpark(); return EXE_OK; } } } else if (tailNext instanceof TaskNode) { TaskNode tailNextTaskNode = (TaskNode) tailNext; if (compareAndSetTail(tail, tailNextTaskNode)) { tail = tailNextTaskNode; continue; } } else { assert tailNext instanceof TerminateWaiterNode; return EXE_REJECT_SHUTDOWN; } if (UPDATE_STATISTICS) spinMisses.increment(); tail = this.tail; } }
Source:
FileHeader(final byte[] b, final int offset) { changeType = ChangeType.MODIFY; buf = b; startOffset = offset; patchType = PatchType.UNIFIED; }

Target:
FileHeader(final byte[] b, final int offset) { buf = b; startOffset = offset; changeType = ChangeType.MODIFY; patchType = PatchType.UNIFIED; }
Source:
public void process(Context context, CompilationUnit cu) { if (whitelist == null) { return; } List<BodyDeclaration> matchingNodes = Lists.newArrayList(); cu.accept(new ASTVisitor() { @Override public boolean visit(EnumConstantDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(EnumDeclaration node) { return handleTypeDeclarationNode(node); } @Override public boolean visit(FieldDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(MethodDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(TypeDeclaration node) { return handleTypeDeclarationNode(node); } private boolean handleTypeDeclarationNode(AbstractTypeDeclaration node) { matchIfNotWhitelistedAndNotHidden(node); return true; } private boolean handleMemberDeclarationNode(BodyDeclaration node) { matchIfNotWhitelistedAndNotHidden(node); return false; } private void matchIfNotWhitelistedAndNotHidden(final BodyDeclaration node) { if (node == null) { return; } if (!RecordPublicApiRules.isPublicApiEligible(node)) { return; } if (BodyDeclarationLocators.matchesAny(whitelist, node)) { return; } matchingNodes.add(node); } }); Collections.sort(matchingNodes, new StartPositionComparator()); ASTRewrite rewrite = context.rewrite(); for (BodyDeclaration bodyDeclaration : Lists.reverse(matchingNodes)) { System.out.println("Victor: hide " + bodyDeclaration.toString()); JavadocUtils.addJavadocTag(rewrite, bodyDeclaration, tagComment); } }

Target:
public void process(Context context, CompilationUnit cu) { if (whitelist == null) { return; } List<BodyDeclaration> matchingNodes = Lists.newArrayList(); cu.accept(new ASTVisitor() { @Override public boolean visit(EnumConstantDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(EnumDeclaration node) { return handleTypeDeclarationNode(node); } @Override public boolean visit(FieldDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(MethodDeclaration node) { return handleMemberDeclarationNode(node); } @Override public boolean visit(TypeDeclaration node) { return handleTypeDeclarationNode(node); } private boolean handleTypeDeclarationNode(AbstractTypeDeclaration node) { matchIfNotWhitelistedAndNotHidden(node); return true; } private boolean handleMemberDeclarationNode(BodyDeclaration node) { matchIfNotWhitelistedAndNotHidden(node); return false; } private void matchIfNotWhitelistedAndNotHidden(final BodyDeclaration node) { if (node == null) { return; } if (!RecordPublicApiRules.isPublicApiEligible(node)) { return; } if (BodyDeclarationLocators.matchesAny(whitelist, node)) { return; } matchingNodes.add(node); } }); Collections.sort(matchingNodes, new StartPositionComparator()); ASTRewrite rewrite = context.rewrite(); for (BodyDeclaration bodyDeclaration : Lists.reverse(matchingNodes)) { JavadocUtils.addJavadocTag(rewrite, bodyDeclaration, tagComment); } }
Source:
private FileSystemOptions initializeFsOptions(PluginTask task) { FileSystemOptions fsOptions = new FileSystemOptions(); try { SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance(); builder.setUserDirIsRoot(fsOptions, task.getUserDirIsRoot()); builder.setTimeout(fsOptions, task.getSftpConnectionTimeout() * 1000); builder.setStrictHostKeyChecking(fsOptions, "no"); if (task.getSecretKeyFilePath().isPresent()) { IdentityInfo identityInfo = new IdentityInfo( new File((task.getSecretKeyFilePath().map(localFileToPathString()).get())), task.getSecretKeyPassphrase().getBytes() ); builder.setIdentityInfo(fsOptions, identityInfo); logger.info("checksum of key file: {}", getchecksumSecretKey(task.getSecretKeyFilePath().get().getPath())); logger.info("set identity: {}", task.getSecretKeyFilePath().get().getPath().toString()); } if (task.getProxy().isPresent()) { ProxyTask proxy = task.getProxy().get(); ProxyTask.ProxyType.setProxyType(builder, fsOptions, proxy.getType()); if (proxy.getHost().isPresent()) { builder.setProxyHost(fsOptions, proxy.getHost().get()); builder.setProxyPort(fsOptions, proxy.getPort()); } if (proxy.getUser().isPresent()) { builder.setProxyUser(fsOptions, proxy.getUser().get()); } if (proxy.getPassword().isPresent()) { builder.setProxyPassword(fsOptions, proxy.getPassword().get()); } if (proxy.getCommand().isPresent()) { builder.setProxyCommand(fsOptions, proxy.getCommand().get()); } } } catch (FileSystemException e) { logger.error("Error during initialize FsOptions: {}", e.getMessage()); throw new ConfigException(e); } return fsOptions; }

Target:
private FileSystemOptions initializeFsOptions(PluginTask task) { FileSystemOptions fsOptions = new FileSystemOptions(); try { SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance(); builder.setUserDirIsRoot(fsOptions, task.getUserDirIsRoot()); builder.setTimeout(fsOptions, task.getSftpConnectionTimeout() * 1000); builder.setStrictHostKeyChecking(fsOptions, "no"); if (task.getSecretKeyFilePath().isPresent()) { File secretKeyFile = task.getSecretKeyFilePath().get().getFile(); IdentityInfo identityInfo = new IdentityInfo( secretKeyFile, task.getSecretKeyPassphrase().getBytes() ); builder.setIdentityInfo(fsOptions, identityInfo); logger.info("set identity: {}", task.getSecretKeyFilePath().get().getPath().toString()); logger.info("checksum of identity: {}", getChecksum(secretKeyFile.toPath())); } if (task.getProxy().isPresent()) { ProxyTask proxy = task.getProxy().get(); ProxyTask.ProxyType.setProxyType(builder, fsOptions, proxy.getType()); if (proxy.getHost().isPresent()) { builder.setProxyHost(fsOptions, proxy.getHost().get()); builder.setProxyPort(fsOptions, proxy.getPort()); } if (proxy.getUser().isPresent()) { builder.setProxyUser(fsOptions, proxy.getUser().get()); } if (proxy.getPassword().isPresent()) { builder.setProxyPassword(fsOptions, proxy.getPassword().get()); } if (proxy.getCommand().isPresent()) { builder.setProxyCommand(fsOptions, proxy.getCommand().get()); } } } catch (FileSystemException e) { logger.error(e.getMessage()); throw new ConfigException(e); } return fsOptions; }
Source:
public <T extends Credential> T add(Class<T> type) { addButton.selectDropdownMenuAlt(type); String path = find(by.name("credentials")).getAttribute("path"); return newInstance(type, this, "/credentials"); }

Target:
public <T extends Credential> T add(Class<T> type) { addButton.selectDropdownMenuAlt(type); String path = find(by.name("credentials")).getAttribute("path"); return newInstance(type, this, path); }
Source:
public long getHeaderId(int position) { Date feedDate = feedsDate.get(position); return FeedHeaderHolder.getId(context, feedDate); }

Target:
public long getHeaderId(int position) { Calendar calendar = Calendar.getInstance(); calendar.setTime(feedsDate.get(position)); return calendar.get(Calendar.YEAR) * 367 + calendar.get(Calendar.DAY_OF_YEAR); }
Source:
public void testMaxApplicationId() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> new HttpLogOptions().setApplicationId("AppId-0123456789012345678912345")); assertEquals(thrown.getMessage(), "'applicationId' length cannot be greater than 24"); }

Target:
public void testMaxApplicationId() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> new HttpLogOptions().setApplicationId("AppId-0123456789012345678912345")); }
Source:
protected void filterClosedAccounts(UserIdentityContext userIdentityContext){ if(userIdentityContext.getEffectiveAccount() != null && userIdentityContext.getEffectiveAccount().getStatus().equals(Account.Status.CLOSED)){ throw new WebApplicationException(Status.FORBIDDEN); } }

Target:
protected void filterClosedAccounts(UserIdentityContext userIdentityContext){ if(userIdentityContext.getEffectiveAccount() != null && !userIdentityContext.getEffectiveAccount().getStatus().equals(Account.Status.ACTIVE)){ throw new WebApplicationException(status(Status.FORBIDDEN).entity("Provided Account is not active").build()); } }
Source:
protected void markAlignmentEnd(long alignmentDuration) { if (!latestAlignmentDurationNanos.isDone()) { latestAlignmentDurationNanos.complete(alignmentDuration); } startOfAlignmentTimestamp = 0; }

Target:
protected void markAlignmentEnd(long alignmentDuration) { latestAlignmentDurationNanos.complete(alignmentDuration); latestBytesProcessedDuringAlignment.complete(bytesProcessedDuringAlignment); startOfAlignmentTimestamp = OUTSIDE_OF_ALIGNMENT; bytesProcessedDuringAlignment = 0; }
Source:
public static long getDelayFromXml() { long delay = (long) minimum; if (appConfigDelay != null) { try { if (randomDelay == true){ if (appConfigDelay_asInit <= 0) { appConfigDelay_asInit = Integer.parseInt(String.valueOf(appConfigDelay)); } delay = Long.parseLong(getRandomInRange(minimum, appConfigDelay_asInit)); } else { delay = appConfigDelay; } return delay; }catch (Exception e) { log.error("get to get delay from xml, {}", e); } } else { AppConfig config = AppConfig.getInstance(); if (config.getDelayMinimum() > minimum){ minimum = (int) config.getDelayMinimum(); } if (config.getConstantDelay() > 0) { appConfigDelay = config.getConstantDelay(); } else if (config.getRandomDelay() > 0){ appConfigDelay = config.getRandomDelay(); randomDelay = true; }else{ delay = (long) minimum; } } return delay; }

Target:
public static long getDelayFromXml() { long delay = (long) minimum; if (appConfigDelay != null) { try { if (randomDelay == true){ if (appConfigDelay_asInit <= 0) { appConfigDelay_asInit = Integer.parseInt(String.valueOf(appConfigDelay)); } delay = Long.parseLong(getRandomInRange(minimum, appConfigDelay_asInit)); } else { delay = appConfigDelay; } return delay; }catch (NumberFormatException e) { log.error("failed to get delay from xml, make sure delay is in ms {}", e); } } else { AppConfig config = AppConfig.getInstance(); if (config.getDelayMinimum() > minimum){ minimum = (int) config.getDelayMinimum(); } if (config.getConstantDelay() > 0) { appConfigDelay = config.getConstantDelay(); } else if (config.getRandomDelay() > 0){ appConfigDelay = config.getRandomDelay(); randomDelay = true; }else{ delay = (long) minimum; } } return delay; }
Source:
public BigDecimal convertRain(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value.setScale(1, RoundingMode.HALF_UP); } return value.multiply(MM_TO_INCHES).setScale(2, RoundingMode.HALF_UP); }

Target:
public BigDecimal convertRain(BigDecimal value) { if (this == DEFAULT_UNIT_SYSTEM) { return value; } return value.multiply(MM_TO_INCHES); }
Source:
public ProbeStatus run() { long failures = getFailures(); if (failures == 0) { return ProbeStatus.newSuccess("No failure"); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String dateFailure = dateFormat.format(new Date(getDetected())); String message = String.format(FAILURE_MESSAGE, failures, dateFailure, getTimeout().toString()); if ((System.currentTimeMillis() - getDetected()) < getTimeout().toMillis()) { return ProbeStatus.newSuccess(message); } return ProbeStatus.newFailure(message); }

Target:
public ProbeStatus run() { long failures = getFailures(); if (failures == 0) { return ProbeStatus.newSuccess("No failure"); } String dateFailure = FORMATTER.format(Instant.ofEpochMilli(detected)); String message = String.format(FAILURE_MESSAGE, failures, dateFailure, getTimeout()); if (System.currentTimeMillis() - detected < getTimeout().toMillis()) { return ProbeStatus.newSuccess(message); } return ProbeStatus.newFailure(message); }
Source:
public void save(Object object, long windowId) throws IOException { closeReaders(); FileSystemWAL.FileSystemWALWriter writer = wal.getWriter(); writer.batchCompleted(); byte[] windowIdBytes = Longs.toByteArray(windowId); writer.append(new Slice(windowIdBytes)); writer.append(toSlice(object)); wal.beforeCheckpoint(windowId); wal.windowWalParts.put(windowId, writer.getCurrentPointer().getPartNum()); }

Target:
public void save(Object object, long windowId) throws IOException { closeReaders(); FileSystemWAL.FileSystemWALWriter writer = wal.getWriter(); byte[] windowIdBytes = Longs.toByteArray(windowId); writer.append(new Slice(windowIdBytes)); writer.append(toSlice(object)); wal.beforeCheckpoint(windowId); wal.windowWalParts.put(windowId, writer.getCurrentPointer().getPartNum()); writer.rotateIfNecessary(); }
Source:
S getFeatureStats() { assertIsFit(); return featureStats; }

Target:
protected S getFeatureStats() { assertIsFit(); return featureStats; }
Source:
public static ScrubberStore create(KeyValueService keyValueService) { TableMetadata scrubTableMeta = new TableMetadata( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription("row", ValueType.BLOB))), new ColumnMetadataDescription(new DynamicColumnDescription( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription("table", ValueType.VAR_STRING), new NameComponentDescription("col", ValueType.BLOB))), ColumnValueDescription.forType(ValueType.VAR_LONG))), ConflictHandler.IGNORE_ALL); keyValueService.createTables(ImmutableMap.of( AtlasDbConstants.SCRUB_TABLE, scrubTableMeta.persistToBytes())); return new KeyValueServiceScrubberStore(keyValueService); }

Target:
public static ScrubberStore create(KeyValueService keyValueService) { TableMetadata scrubTableMeta = new TableMetadata( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription.Builder() .componentName("row") .type(ValueType.BLOB) .build())), new ColumnMetadataDescription(new DynamicColumnDescription( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription.Builder() .componentName("table") .type(ValueType.VAR_STRING) .build(), new NameComponentDescription.Builder() .componentName("col") .type(ValueType.BLOB) .build())), ColumnValueDescription.forType(ValueType.VAR_LONG))), ConflictHandler.IGNORE_ALL); keyValueService.createTable(AtlasDbConstants.SCRUB_TABLE, scrubTableMeta.persistToBytes()); return new KeyValueServiceScrubberStore(keyValueService); }
Source:
public Map create(Map vmParams) { try { final Host host = getActiveHost(); final String vmId = (String) vmParams.get("vmId"); final VM vm = new VM(); vm.setTimeCreated(System.currentTimeMillis()); vm.setId(vmId); vm.setName((String) vmParams.get("vmName")); vm.setCpuType((String) vmParams.get("cpuType")); vm.setHost(host); vm.setIp(Utils.ipGenerator()); Integer memSize = 0; Object boxedMemSize = vmParams.get("memSize"); if(boxedMemSize instanceof String) { memSize = Integer.parseInt((String) boxedMemSize); } else { memSize = (Integer)boxedMemSize; } vm.setMemSize(memSize); final Object[] devices = (Object[]) vmParams.get("devices"); vm.setDeviceList(devices == null ? new ArrayList() : Arrays.asList(devices)); Map custom = (Map) vmParams.get("custom"); vm.setCustomMap(custom != null ? custom : map()); vm.generateDevicesAddressIfMissing(); vm.parseDevices(); host.getRunningVMs().put(vm.getId(), vm); updateHost(host); final Map resultMap = getDoneStatus(); vmParams.put("status", vm.getStatus().toString()); resultMap.put("vmList", vmParams); log.debug("VM created on host {}", vmId, host.getName()); addTask(TaskType.START_VM, 2000l, vm); addTask(TaskType.START_VM_POWERING_UP, 5000l, vm); addTask(TaskType.START_VM_AS_UP, 19000l, vm); return resultMap; } catch (Exception e) { throw error(e); } }

Target:
public Map create(Map vmParams) { try { final Host host = getActiveHost(); final String vmId = (String) vmParams.get("vmId"); final VM vm = new VM(); vm.setTimeCreated(System.currentTimeMillis()); vm.setId(vmId); vm.setName((String) vmParams.get("vmName")); vm.setCpuType((String) vmParams.get("cpuType")); vm.setHost(host); vm.setIp(Utils.ipGenerator()); Integer memSize = 0; Object boxedMemSize = vmParams.get("memSize"); if(boxedMemSize instanceof String) { memSize = Integer.parseInt((String) boxedMemSize); } else { memSize = (Integer)boxedMemSize; } vm.setMemSize(memSize); final Object[] devices = (Object[]) vmParams.get("devices"); vm.setDeviceList(devices == null ? new ArrayList() : Arrays.asList(devices)); Map custom = (Map) vmParams.get("custom"); vm.setCustomMap(custom != null ? custom : map()); vm.generateDevicesAddressIfMissing(); vm.parseDevices(); host.getRunningVMs().put(vm.getId(), vm); updateHost(host); final Map resultMap = getDoneStatus(); vmParams.put("status", vm.getStatus().toString()); resultMap.put("vmList", vmParams); log.debug("VM created on host {}", vmId, host.getName()); addTask(TaskType.START_VM, 2000l, vm); addTask(TaskType.START_VM_POWERING_UP, 5000l, vm); addTask(TaskType.START_VM_AS_UP, 20000l, vm); return resultMap; } catch (Exception e) { throw error(e); } }
Source:
protected StepEnum getStepType() { return StepEnum.STOP_REBALANCING_GLUSTER_VOLUME; }

Target:
protected StepEnum getStepType() { return StepEnum.REBALANCING_VOLUME; }