auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int execute(StratosCommandContext context, String[] args) throws CommandException { if (logger.isDebugEnabled()) { logger.debug("Executing command...", getName()); logger.info("Get name" + getName()); } if (args != null && args.length > 0) { String resourcePath = null; String partitionJson = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); if (logger.isDebugEnabled()) { logger.debug("Network Partition deployment"); } if (commandLine.hasOption(CliConstants.RESOURCE_PATH)) { if (logger.isTraceEnabled()) { logger.trace("Resource path option is passed"); } resourcePath = commandLine.getOptionValue(CliConstants.RESOURCE_PATH); partitionJson = readResource(resourcePath); } if (resourcePath == null) { System.out.println("usage: " + getName() + " [-p <resource path>]"); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().addNetworkPartition(partitionJson); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { if (logger.isErrorEnabled()) { logger.error("Error parsing arguments", e); } System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }

Target:
public int execute(StratosCommandContext context, String[] args) throws CommandException { if (logger.isDebugEnabled()) { logger.debug("Executing command...", getName()); logger.debug("Get name" + getName()); } if (args != null && args.length > 0) { String resourcePath = null; String partitionJson = null; final CommandLineParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); if (logger.isDebugEnabled()) { logger.debug("Network Partition deployment"); } if (commandLine.hasOption(CliConstants.RESOURCE_PATH)) { if (logger.isTraceEnabled()) { logger.trace("Resource path option is passed"); } resourcePath = commandLine.getOptionValue(CliConstants.RESOURCE_PATH); partitionJson = readResource(resourcePath); } if (resourcePath == null) { System.out.println("usage: " + getName() + " [-p <resource path>]"); return CliConstants.COMMAND_FAILED; } RestCommandLineService.getInstance().addNetworkPartition(partitionJson); return CliConstants.COMMAND_SUCCESSFULL; } catch (ParseException e) { if (logger.isErrorEnabled()) { logger.error("Error parsing arguments", e); } System.out.println(e.getMessage()); return CliConstants.COMMAND_FAILED; } catch (IOException e) { System.out.println("Invalid resource path"); return CliConstants.COMMAND_FAILED; } } else { context.getStratosApplication().printUsage(getName()); return CliConstants.COMMAND_FAILED; } }
Source:
public NodeValue exec(List<NodeValue> args) { if ( args == null ) throw new ARQInternalErrorException("FunctionBase1: Null args list") ; int size = args.size(); switch(args.size()) { case 0: throw new ExprEvalException(); case 1: { NodeValue nv = args.get(0); String str = NodeFunctions.str(nv.asNode()); throw new ExprEvalException(str); } default: throw new ExprEvalException("fn:error: Wrong number of arguments: Wanted 0 or 1, got "+args.size()) ; } }

Target:
public NodeValue exec(List<NodeValue> args) { if ( args == null ) throw new ARQInternalErrorException("FunctionBase1: Null args list") ; switch(args.size()) { case 0: throw new ExprEvalException(); case 1: { NodeValue nv = args.get(0); String str = NodeFunctions.str(nv.asNode()); throw new ExprEvalException(str); } default: throw new ExprEvalException("fn:error: Wrong number of arguments: Wanted 0 or 1, got "+args.size()) ; } }
Source:
private VdcActionType getSnapshotActionType() { if (getVm().isQualifiedForLiveSnapshotMerge()) { return VdcActionType.RemoveSnapshotSingleDiskLive; } if (FeatureSupported.isQemuimgCommitSupported(getStoragePool().getCompatibilityVersion())) { return VdcActionType.ColdMergeSnapshotSingleDisk; } return VdcActionType.RemoveSnapshotSingleDisk; }

Target:
private VdcActionType getSnapshotActionType() { if (getVm().isQualifiedForLiveSnapshotMerge()) { return VdcActionType.RemoveSnapshotSingleDiskLive; } if (isQemuimgCommitSupported()) { return VdcActionType.ColdMergeSnapshotSingleDisk; } return VdcActionType.RemoveSnapshotSingleDisk; }
Source:
public static SpecificHaxeClassReference convertGenericType(HaxeMethodModel model, SpecificHaxeClassReference classReference) { if (nonNull(model.getGenericParams())) { List<HaxeGenericParamModel> genericParams = model.getGenericParams(); ResultHolder[] specifics = classReference.getGenericResolver().getSpecifics(); if (genericParams != null) { Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); ResultHolder[] newSpecifics = new ResultHolder[specifics.length]; for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { newSpecifics[i] = nameAndConstraints.get(name); continue; } } newSpecifics[i] = specifics[i]; } return SpecificHaxeClassReference.withGenerics(classReference.getHaxeClassReference(), newSpecifics); } } return classReference; }

Target:
public static SpecificHaxeClassReference convertGenericType(HaxeMethodModel model, SpecificHaxeClassReference classReference) { List<HaxeGenericParamModel> genericParams = model.getGenericParams(); if (nonNull(genericParams)) { ResultHolder[] specifics = classReference.getGenericResolver().getSpecifics(); Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); ResultHolder[] newSpecifics = new ResultHolder[specifics.length]; for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { newSpecifics[i] = nameAndConstraints.get(name); continue; } } newSpecifics[i] = specifics[i]; } return SpecificHaxeClassReference.withGenerics(classReference.getHaxeClassReference(), newSpecifics); } return classReference; }
Source:
public void setI18n(ResourceBundleLocator resourceBundleLocator) { try { ResourceBundle resourceBundle = resourceBundleLocator.getBundle(INTRIGUE_BASE_NAME); if (resourceBundle != null) { Enumeration bundleKeys = resourceBundle.getKeys(); i18n = new HashMap<>(); while (bundleKeys.hasMoreElements()) { String key = (String) bundleKeys.nextElement(); String value = resourceBundle.getString(key); i18n.put(key, value); } } } catch (IOException e) { LOGGER.debug( "An error occurred while creating class loader to URL for ResourceBundle: {}, {}", INTRIGUE_BASE_NAME, Locale.getDefault(), e); } }

Target:
public void setI18n(ResourceBundleLocator resourceBundleLocator) { try { ResourceBundle resourceBundle = resourceBundleLocator.getBundle(INTRIGUE_BASE_NAME); if (resourceBundle != null) { Enumeration bundleKeys = resourceBundle.getKeys(); Map<String, String> keywords = new HashMap<>(); while (bundleKeys.hasMoreElements()) { String key = (String) bundleKeys.nextElement(); String value = resourceBundle.getString(key); keywords.put(key, value); } i18n = keywords; } } catch (IOException e) { LOGGER.debug( "An error occurred while creating class loader to URL for ResourceBundle: {}, {}", INTRIGUE_BASE_NAME, Locale.getDefault(), e); } }
Source:
NavigationState2.NavigationStateProto toProto() { NavigationState2.NavigationStateProto.Builder builder = NavigationState2.NavigationStateProto.newBuilder(); if (mSteps != null) { for (Step step : mSteps) { if (step != null) { builder.addSteps(step.toProto()); } } } if (mDestinations != null) { for (Destination destination : mDestinations) { if (destination != null) { builder.addDestinations(destination.toProto()); } } } return builder.build(); }

Target:
NavigationState2.NavigationStateProto toProto() { NavigationState2.NavigationStateProto.Builder builder = NavigationState2.NavigationStateProto.newBuilder(); if (mSteps != null) { for (Step step : mSteps) { if (step != null) { builder.addSteps(step.toProto()); } } } if (mDestinations != null) { for (Destination destination : mDestinations) { if (destination != null) { builder.addDestinations(destination.toProto()); } } } if (mCurrentSegment != null) { builder.setCurrentSegment(mCurrentSegment.toProto()); } if (mServiceStatus != null) { builder.addServiceStatuses(getServiceStatusProto()); } return builder.build(); }
Source:
public ControllerTenantBrokerResponse getBrokersFromController(String controllerAddress, String tenant) { try { String url = "http://" + controllerAddress + "/brokers/tenants/" + tenant; AsyncHttpClient.BoundRequestBuilder requestBuilder = _httpClient.prepareGet(url); if (_headers != null) { _headers.forEach((k, v) -> requestBuilder.addHeader(k, v)); } final Future<Response> response = requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8").execute(); ControllerTenantBrokerResponse.ControllerTenantBrokerResponseFuture controllerTableBrokerResponseFuture = new ControllerTenantBrokerResponse.ControllerTenantBrokerResponseFuture(response, url); return controllerTableBrokerResponseFuture.get(); } catch (ExecutionException e) { throw new PinotClientException(e); } }

Target:
public ControllerTenantBrokerResponse getBrokersFromController(String controllerAddress, String tenant) { try { String url = "http://" + controllerAddress + "/v2/brokers/tenants/" + tenant; AsyncHttpClient.BoundRequestBuilder requestBuilder = _httpClient.prepareGet(url); if (_headers != null) { _headers.forEach((k, v) -> requestBuilder.addHeader(k, v)); } final Future<Response> response = requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8").execute(); ControllerTenantBrokerResponse.ControllerTenantBrokerResponseFuture controllerTableBrokerResponseFuture = new ControllerTenantBrokerResponse.ControllerTenantBrokerResponseFuture(response, url); return controllerTableBrokerResponseFuture.get(); } catch (ExecutionException e) { throw new PinotClientException(e); } }
Source:
public Category<? super Integer> getKeys() { return $ceylon$language$Correspondence$this.getKeys(); }

Target:
public Category<? super ceylon.language.Integer> getKeys() { return $ceylon$language$Correspondence$this.getKeys(); }
Source:
protected void addVmStatic() { VmStatic vmStatic = getParameters().getVmStaticData(); if (vmStatic.getOrigin() == null) { vmStatic.setOrigin(OriginType.valueOf(Config.<String> getValue(ConfigValues.OriginType))); } vmStatic.setId(getVmId()); vmStatic.setQuotaId(getQuotaId()); vmStatic.setCreationDate(new Date()); vmStatic.setCreatedByUserId(getUserId()); VmPropertiesUtils.getInstance().separeteCustomPropertiesToUserAndPredefined( ClusterUtils.getCompatibilityVersion(getParameters().getVm()), vmStatic); updateOriginalTemplate(vmStatic); getVmStaticDao().save(vmStatic); getCompensationContext().snapshotNewEntity(vmStatic); }

Target:
protected void addVmStatic() { VmStatic vmStatic = getParameters().getVmStaticData(); if (vmStatic.getOrigin() == null) { vmStatic.setOrigin(OriginType.valueOf(Config.<String> getValue(ConfigValues.OriginType))); } vmStatic.setId(getVmId()); vmStatic.setQuotaId(getQuotaId()); vmStatic.setCreationDate(new Date()); vmStatic.setCreatedByUserId(getUserId()); VmPropertiesUtils.getInstance().separeteCustomPropertiesToUserAndPredefined( getVdsGroup().getcompatibility_version(), vmStatic); updateOriginalTemplate(vmStatic); getVmStaticDao().save(vmStatic); getCompensationContext().snapshotNewEntity(vmStatic); }
Source:
private void showServices() { serviceArrow.setImageResource(R.drawable.ic_arrow_up_white); for(StreamingService s : NewPipe.getServices()) { final String title = s.getServiceInfo().getName() + (ServiceHelper.isBeta(s) ? " (beta)" : ""); drawerItems.getMenu() .add(R.id.menu_services_group, s.getServiceId(), ORDER, title) .setIcon(ServiceHelper.getIcon(s.getServiceId())); } drawerItems.getMenu().getItem(ServiceHelper.getSelectedServiceId(this)).setChecked(true); }

Target:
private void showServices() { serviceArrow.setImageResource(R.drawable.ic_arrow_up_white); for(StreamingService s : NewPipe.getServices()) { final String title = s.getServiceInfo().getName() + (ServiceHelper.isBeta(s) ? " (beta)" : ""); MenuItem menuItem = drawerItems.getMenu() .add(R.id.menu_services_group, s.getServiceId(), ORDER, title) .setIcon(ServiceHelper.getIcon(s.getServiceId())); if(s.getServiceId() == 3){ enhancePeertubeMenu(s, menuItem); } } drawerItems.getMenu().getItem(ServiceHelper.getSelectedServiceId(this)).setChecked(true); }
Source:
public void testLinkImplicitParagraph() { builder.beginDocument(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("A "); builder.link("<LINK_1>", "link"); builder.characters(" in a paragraph."); builder.endBlock(); builder.link("<LINK_1>", "A link"); builder.characters(" opens an implicit paragraph."); builder.endDocument(); assertMarkup("A [link](<LINK_0> in a paragraph.\n\n[A link](<LINK_0> opens an implicit paragraph.\n\n"); }

Target:
public void testLinkImplicitParagraph() { builder.beginDocument(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("A paragraph."); builder.endBlock(); builder.link("<LINK_1>", "A link"); builder.characters(" opens an implicit paragraph."); builder.endDocument(); assertMarkup("A paragraph.\n\n[A link](<LINK_0> opens an implicit paragraph.\n\n"); }
Source:
private void writeFromOsgiConfig(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); rules.getGroups().forEach(group -> writeGroup(group, request, writer)); rules.getSitemaps().stream().map(sitemap -> buildSitemapString(sitemap, request.getResourceResolver())).forEach(writer::println); if(!rules.getSitemapProperties().isEmpty()) { PageManager pageManager = request.getResourceResolver().adaptTo(PageManager.class); Page page = pageManager.getContainingPage(request.getResource()); addRulesFromPages(page, request.getResourceResolver(), rules.getSitemapProperties(), writer, this::buildSitemapString); } }

Target:
private void writeFromOsgiConfig(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); PageManager pageManager = request.getResourceResolver().adaptTo(PageManager.class); Page page = pageManager.getContainingPage(request.getResource()); if (page != null) { rules.getGroups().forEach(group -> writeGroup(group, request.getResourceResolver(), page, writer)); rules.getSitemaps().stream().map(sitemap -> buildSitemapString(sitemap, request.getResourceResolver())).forEach(writer::println); if (!rules.getSitemapProperties().isEmpty()) { addRulesFromPages(page, request.getResourceResolver(), rules.getSitemapProperties(), writer, this::buildSitemapString); } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
Source:
public void testOverridesWithAsgEnabledThenDisabled() { InstanceInfo myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus("ASG-YO-HO", false); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus("ASG-YO-HO", true); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); }

Target:
public void testOverridesWithAsgEnabledThenDisabled() { InstanceInfo myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), false); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.OUT_OF_SERVICE); ((AwsInstanceRegistry) registry).getAwsAsgUtil().setStatus(myInstance.getASGName(), true); myInstance = createLocalUpInstanceWithAsg(LOCAL_REGION_INSTANCE_1_HOSTNAME); registerInstanceLocally(myInstance); verifyLocalInstanceStatus(myInstance.getId(), InstanceStatus.UP); }
Source:
private void RemoveVdsFromCollection() { VDSReturnValue returnValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(getVdsId())); }

Target:
private void RemoveVdsFromCollection() { Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(getVdsId())); }
Source:
protected Poller(Context context, int size) { this.context = context; selector = context.selector(); items = new PollItem[size]; timeout = -1L; next = 0; freeSlots = new LinkedList<Integer>(); }

Target:
protected Poller(Context context, int size) { assert (context != null); this.context = context; selector = context.selector(); assert (selector != null); items = new PollItem[size]; timeout = -1L; next = 0; freeSlots = new LinkedList<Integer>(); }
Source:
ByteBuffer wrap(ByteBuffer buffer) throws IOException; ByteBuffer unwrap(ByteBuffer wrappedBuffer) throws IOException; ByteBuffer ensureWrappedCapacity(int amount, ByteBuffer wrappedBuffer, BufferPool.BufferType bufferType); ByteBuffer readAtLeast(int amount, ByteBuffer wrappedBuffer, Socket socket) throws IOException; default void doneReadingDirectAck(ByteBuffer unwrappedBuffer) { doneReading(unwrappedBuffer); }

Target:
ByteBuffer wrap(ByteBuffer buffer) throws IOException; ByteBuffer unwrap(ByteBuffer wrappedBuffer) throws IOException; ByteBuffer ensureWrappedCapacity(int amount, ByteBuffer wrappedBuffer, BufferPool.BufferType bufferType); ByteBuffer readAtLeast(SocketChannel channel, int amount, ByteBuffer wrappedBuffer) throws IOException; default void doneReadingDirectAck(ByteBuffer unwrappedBuffer) { doneReading(unwrappedBuffer); }
Source:
protected void executeCommand() { try { addVmToDb(); VM vm = getVm(); processImages(); if (getReturnValue().getTaskIdList().isEmpty()) { endVmRelatedOps(); } } catch (RuntimeException e) { MacPoolManager.getInstance().freeMacs(macsAdded); throw e; } setSucceeded(true); }

Target:
protected void executeCommand() { try { addVmToDb(); processImages(); if (getReturnValue().getVdsmTaskIdList().isEmpty()) { endVmRelatedOps(); } } catch (RuntimeException e) { MacPoolManager.getInstance().freeMacs(macsAdded); throw e; } setSucceeded(true); }
Source:
private boolean managementNetworkModifiedCorrectly(VdsNetworkInterface iface) { if (!Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(iface.getNetworkName())) { return true; } if (iface.getBootProtocol() == NetworkBootProtocol.STATIC_IP && vds.getHostName().matches(ValidationUtils.IP_PATTERN)) { return StringUtils.equals(vds.getHostName(), iface.getAddress()); } return true; }

Target:
private boolean managementNetworkModifiedCorrectly(VdsNetworkInterface iface) { if (iface.getBootProtocol() == NetworkBootProtocol.STATIC_IP && vds.getHostName().matches(ValidationUtils.IP_PATTERN)) { return StringUtils.equals(vds.getHostName(), iface.getAddress()); } return true; }
Source:
public synchronized void addLocation(URI location, TaskId remoteSourceTaskId) { requireNonNull(location, "location is null"); if (closed.get()) { return; } if (allClients.containsKey(location)) { return; } if (removedRemoteSourceTaskIds.contains(remoteSourceTaskId)) { return; } checkState(!noMoreLocations, "No more locations already set"); TaskResultClient resultClient; if (location.getScheme().toLowerCase(Locale.ENGLISH).startsWith("http")) { resultClient = new HttpTaskResultClient(httpClient, location); } else if (location.getScheme().toLowerCase(Locale.ENGLISH).startsWith("thrift")) { resultClient = new ThriftTaskResultClient(driftClient, location, pageBufferClientCallbackExecutor); } else { throw new PrestoException(GENERIC_INTERNAL_ERROR, "unsupported task result client scheme " + location.getScheme()); } PageBufferClient client = new PageBufferClient( resultClient, maxErrorDuration, acknowledgePages, location, new ExchangeClientCallback(), scheduler, pageBufferClientCallbackExecutor); allClients.put(location, client); checkState(taskIdToLocationMap.put(remoteSourceTaskId, location) == null, "Duplicate remoteSourceTaskId: " + remoteSourceTaskId); queuedClients.add(client); scheduleRequestIfNecessary(); }

Target:
public synchronized void addLocation(URI location, TaskId remoteSourceTaskId) { requireNonNull(location, "location is null"); if (closed.get()) { return; } if (allClients.containsKey(location)) { return; } if (removedRemoteSourceTaskIds.contains(remoteSourceTaskId)) { return; } checkState(!noMoreLocations, "No more locations already set"); RpcShuffleClient resultClient; switch (location.getScheme().toLowerCase(Locale.ENGLISH)) { case "http": case "https": resultClient = new HttpRpcShuffleClient(httpClient, location); break; case "thrift": resultClient = new ThriftRpcShuffleClient(driftClient, location); break; default: throw new PrestoException(GENERIC_INTERNAL_ERROR, "unsupported task result client scheme " + location.getScheme()); } PageBufferClient client = new PageBufferClient( resultClient, maxErrorDuration, acknowledgePages, location, new ExchangeClientCallback(), scheduler, pageBufferClientCallbackExecutor); allClients.put(location, client); checkState(taskIdToLocationMap.put(remoteSourceTaskId, location) == null, "Duplicate remoteSourceTaskId: " + remoteSourceTaskId); queuedClients.add(client); scheduleRequestIfNecessary(); }
Source:
public PlanNodeCostEstimate visitAssignUniqueId(AssignUniqueId node, Void context) { return cpuCost(getStats(node.getSource()).getOutputRowCount() * BigintType.BIGINT.getFixedSize()); }

Target:
public PlanNodeCostEstimate visitAssignUniqueId(AssignUniqueId node, Void context) { return cpuCost(getStats(node).getOutputSizeInBytes(ImmutableList.of(node.getIdColumn()))); }
Source:
public Event(String tenantId, String id, long ctime, String dataId, String category, String text, Map<String, String> context, Map<String, String> tags) { this.tenantId = tenantId; this.id = id; this.ctime = ctime; this.dataId = dataId; this.category = category; this.text = text; this.context = context; this.tags = tags; }

Target:
public Event(String tenantId, String id, long ctime, String dataId, String category, String text, Map<String, String> context, Map<String, String> tags) { this.tenantId = tenantId; this.id = id; this.ctime = (ctime <= 0) ? System.currentTimeMillis() : ctime; this.dataId = dataId; this.category = category; this.text = text; this.context = context; this.tags = tags; }
Source:
private InterpreterResult executeQuery(String sql) throws IOException { HttpResponse response = prepareRequest(sql); String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); int code = response.getStatusLine().getStatusCode(); if (code != 200) { StringBuilder errorMessage = new StringBuilder("Failed : HTTP error code " + code); logger.error("failed to execute query: " + result); try { JSONObject content = new JSONObject(result); if (content.has("exception")) { errorMessage.append(". Error message: " + content.getString("exception")); } } catch (JSONException e) { logger.error("Cannot parse json string ", e); if (code == 401) { errorMessage.append(". Error message: Unauthorized. This request requires " + "HTTP authentication. Please make sure your have set your credentials correctly."); } else { errorMessage.append(". Error message: " + result); } } return new InterpreterResult(InterpreterResult.Code.ERROR, errorMessage.toString()); } return new InterpreterResult(InterpreterResult.Code.SUCCESS, formatResult(result)); }

Target:
private InterpreterResult executeQuery(String sql) throws IOException { HttpResponse response = prepareRequest(sql); String result; try { int code = response.getStatusLine().getStatusCode(); result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); if (code != 200) { StringBuilder errorMessage = new StringBuilder("Failed : HTTP error code " + code); logger.error("Failed to execute query: " + result); KylinErrorResponse kylinErrorResponse = KylinErrorResponse.fromJson(result); if (kylinErrorResponse == null) { logger.error("Cannot get json from string: " + result); if (code == 401) { errorMessage.append(". Error message: Unauthorized. This request requires " + "HTTP authentication. Please make sure your have set your credentials" + " correctly."); } else { errorMessage.append(". Error message: " + result); } } else { String exception = kylinErrorResponse.getException(); logger.error("The exception is " + exception); errorMessage.append(". Error message: " + exception); } return new InterpreterResult(InterpreterResult.Code.ERROR, errorMessage.toString()); } } catch (NullPointerException | IOException e) { throw new IOException(e); } return new InterpreterResult(InterpreterResult.Code.SUCCESS, formatResult(result)); }
Source:
private void handleMap(Entry entry, SourceFile.FileType fileType, Version version, Map<String, SourceFile> imports, Map<String, ?> map) { for (Map.Entry<String, ?> e : map.entrySet()) { final Object mapValue = e.getValue(); if (e.getKey().equalsIgnoreCase("$import") || e.getKey().equalsIgnoreCase("$include") || e.getKey().equalsIgnoreCase("$mixin") || e.getKey().equalsIgnoreCase("import") || e.getKey().equalsIgnoreCase("include") || e.getKey() .equalsIgnoreCase("mixin")) { if (mapValue instanceof String) { handleImport(fileType, version, imports, (String)mapValue); } } else if (e.getKey().equalsIgnoreCase("run")) { if (mapValue instanceof String) { handleImport(fileType, version, imports, (String)mapValue); } else if (mapValue instanceof Map) { handleMap(entry, fileType, version, imports, (Map)mapValue); } } else { handleMapValue(entry, fileType, version, imports, mapValue); } } }

Target:
private void handleMap(Entry entry, SourceFile.FileType fileType, Version version, Map<String, SourceFile> imports, Map<String, ?> map) { Set<String> importKeywords = Sets.newHashSet("$import", "$include", "$mixin", "import", "include", "mixin"); for (Map.Entry<String, ?> e : map.entrySet()) { final Object mapValue = e.getValue(); if (importKeywords.contains(e.getKey().toLowerCase())) { if (mapValue instanceof String) { handleImport(fileType, version, imports, (String)mapValue); } } else if (e.getKey().equalsIgnoreCase("run")) { if (mapValue instanceof String) { handleImport(fileType, version, imports, (String)mapValue); } else if (mapValue instanceof Map) { handleMap(entry, fileType, version, imports, (Map)mapValue); } } else { handleMapValue(entry, fileType, version, imports, mapValue); } } }
Source:
protected boolean needsValue() { boolean isRequired = getTaskAttribute().getMetaData().isRequired(); boolean isReadOnly = getTaskAttribute().getMetaData().isReadOnly(); return isRequired && !isReadOnly; }

Target:
protected boolean needsValue() { boolean isRequired = getTaskAttribute().getMetaData().isRequired(); boolean isReadOnly = getTaskAttribute().getMetaData().isReadOnly(); boolean textIsEmpty = getText().getText().isEmpty(); return isRequired && !isReadOnly && textIsEmpty; }
Source:
public boolean isWriting() { return writing == true || (!reading && isSimpleTargetType()); }

Target:
public boolean isWriting() { return writing || (!reading && isSimpleTargetType()); }
Source:
private void setError(Throwable error) { response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); response.setStatusMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()); response.headers().add("X-Exception", String.valueOf(error.getMessage())); response.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); EngineErrorResponse errorResponse = new EngineErrorResponse(); errorResponse.setResponseCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); errorResponse.setMessage(error.getMessage()); errorResponse.setTrace(error); response.write(Json.encode(errorResponse)); log.debug("Finished setting error"); if (!response.ended()) response.end(); }

Target:
private void setError(Throwable error) { response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); response.setStatusMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()); response.headers().add("X-Gateway-Error", String.valueOf(error.getMessage())); response.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); EngineErrorResponse errorResponse = new EngineErrorResponse(); errorResponse.setResponseCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); errorResponse.setMessage(error.getMessage()); errorResponse.setTrace(error); response.write(Json.encode(errorResponse)); log.debug("Finished setting error"); if (!response.ended()) response.end(); }
Source:
public void start() throws ResourceException { if (started.get()) { return; } final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); resourceAdapter.endpointActivation(endpointFactory, activationSpec); Thread.currentThread().setContextClassLoader(oldCl); logger.info("Activated endpoint for " + beanContext.getDeploymentID()); started.set(true); }

Target:
public void start() throws ResourceException { if (! started.compareAndSet(false, true)) { return; } final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); resourceAdapter.endpointActivation(endpointFactory, activationSpec); logger.info("Activated endpoint for " + beanContext.getDeploymentID()); } finally { Thread.currentThread().setContextClassLoader(oldCl); } }
Source:
public void setMinMaxFromBytes(byte[] minBytes, byte[] maxBytes) { max = truncator.truncateMax(Binary.fromReusedByteArray(maxBytes), truncateLength); min = truncator.truncateMin(Binary.fromReusedByteArray(minBytes), truncateLength); this.markAsNotEmpty(); }

Target:
public void setMinMaxFromBytes(byte[] minBytes, byte[] maxBytes) { max = Binary.fromReusedByteArray(maxBytes); min = Binary.fromReusedByteArray(minBytes); this.markAsNotEmpty(); }
Source:
private List<CustomAction> customActions() { List<CustomAction> actions = new LinkedList<>(); CustomAction tra = new CustomAction("org.finra.datagenerator", "positive", Transform.class); actions.add(tra); CustomAction neg = new CustomAction("org.finra.datagenerator", "negative", NegativeAssign.class); actions.add(neg); CustomAction pos = new CustomAction("org.finra.datagenerator", "positive", Assign.class); actions.add(pos); return actions; }

Target:
private List<CustomAction> customActions() { List<CustomAction> actions = new LinkedList<>(); CustomAction tra = new CustomAction("org.finra.datagenerator", "transform", Transform.class); actions.add(tra); CustomAction neg = new CustomAction("org.finra.datagenerator", "negative", NegativeAssign.class); actions.add(neg); return actions; }
Source:
private void addGroupKey(int grpId, GroupKeyEncrypted key) { try { synchronized (metaStorageMux) { withMasterKeyChangeReadLock(() -> grpKeys.changeActiveKey(grpId, key)); writeToMetaStore(grpId, true, false); } } catch (IgniteCheckedException e) { throw new IgniteException("Failed to write cache group encryption key [grpId=" + grpId + ']', e); } }

Target:
void addGroupKey(int grpId, GroupKeyEncrypted key) { synchronized (metaStorageMux) { try { grpKeys.addKey(grpId, key); writeGroupKeysToMetaStore(grpId, grpKeys.getAll(grpId)); } catch (IgniteCheckedException e) { throw new IgniteException("Failed to write cache group encryption key [grpId=" + grpId + ']', e); } } }
Source:
public SummaryCollection processFiles(FileSystemResolver volMgr, Map<String,List<TRowRange>> files, BlockCache summaryCache, BlockCache indexCache, ExecutorService srp) { SummaryCollection fileSummaries = new SummaryCollection(); List<Future<SummaryCollection>> futures = new ArrayList<>(); for (Entry<String,List<TRowRange>> entry : files.entrySet()) { Future<SummaryCollection> future = srp.submit(() -> { List<RowRange> rrl = Lists.transform(entry.getValue(), RowRange::new); return getSummaries(volMgr, entry.getKey(), rrl, summaryCache, indexCache); }); futures.add(future); } for (Future<SummaryCollection> future : futures) { try { fileSummaries.merge(future.get(), factory); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } return fileSummaries; }

Target:
public Future<SummaryCollection> processFiles(FileSystemResolver volMgr, Map<String,List<TRowRange>> files, BlockCache summaryCache, BlockCache indexCache, ExecutorService srp) { List<CompletableFuture<SummaryCollection>> futures = new ArrayList<>(); for (Entry<String,List<TRowRange>> entry : files.entrySet()) { futures.add(CompletableFuture.supplyAsync(() -> { List<RowRange> rrl = Lists.transform(entry.getValue(), RowRange::new); return getSummaries(volMgr, entry.getKey(), rrl, summaryCache, indexCache); }, srp)); } return CompletableFutureUtil.merge(futures, (sc1, sc2) -> SummaryCollection.merge(sc1, sc2, factory), SummaryCollection::new); }
Source:
public void loadVmFromOva() { clearForLoad(); if (!validateOvaConfiguration()) { return; } startProgress(); AsyncDataProvider.getInstance().getVmFromOva(new AsyncQuery<>(returnValue -> { if (returnValue.getSucceeded()) { Map<VM, String> vmToOva = returnValue.getReturnValue(); List<VM> vms = new ArrayList<>(vmToOva.keySet()); vmNameToOva = vms.stream().collect(Collectors.toMap(VM::getName, vm -> vmToOva.get(vm))); updateVms(vms); } else { setError(messages.failedToLoadOva(getOvaPath().getEntity())); } stopProgress(); }), getHosts().getSelectedItem().getId(), getOvaPath().getEntity()); }

Target:
public void loadVmFromOva() { clearForLoad(); if (!validateOvaConfiguration()) { return; } startProgress(); AsyncDataProvider.getInstance().getVmFromOva(new AsyncQuery<>(returnValue -> { if (returnValue.getSucceeded()) { Map<VM, String> vmToOva = returnValue.getReturnValue(); vmNameToOva = vmToOva.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().getName(), Entry::getValue)); updateVms(vmToOva.keySet()); } else { setError(messages.failedToLoadOva(getOvaPath().getEntity())); } stopProgress(); }), getHosts().getSelectedItem().getId(), getOvaPath().getEntity()); }
Source:
public void shouldReturnTaskInformation() throws IOException { String sourceIndex = "test_source_index"; String destIndex = "test_dest_index"; String documentType = "test_type"; String documentId = "test_id"; createIndex(sourceIndex); index(sourceIndex, documentType, documentId, "{}"); flushAndRefresh(sourceIndex); ImmutableMap<String, Object> source = ImmutableMap.of("index", sourceIndex); ImmutableMap<String, Object> dest = ImmutableMap.of("index", destIndex); Reindex reindex = new Reindex.Builder(source, dest).refresh(true).waitForCompletion(false).build(); JestResult result = client.execute(reindex); Object task = result.getValue("task"); assertNotNull(task); JestResult taskInformation = client.execute(new TasksInformation.Builder(String.valueOf(task)).build()); Object completed = taskInformation.getValue("completed"); assertNotNull(completed); }

Target:
public void shouldReturnTaskInformation() throws IOException { String sourceIndex = "test_source_index"; String destIndex = "test_dest_index"; String documentType = "test_type"; String documentId = "test_id"; createIndex(sourceIndex); index(sourceIndex, documentType, documentId, "{}"); flushAndRefresh(sourceIndex); ImmutableMap<String, Object> source = ImmutableMap.of("index", sourceIndex); ImmutableMap<String, Object> dest = ImmutableMap.of("index", destIndex); Reindex reindex = new Reindex.Builder(source, dest).refresh(true).waitForCompletion(false).build(); JestResult result = client.execute(reindex); String task = (String) result.getValue("task"); assertNotNull(task); JestResult taskInformation = client.execute(new TasksInformation.Builder().task(task).build()); Boolean completed = (Boolean) taskInformation.getValue("completed"); assertNotNull(completed); }
Source:
public String[] formatProperties() { List<String> ret = new ArrayList<>(); ret.add("'format'='json'"); if (configure) { ret.add("'format.fail-on-missing-field'='true'"); ret.add("'format.ignore-parse-errors'='false'"); } return ret.toArray(new String[0]); }

Target:
public String[] formatProperties() { List<String> ret = new ArrayList<>(); ret.add("'format'='json'"); ret.add("'format.ignore-parse-errors'='true'"); return ret.toArray(new String[0]); }
Source:
public void performEngineNicsHealthCheck() { List<NetworkInterface> nicsToCheck = networkInterfacesToCheck(); log.debug("Performing engine NICs health check on: " + nicsToString(nicsToCheck)); checkNicsAndUpdateEngineStatus(nicsToCheck); log.debug("Health check done, engine NICs are {}.", (engineNicHealthCache.isAllNicHealthy() ? "healthy" : "unhealthy")); }

Target:
public void performEngineNicsHealthCheck() { List<NetworkInterface> nicsToCheck = networkInterfacesToCheck(); log.debug("Performing engine NICs health check on: " + StringUtils.join(toNicsDisplayNames(nicsToCheck), ", ")); checkNicsAndUpdateEngineStatus(nicsToCheck); log.debug("Health check done, engine NICs are {}.", engineNicHealthCache.isAllNicHealthy() ? "healthy" : "unhealthy"); }
Source:
void execute() throws AzureBlobFileSystemException { String latencyHeader = this.client.getAbfsPerfTracker().getClientLatency(); if (latencyHeader != null && !latencyHeader.isEmpty()) { AbfsHttpHeader httpHeader = new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_ABFS_CLIENT_LATENCY, latencyHeader); requestHeaders.add(httpHeader); } retryCount = 0; LOG.debug("First execution of REST operation - {}", operationType); while (!executeHttpOperation(retryCount++)) { try { LOG.debug("Retrying REST operation {}. RetryCount = {}", operationType, retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { if (this.isAppendBlobAppend && retryCount > 0 && result.getStorageErrorCode().equals("InvalidQueryParameterValue")) { return; } throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } LOG.trace("{} REST operation complete", operationType); }

Target:
void execute() throws AzureBlobFileSystemException { String latencyHeader = this.client.getAbfsPerfTracker().getClientLatency(); if (latencyHeader != null && !latencyHeader.isEmpty()) { AbfsHttpHeader httpHeader = new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_ABFS_CLIENT_LATENCY, latencyHeader); requestHeaders.add(httpHeader); } retryCount = 0; LOG.debug("First execution of REST operation - {}", operationType); while (!executeHttpOperation(retryCount++)) { try { LOG.debug("Retrying REST operation {}. RetryCount = {}", operationType, retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } LOG.trace("{} REST operation complete", operationType); }
Source:
public Assignment apply(Task task, TaskContext taskContext, String s) { List<OrganizationalEntity> excluded = ((InternalPeopleAssignments)task.getPeopleAssignments()).getExcludedOwners(); UserInfo userInfo = (UserInfo) ((org.jbpm.services.task.commands.TaskContext)taskContext).get(EnvironmentName.TASK_USER_INFO); List<OrganizationalEntity> potentialOwners = task.getPeopleAssignments().getPotentialOwners().parallelStream() .filter(oe -> oe instanceof User && !excluded.contains(oe)) .collect(Collectors.toList()); task.getPeopleAssignments().getPotentialOwners().parallelStream().filter(oe -> oe instanceof Group) .forEach(oe -> { Iterator<OrganizationalEntity> groupUsers = userInfo.getMembersForGroup((Group)oe); if (groupUsers != null) { groupUsers.forEachRemaining(user -> { if (user != null && !excluded.contains(user) && !potentialOwners.contains(user)) { potentialOwners.add(user); } }); } }); String queueName = getQueueName(task); CircularQueue<OrganizationalEntity> mappedQueue = null; if (circularQueueMap.containsKey(queueName)) { final CircularQueue<OrganizationalEntity> queue = circularQueueMap.get(queueName); potentialOwners.forEach(po -> { if (!queueContainsUser(queue,po)) { queue.add(po); } }); queue.removeIf(oe -> !potentialOwners.contains(oe)); mappedQueue = queue; } else { CircularQueue<OrganizationalEntity> queue = new CircularQueue(); potentialOwners.forEach(po -> {queue.add(po);}); circularQueueMap.put(queueName,queue); mappedQueue = queue; } OrganizationalEntity owner = mappedQueue.take(); return new Assignment(owner.getId()); }

Target:
public Assignment apply(Task task, TaskContext taskContext, String s) { List<OrganizationalEntity> excluded = ((InternalPeopleAssignments)task.getPeopleAssignments()).getExcludedOwners(); UserInfo userInfo = (UserInfo) ((org.jbpm.services.task.commands.TaskContext)taskContext).get(EnvironmentName.TASK_USER_INFO); List<OrganizationalEntity> potentialOwners = task.getPeopleAssignments().getPotentialOwners().stream() .filter(oe -> oe instanceof User && !excluded.contains(oe)) .collect(Collectors.toList()); task.getPeopleAssignments().getPotentialOwners().stream().filter(oe -> oe instanceof Group) .forEach(oe -> { Iterator<OrganizationalEntity> groupUsers = userInfo.getMembersForGroup((Group)oe); if (groupUsers != null) { groupUsers.forEachRemaining(user -> { if (user != null && !excluded.contains(user) && !potentialOwners.contains(user)) { potentialOwners.add(user); } }); } }); String queueName = getQueueName(task); CircularQueue<OrganizationalEntity> mappedQueue = synchronizedQueue(queueName,potentialOwners); OrganizationalEntity owner = mappedQueue.take(); return new Assignment(owner.getId()); }
Source:
protected void testAccessControl() throws Exception { StudentAttributes student = typicalBundle.students.get("student1InCourse1"); String feedbackSessionName = "First feedback session"; String courseId = student.course; String moderatedStudentEmail = student.email; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedStudentEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifyCoursePrivilege(submissionParams); }

Target:
protected void testAccessControl() throws Exception { testDifferentPrivileges(); StudentAttributes student = typicalBundle.students.get("student1InCourse1"); String feedbackSessionName = "First feedback session"; String courseId = student.course; String moderatedStudentEmail = student.email; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedStudentEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifySessionCommentInSectionsPrivilege(submissionParams); }
Source:
public void testWriteBehind() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException, IOException, InterruptedException { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.xml")); assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true)); final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration); cacheManager.init(); final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class); assertThat(cache, notNullValue()); assertThat(cache.get(1), notNullValue()); final Number key = new Long(42); TestCacheLoaderWriter.latch = new CountDownLatch(1); cache.put(key, "Bye y'all!"); TestCacheLoaderWriter.latch.await(); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key)); assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true)); final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class); assertThat(templateCache, notNullValue()); assertThat(templateCache.get(1), notNullValue()); final Number key1 = new Long(100); TestCacheLoaderWriter.latch = new CountDownLatch(1); templateCache.put(key1, "Bye y'all!"); TestCacheLoaderWriter.latch.await(); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1)); }

Target:
public void testWriteBehind() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException, IOException, InterruptedException { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.xml")); assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true)); final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration); cacheManager.init(); final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class); assertThat(cache, notNullValue()); assertThat(cache.get(1), notNullValue()); final Number key = new Long(42); TestCacheLoaderWriter.latch = new CountDownLatch(1); cache.put(key, "Bye y'all!"); TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key)); assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true)); final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class); assertThat(templateCache, notNullValue()); assertThat(templateCache.get(1), notNullValue()); final Number key1 = new Long(100); TestCacheLoaderWriter.latch = new CountDownLatch(1); templateCache.put(key1, "Bye y'all!"); TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1)); }