auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getConcatedTypeNameValues(Query query, List<String> typeNames, String typeName) { List<String> filteredTypeNames; Set<String> queryTypeNames = query.getTypeNames(); if (queryTypeNames != null && queryTypeNames.size() > 0) { filteredTypeNames = new ArrayList<String>(queryTypeNames); for (String name : typeNames) { if (!filteredTypeNames.contains(name)) { filteredTypeNames.add(name); } } } else { filteredTypeNames = typeNames; } <START> if (query.isAllowDottedKeys()) { <END> return getConcatedTypeNameValues(filteredTypeNames, typeName, "."); } else { return getConcatedTypeNameValues(filteredTypeNames, typeName); } }</code><technical_language>gonna picky, extract a method compute separator a single place call getConcatedTypeNameValues</technical_language>

Target:
public static String getConcatedTypeNameValues(Query query, List<String> typeNames, String typeName) { Set<String> queryTypeNames = query.getTypeNames(); if (queryTypeNames != null && queryTypeNames.size() > 0) { List<String> filteredTypeNames = new ArrayList<String>(queryTypeNames); for (String name : typeNames) { if (!filteredTypeNames.contains(name)) { filteredTypeNames.add(name); } } return getConcatedTypeNameValues(filteredTypeNames, typeName, getTypeNameValuesSeparator(query)); } else { return getConcatedTypeNameValues(typeNames, typeName, getTypeNameValuesSeparator(query)); } }
Source:
<code>private XSDSchema getSchema(String resourceName) { InputStream inputStream = getClass().getResourceAsStream(resourceName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); String xsd = new String(outputStream.toByteArray()); XSDSchema schema = Util.getXSDSchema(xsd); return schema; } catch (Exception e) { <START> LOG.error(e.getMessage(), e); <END> } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); } return null; }</code><technical_language>e.getMessage a self-defined message</technical_language>

Target:
private XSDSchema getSchema(String resourceName) { InputStream inputStream = getClass().getResourceAsStream(resourceName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); String xsd = new String(outputStream.toByteArray()); XSDSchema schema = Util.getXSDSchema(xsd); return schema; } catch (Exception e) { LOG.error("Fail in parsing schema:", e); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); } return null; }
Source:
<code><START> public ArrayList<ConfigNode> children() { <END> return children; }</code><technical_language>return more general List, Collection, Iterable</technical_language>

Target:
final public Collection<AbstractConfigNode> children() { return children; }
Source:
<code>protected MutableBoundedValue<Short> constructValue(Short actualValue) { <START> return SpongeValueFactory.boundedBuilder(Keys.SPAWNER_MAXIMUM_NEARBY_ENTITIES) <END> .minimum((short) 0) .maximum(Short.MAX_VALUE) .defaultValue(DataConstants.DEFAULT_SPAWNER_MAXMIMUM_NEARBY_ENTITIES) .actualValue(actualValue) .build(); }</code><technical_language>this.key in place of Keys.SPAWNER_MAXIMUM_NEARBY_ENTITIES</technical_language>

Target:
protected MutableBoundedValue<Short> constructValue(Short actualValue) { return SpongeValueFactory.boundedBuilder(this.key) .minimum((short) 0) .maximum(Short.MAX_VALUE) .defaultValue(DataConstants.DEFAULT_SPAWNER_MAXMIMUM_NEARBY_ENTITIES) .actualValue(actualValue) .build(); }
Source:
<code>public String toString() { <START> return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE); <END> }</code><technical_language>prefer this reflection things. introduced issues elsewhere</technical_language>

Target:
public String toString() { return new ToStringBuilder(this) .appendSuper(super.toString()) .append("event", getEvent()) .append("rule", getRule()) .append("service", getService()) .append("operation", getOperation()) .append("endPoint", getEndPoint()) .toString(); }
Source:
<code>public void test_connectLjava_net_SocketAddressI_setSOTimeout() throws Exception { class SocketConnector extends Thread { private final int timeout; private final Socket theSocket; private final SocketAddress address; private Exception exception = null; @Override public void run() { try { theSocket.connect(address, timeout); } catch (SocketTimeoutException e) { } catch (Exception e) { exception = e; } } private SocketConnector(int timeout, Socket theSocket, SocketAddress address) { this.timeout = timeout; this.theSocket = theSocket; this.address = address; } private Exception getException() { return exception; } } try (final Socket theSocket = new Socket()) { final SocketConnector connector = new SocketConnector(5000, theSocket, UNREACHABLE_ADDRESS); connector.start(); theSocket.setSoTimeout(1000); Thread.sleep(10); assertTrue("Socket option not set during connect: 10 ", Math.abs(1000 - theSocket.getSoTimeout()) <= 10); Thread.sleep(50); theSocket.setSoTimeout(2000); assertTrue("Socket option not set during connect: 50 ", Math.abs(2000 - theSocket.getSoTimeout()) <= 10); connector.join(); Exception e = connector.getException(); if (e != null) { <START> e.printStackTrace(); <END> } assertNull(e); } }</code><technical_language>Printing stdout guarantee stacktrace is shown failure logs? about: fail(printStacktraceToString(e)); printStacktraceToString a helper function in ThrowableTest - a general in libcore? (I'm 100% if assert*() overload takes a Throwable/Exception)</technical_language>

Target:
public void test_connectLjava_net_SocketAddressI_setSOTimeout() throws Exception { final AtomicReference<Exception> exceptionRef = new AtomicReference<>(); class SocketConnector extends Thread { private final int timeout; private final Socket theSocket; private final SocketAddress address; @Override public void run() { try { theSocket.connect(address, timeout); } catch (Exception e) { exceptionRef.set(e); } } private SocketConnector(int timeout, Socket theSocket, SocketAddress address) { this.timeout = timeout; this.theSocket = theSocket; this.address = address; } } try (final Socket theSocket = new Socket()) { final SocketConnector connector = new SocketConnector(5000, theSocket, UNREACHABLE_ADDRESS); connector.start(); theSocket.setSoTimeout(1000); Thread.sleep(10); assertTrue("Socket option not set during connect: 10 ", Math.abs(1000 - theSocket.getSoTimeout()) <= 10); Thread.sleep(50); theSocket.setSoTimeout(2000); assertTrue("Socket option not set during connect: 50 ", Math.abs(2000 - theSocket.getSoTimeout()) <= 10); connector.join(); Exception e = exceptionRef.get(); if (!(e instanceof SocketTimeoutException)) { fail(printStackTraceToString(e)); } } }
Source:
<code>protected void AddVmTemplateImages() { Guid srcStorageDomain = mImages.get(0).getstorage_id().getValue(); Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getId(), getVmTemplateId(), getVmTemplateName(), getVmId()); if (!diskImage.getstorage_id().equals(Guid.Empty)) { createParams.setStorageDomainId(diskImage.getstorage_id().getValue()); } else { createParams.setStorageDomainId(srcStorageDomain); } createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(getStorageDomainId().getValue()); createParams.setParentParemeters(getParameters()); getParameters().getImagesParameters().add(createParams); VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams, = ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); <START> QuotaManager.reduceCommandStorageSize(createParams.getStorageDomainId(), diskImage.getsize(), <END> getStoragePool().getQuotaEnforcementType(), getCommandId(), getParameters().getQuotaId()); getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); } }</code><technical_language>i this is needed images added in transaction</technical_language>

Target:
protected void AddVmTemplateImages() { Guid srcStorageDomain = mImages.get(0).getstorage_ids().get(0); Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getId(), getVmTemplateId(), getVmTemplateName(), getVmId()); if (!Guid.Empty.equals(diskImage.getstorage_ids().get(0))) { createParams.setStorageDomainId(diskImage.getstorage_ids().get(0)); } else { createParams.setStorageDomainId(srcStorageDomain); } createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(getStorageDomainId().getValue()); createParams.setParentParemeters(getParameters()); getParameters().getImagesParameters().add(createParams); VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams, = ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); QuotaManager.reduceCommandStorageSize(createParams.getStorageDomainId(), diskImage.getsize(), getStoragePool().getQuotaEnforcementType(), getCommandId(), getParameters().getQuotaId()); getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); } }
Source:
<code>public void write(JsonGenerator jg, DocumentModel document) throws IOException { jg.writeObjectFieldStart(NAME); int resultCount; try (SessionWrapper wrapper = ctx.getSession(document)) { String escapedId = NXQL.escapeString(document.getId()); resultCount = wrapper.getSession() .queryProjection( <START> String.format(org.nuxeo.ecm.platform.rendition.Constants.ALL_PUBLICATION_QUERY, <END> escapedId, escapedId), 0, 0) .size(); } jg.writeNumberField("resultsCount", resultCount); jg.writeEndObject(); }</code><technical_language>import class static import constant</technical_language>

Target:
public void write(JsonGenerator jg, DocumentModel document) throws IOException { jg.writeObjectFieldStart(NAME); int resultCount; try (SessionWrapper wrapper = ctx.getSession(document)) { String escapedId = NXQL.escapeString(document.getId()); resultCount = wrapper.getSession() .queryProjection( String.format(ALL_PUBLICATION_QUERY, escapedId, escapedId), 0, 0) .size(); } jg.writeNumberField("resultsCount", resultCount); jg.writeEndObject(); }
Source:
<code>public void testDeserializeSimpleDefinition() throws Exception { <START> String yaml = <END> "{\n" + " \"openapi\": \"3.0.0-rc0\",\n" + " \"info\": {\n" + " \"title\": \"Swagger Petstore\",\n" + " \"description\": \"This is a sample server Petstore server. You can find out more about Swagger at [<LINK_2>](<LINK_0> or on [irc.freenode.net, #swagger](<LINK_1> For this sample, you can use the api key `special-key` to test the authorization filters.\",\n" + " \"termsOfService\": \"<LINK_2>/terms/\",\n" + " \"contact\": {\n" + " \"email\": \"apiteam@swagger.io\"\n" + " },\n" + " \"license\": {\n" + " \"name\": \"Apache 2.0\",\n" + " \"url\": \"<LINK_4>\"\n" + " },\n" + " \"version\": \"1.0.0\"\n" + " }\n" + "}"; SwaggerParseResult result = new OpenAPIV3Parser().readContents(yaml, null, null); assertNotNull(result.getOpenAPI()); }</code><technical_language>this variable called json 'aint yaml..</technical_language>

Target:
public void testDeserializeSimpleDefinition() throws Exception { String json = "{\n" + " \"openapi\": \"3.0.0-rc0\",\n" + " \"info\": {\n" + " \"title\": \"Swagger Petstore\",\n" + " \"description\": \"This is a sample server Petstore server. You can find out more about Swagger at [<LINK_2>](<LINK_0> or on [irc.freenode.net, #swagger](<LINK_1> For this sample, you can use the api key `special-key` to test the authorization filters.\",\n" + " \"termsOfService\": \"<LINK_2>/terms/\",\n" + " \"contact\": {\n" + " \"email\": \"apiteam@swagger.io\"\n" + " },\n" + " \"license\": {\n" + " \"name\": \"Apache 2.0\",\n" + " \"url\": \"<LINK_4>\"\n" + " },\n" + " \"version\": \"1.0.0\"\n" + " }\n" + "}"; ParseOptions options = new ParseOptions(); options.setResolve(true); SwaggerParseResult result = new OpenAPIV3Parser().readContents(json, null, options); assertNotNull(result.getOpenAPI()); }
Source:
<code>public Page getNextPage() { try { batchId++; long start = System.nanoTime(); int batchSize = parquetReader.nextBatch(); readTimeNanos += System.nanoTime() - start; if (closed || batchSize <= 0) { close(); return null; } Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (constantBlocks[fieldId] != null) { blocks[fieldId] = constantBlocks[fieldId].getRegion(0, batchSize); } else { Type type = types.get(fieldId); Optional<Field> field = fields.get(fieldId); <START> int fieldIndex = useParquetColumnNames ? getFieldIndex(fileSchema, columnNames.get(fieldId)) : hiveColumnIndexes[fieldId]; <END> if (fieldIndex != -1 && field.isPresent()) { blocks[fieldId] = new LazyBlock(batchSize, new ParquetBlockLoader(field.get())); } else { blocks[fieldId] = RunLengthEncodedBlock.create(type, null, batchSize); } } } return new Page(batchSize, blocks); } catch (PrestoException e) { closeWithSuppression(e); throw e; } catch (RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, e); } }</code><technical_language>this if/else this is a complex expression</technical_language>

Target:
public Page getNextPage() { try { batchId++; long start = System.nanoTime(); int batchSize = parquetReader.nextBatch(); readTimeNanos += System.nanoTime() - start; if (closed || batchSize <= 0) { close(); return null; } Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (constantBlocks[fieldId] != null) { blocks[fieldId] = constantBlocks[fieldId].getRegion(0, batchSize); } else { Type type = types.get(fieldId); Optional<Field> field = fields.get(fieldId); int fieldIndex; if (useParquetColumnNames) { fieldIndex = getFieldIndex(fileSchema, columnNames.get(fieldId)); } else { fieldIndex = hiveColumnIndexes[fieldId]; } if (fieldIndex != -1 && field.isPresent()) { blocks[fieldId] = new LazyBlock(batchSize, new ParquetBlockLoader(field.get())); } else { blocks[fieldId] = RunLengthEncodedBlock.create(type, null, batchSize); } } } return new Page(batchSize, blocks); } catch (PrestoException e) { closeWithSuppression(e); throw e; } catch (RuntimeException e) { closeWithSuppression(e); throw new PrestoException(HIVE_CURSOR_ERROR, e); } }
Source:
<code>public void setUp() throws Exception { Path entryPath = Paths.get(getClass().getResource("/projects/default-spring-project").getPath()); testRepo.addContent(entryPath); projectName = testRepo.getName(); <START> String subPathToGithubArchive = "/archive/master.zip"; <END> String pathToGithubArchive = String.format("%s%s", testRepo.getHtmlUrl(), subPathToGithubArchive); TestFactoryInitializer.TestFactoryBuilder factoryBuilder = testFactoryInitializer.fromTemplate(FactoryTemplate.MINIMAL); ProjectConfigDto projectConfigDto = factoryBuilder.getWorkspace().getProjects().get(0); projectConfigDto.setName(projectName); projectConfigDto.setPath("/" + projectName); projectConfigDto.getSource().setParameters(ImmutableMap.of("skipFirstLevel", "true")); projectConfigDto.getSource().setType("zip"); projectConfigDto.getSource().setLocation(pathToGithubArchive); testFactory = factoryBuilder.build(); }</code><technical_language>subPathToGithubArchive is inline is used</technical_language>

Target:
public void setUp() throws Exception { Path entryPath = Paths.get(getClass().getResource("/projects/default-spring-project").getPath()); testRepo.addContent(entryPath); projectName = testRepo.getName(); String urlToDownloadZippedRepoFromGitHub = String.format("%s%s", testRepo.getHtmlUrl(), "/archive/master.zip"); TestFactoryInitializer.TestFactoryBuilder factoryBuilder = testFactoryInitializer.fromTemplate(FactoryTemplate.MINIMAL); ProjectConfigDto projectConfigDto = factoryBuilder.getWorkspace().getProjects().get(0); projectConfigDto.setName(projectName); projectConfigDto.setPath("/" + projectName); projectConfigDto.getSource().setParameters(ImmutableMap.of("skipFirstLevel", "true")); projectConfigDto.getSource().setType("zip"); projectConfigDto.getSource().setLocation(urlToDownloadZippedRepoFromGitHub); testFactory = factoryBuilder.build(); }
Source:
<code>private FileStorage getJarStorage (StreamlineConfiguration configuration, StorageManager storageManager) { FileStorage fileStorage = null; try { fileStorage = ReflectionHelper.newInstance(configuration.getFileStorageConfiguration().getClassName()); fileStorage.init(configuration.getFileStorageConfiguration().getProperties()); <START> if (fileStorage instanceof DbFileStorage) { <END> ((DbFileStorage) fileStorage).setStorageManager(storageManager); } } catch (Exception e) { throw new RuntimeException(e); } return fileStorage; }</code><technical_language>If a fan of interface, interface StorageManagerAware DbFileStorage implement it. more flexible FileStorage is a kind of plug-in</technical_language>

Target:
private FileStorage getJarStorage (StreamlineConfiguration configuration, StorageManager storageManager) { FileStorage fileStorage = null; try { fileStorage = ReflectionHelper.newInstance(configuration.getFileStorageConfiguration().getClassName()); fileStorage.init(configuration.getFileStorageConfiguration().getProperties()); if (fileStorage instanceof StorageManagerAware) { ((StorageManagerAware) fileStorage).setStorageManager(storageManager); } } catch (Exception e) { throw new RuntimeException(e); } return fileStorage; }
Source:
<code>public ServerSelector() { Queue<ServerComponent> widgets = getServers(); <START> if (initServer != null || Core.quickLaunchByUuid > 0) { <END> if (runServer(widgets)) { initServer = null; return; } } setLayout(new BorderLayout()); setPreferredSize(new Dimension(600, 350)); JPanel interior = new JPanel(null); int i = 0; int y = 0; while (widgets != null && !widgets.isEmpty()) { final ServerComponent w = widgets.poll(); w.setSize(300, 100); if (i % 2 == 0 && i != 0) { y += 100; } w.setLocation(i % 2 == 0 ? 0 : 300, y); interior.add(w); i++; } y += 100; interior.setPreferredSize(new Dimension(300, y)); JScrollPane scrlInterior = new JScrollPane(interior); scrlInterior .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrlInterior .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); add(scrlInterior); }</code><technical_language>a getter</technical_language>

Target:
public ServerSelector() { Queue<ServerComponent> widgets = getServers(); if (initServer != null || Core.getQuickLaunchByUuid() > -1) { if (runServer(widgets)) { initServer = null; return; } } setLayout(new BorderLayout()); setPreferredSize(new Dimension(600, 350)); JPanel interior = new JPanel(null); int i = 0; int y = 0; while (widgets != null && !widgets.isEmpty()) { final ServerComponent w = widgets.poll(); w.setSize(300, 100); if (i % 2 == 0 && i != 0) { y += 100; } w.setLocation(i % 2 == 0 ? 0 : 300, y); interior.add(w); i++; } y += 100; interior.setPreferredSize(new Dimension(300, y)); JScrollPane scrlInterior = new JScrollPane(interior); scrlInterior .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrlInterior .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); add(scrlInterior); }
Source:
<code><START> private List<Object> buildParametersList() { <END> List<Object> result = new ArrayList(this.generatorParameters.length); for (String param : this.generatorParameters) { result.add(param); } return result; }</code><technical_language>changed Arrays.asList(this.generatorParameters)</technical_language>

Target:
private List<String> buildParametersList() { return Arrays.asList(this.generatorParameters); }
Source:
<code><START> public View getView(int position, View convertView, ViewGroup parent) { <END> View view; if (convertView == null) { view = mInflater.inflate(mResource, parent, false); } else { view = convertView; } final DishDetail current = getItem(position); ImageView image = (ImageView) view.findViewById(R.id.dish_image); image.setImageBitmap(ImageHelper.getImage(current.getDishImage())); TextView name = (TextView) view.findViewById(R.id.dish_name); name.setText(current.getDishName()); TextView price = (TextView) view.findViewById(R.id.dish_price); price.setText(String.valueOf(current.getDishPrice())); final TextView amount = (TextView) view.findViewById(R.id.count); amount.setText(String.valueOf(current.getDishCount())); Button rm = (Button) view.findViewById(R.id.descend_copy); rm.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int count = current.getDishCount() - 1; if (count < 0) { return; } current.setDishCount(count); mOrderManager.setDishCopy(current.getId(), count); amount.setText(String.valueOf(current.getDishCount())); showDishCount(); showTotalPrice(mOrderManager.getTotalPrice()); } }); Button add = (Button) view.findViewById(R.id.add_copy); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int count = current.getDishCount() + 1; current.setDishCount(count); mOrderManager.setDishCopy(current.getId(), count); amount.setText(String.valueOf(current.getDishCount())); showDishCount(); showTotalPrice(mOrderManager.getTotalPrice()); } }); return view; }</code><technical_language>a view holder get view</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = mInflater.inflate(mResource, parent, false); viewHolder = new ViewHolder(); viewHolder.dishImage = (ImageView) convertView.findViewById(R.id.dish_image); viewHolder.dishName = (TextView) convertView.findViewById(R.id.dish_name); viewHolder.dishPrice = (TextView) convertView.findViewById(R.id.dish_price); viewHolder.dishAmount = (TextView) convertView.findViewById(R.id.count); viewHolder.increaseButton = (Button) convertView.findViewById(R.id.add_copy); viewHolder.decreaseButton = (Button) convertView.findViewById(R.id.descend_copy); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } setDishDetails(viewHolder, position); return convertView; }
Source:
<code>public boolean accept(Issue issue, IssueFilterChain chain) { Integer line = issue.line(); RuleKey ruleKey = issue.ruleKey(); if (line != null) { Multimap<Integer, String> suppressWarningsLines = suppressWarningsLinesByResource.get(issue.componentKey()); if (suppressWarningsLines != null && suppressWarningsLines.containsKey(line)) { Collection<String> lineWarnings = suppressWarningsLines.get(line); for (String warning : lineWarnings) { <START> if ((warningIsTheRuleName(warning, ruleKey) || "all".equals(warning)) && !"S1309".equals(ruleKey.rule())) { <END> return false; } } } } return chain.accept(issue); }</code><technical_language>This condition rewrited small methods</technical_language>

Target:
public boolean accept(Issue issue, IssueFilterChain chain) { for (String warning : getWarningsByLine(issue)) { if (issueShouldNotBeReported(warning, issue)) { return false; } } return chain.accept(issue); }
Source:
<code>public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final ModelNode address = operation.require(OP_ADDR); <START> final String driverName = PathAddress.pathAddress(address).getLastElement().getValue(); <END> if (context.isNormalServer()) { context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { ServiceController<?> sc = context.getServiceRegistry(false).getRequiredService( ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE); DriverRegistry driverRegistry = DriverRegistry.class.cast(sc.getValue()); ModelNode result = new ModelNode(); InstalledDriver driver = driverRegistry.getInstalledDriver(driverName); String dataSourceClsName = driver.getDataSourceClassName(); String xaDataSourceClsName = driver.getXaDataSourceClassName(); if (dataSourceClsName != null) { ModelNode dsNode = new ModelNode(); dsNode.get(dataSourceClsName).set( mapToModelNode(findPropsFromCls(driver.getModuleName(), dataSourceClsName))); result.add(dsNode); } if (xaDataSourceClsName != null) { ModelNode xaDsNode = new ModelNode(); xaDsNode.get(xaDataSourceClsName).set( mapToModelNode(findPropsFromCls(driver.getModuleName(), xaDataSourceClsName))); result.add(xaDsNode); } context.getResult().set(result); } }, OperationContext.Stage.RUNTIME); } }</code><technical_language>This be: final String driverName = context.getCurrentAddressValue();</technical_language>

Target:
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final String driverName = context.getCurrentAddressValue(); if (context.isNormalServer()) { context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { ServiceController<?> sc = context.getServiceRegistry(false).getRequiredService( ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE); DriverRegistry driverRegistry = DriverRegistry.class.cast(sc.getValue()); ModelNode result = new ModelNode(); InstalledDriver driver = driverRegistry.getInstalledDriver(driverName); String dataSourceClsName = driver.getDataSourceClassName(); String xaDataSourceClsName = driver.getXaDataSourceClassName(); if (dataSourceClsName != null) { ModelNode dsNode = new ModelNode(); dsNode.get(dataSourceClsName).set( mapToModelNode(findPropsFromCls(driver.getModuleName(), dataSourceClsName))); result.add(dsNode); } if (xaDataSourceClsName != null) { ModelNode xaDsNode = new ModelNode(); xaDsNode.get(xaDataSourceClsName).set( mapToModelNode(findPropsFromCls(driver.getModuleName(), xaDataSourceClsName))); result.add(xaDsNode); } context.getResult().set(result); } }, OperationContext.Stage.RUNTIME); } }
Source:
<code>protected byte[] getFastDigest(Path path) throws IOException { <START> if (hashAttributeName.isEmpty()) <END> return null; return getxattr(path, hashAttributeName, true); }</code><technical_language>nit: please enclosing braces. Alternately, a ternary operator fine here</technical_language>

Target:
protected byte[] getFastDigest(Path path) throws IOException { return hashAttributeName.isEmpty() ? null : getxattr(path, hashAttributeName, true); }
Source:
<code>public static void output(SpatialPartitioningState state, BlockBuilder out) { if (state.getCount() == 0) { out.appendNull(); return; } List<Rectangle> samples = state.getSamples(); int partitionCount = state.getPartitionCount(); <START> int maxItemsPerNode = (int) (Math.ceil(samples.size() * 1.0 / partitionCount)); <END> Rectangle envelope = state.getExtent(); Rectangle paddedExtent = new Rectangle(envelope.getXMin(), envelope.getYMin(), envelope.getXMax() + 0.01, envelope.getYMax() + 0.01); VARCHAR.writeString(out, KDB_TREE_CODEC.toJson(buildKDBTree(maxItemsPerNode, partitionCount, paddedExtent, samples))); }</code><technical_language>toIntExact</technical_language>

Target:
public static void output(SpatialPartitioningState state, BlockBuilder out) { if (state.getCount() == 0) { out.appendNull(); return; } List<Rectangle> samples = state.getSamples(); int partitionCount = state.getPartitionCount(); int maxItemsPerNode = (samples.size() + partitionCount - 1) / partitionCount; Rectangle envelope = state.getExtent(); Rectangle paddedExtent = new Rectangle(envelope.getXMin(), envelope.getYMin(), Math.nextUp(envelope.getXMax()), Math.nextUp(envelope.getYMax())); VARCHAR.writeString(out, KdbTreeUtils.toJson(buildKdbTree(maxItemsPerNode, paddedExtent, samples))); }
Source:
<code>private void copyToClipboard(String url) { Context context = new ContextThemeWrapper(CredentialsActivity.this, getTheme()); try { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(getString(R.string.app_name), url); <START> if (clipboard != null) { clipboard.setPrimaryClip(clip); } <END> Toast.makeText(context, R.string.simperium_error_browser_copy_success, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(context, R.string.simperium_error_browser_copy_failure, Toast.LENGTH_SHORT).show(); } }</code><technical_language>If clipboard is null copy data clipboard, show a snack message stating successful. Is intentional</technical_language>

Target:
private void copyToClipboard(String url) { Context context = new ContextThemeWrapper(CredentialsActivity.this, getTheme()); try { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(getString(R.string.app_name), url); if (clipboard != null) { clipboard.setPrimaryClip(clip); Toast.makeText(context, R.string.simperium_error_browser_copy_success, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, R.string.simperium_error_browser_copy_failure, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Toast.makeText(context, R.string.simperium_error_browser_copy_failure, Toast.LENGTH_SHORT).show(); } }
Source:
<code>protected void tick(Block b) { BlockMenu inv = BlockStorage.getInventory(b); if (isProcessing(b)) { int timeleft = progress.get(b); if (timeleft > 0) { ChestMenuUtils.updateProgressbar(inv, 22, timeleft, processing.get(b).getTicks(), getProgressBar()); if (!takeCharge(b.getLocation())) { return; } progress.put(b, timeleft - 1); <START> } else { if (!takeCharge(b.getLocation())) { return; } <END> inv.replaceExistingItem(22, new CustomItem(Material.BLACK_STAINED_GLASS_PANE, " ")); for (ItemStack output : processing.get(b).getOutput()) { inv.pushItem(output.clone(), getOutputSlots()); } Bukkit.getPluginManager().callEvent(new AsyncMachineProcessCompleteEvent(b.getLocation(), AContainer.this, getProcessing(b))); progress.remove(b); processing.remove(b); } } else { MachineRecipe next = findNextRecipe(inv); if (next != null) { processing.put(b, next); progress.put(b, next.getTicks()); } } }</code><technical_language>need for this nesting unnecessary guard blocks. suggestion } else if (takeCharge(b.getLocation())) {</technical_language>

Target:
protected void tick(Block b) { BlockMenu inv = BlockStorage.getInventory(b); if (isProcessing(b)) { if (takeCharge(b.getLocation())) { int timeleft = progress.get(b); if (timeleft > 0) { ChestMenuUtils.updateProgressbar(inv, 22, timeleft, processing.get(b).getTicks(), getProgressBar()); progress.put(b, timeleft - 1); } else { inv.replaceExistingItem(22, new CustomItem(Material.BLACK_STAINED_GLASS_PANE, " ")); for (ItemStack output : processing.get(b).getOutput()) { inv.pushItem(output.clone(), getOutputSlots()); } Bukkit.getPluginManager().callEvent(new AsyncMachineProcessCompleteEvent(b.getLocation(), AContainer.this, getProcessing(b))); progress.remove(b); processing.remove(b); } } } else { MachineRecipe next = findNextRecipe(inv); if (next != null) { processing.put(b, next); progress.put(b, next.getTicks()); } } }
Source:
<code>public void testCustomDepthDimensionConvertion() throws IOException, ParseException { MockDimensionReader reader = new MockDimensionReader(); reader.metadata.put("HAS_MYDIM_DOMAIN", "true"); reader.metadata.put("MYDIM_DOMAIN_DATATYPE", "java.lang.Double"); ReaderDimensionsAccessor accessor = new ReaderDimensionsAccessor(reader); List<Object> converted = accessor.convertDimensionValue("MYDIM", Arrays.asList("10/20")); assertEquals(1, converted.size()); <START> NumberRange<Double> range = new NumberRange<Double>(Double.class, 10d, 20d); <END> assertEquals(range, converted.get(0)); }</code><technical_language>"expected" instead of range</technical_language>

Target:
public void testCustomDepthDimensionConvertion() throws IOException, ParseException { MockDimensionReader reader = new MockDimensionReader(); reader.metadata.put("HAS_MYDIM_DOMAIN", "true"); reader.metadata.put("MYDIM_DOMAIN_DATATYPE", "java.lang.Double"); ReaderDimensionsAccessor accessor = new ReaderDimensionsAccessor(reader); List<Object> converted = accessor.convertDimensionValue("MYDIM", Arrays.asList("10/20")); assertEquals(1, converted.size()); NumberRange<Double> expected = new NumberRange<Double>(Double.class, 10d, 20d); assertEquals(expected, converted.get(0)); }
Source:
<code>Observable createRequestObservable(final Callable<ResponseWrapper> request) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { try { ResponseWrapper wrapper = request.call(); <START> if (subscriber.isUnsubscribed()){ <END> return; } subscriber.onNext(wrapper.responseBody); subscriber.onCompleted(); } catch (RetrofitError e) { subscriber.onError(e); } catch (Exception e) { throw new RuntimeException(e); } } }).subscribeOn(scheduler); }</code><technical_language>nit: space {</technical_language>

Target:
Observable createRequestObservable(final Callable<ResponseWrapper> request) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { if (subscriber.isUnsubscribed()) { return; } try { ResponseWrapper wrapper = request.call(); if (subscriber.isUnsubscribed()) { return; } subscriber.onNext(wrapper.responseBody); subscriber.onCompleted(); } catch (RetrofitError e) { subscriber.onError(e); } catch (Exception e) { throw new RuntimeException(e); } } }).subscribeOn(scheduler); }
Source:
<code>private void pollWorkers() { AllNodes allNodes = getAllNodes(); Set<InternalNode> aliveNodes = ImmutableSet.<InternalNode>builder() .addAll(allNodes.getActiveNodes()) .addAll(allNodes.getShuttingDownNodes()) .build(); ImmutableSet<String> aliveNodeIds = aliveNodes.stream() .map(InternalNode::getNodeIdentifier) .collect(toImmutableSet()); Set<String> deadNodes = difference(nodeStates.keySet(), aliveNodeIds).immutableCopy(); nodeStates.keySet().removeAll(deadNodes); for (InternalNode node : aliveNodes) { if (protocol.equals(CommunicationProtocol.THRIFT) && node.getThriftPort().isPresent()) { RemoteNodeState remoteNodeState = nodeStates.get(node.getNodeIdentifier()); <START> if (!(remoteNodeState instanceof ThriftRemoteNodeState)) { <END> nodeStates.put(node.getNodeIdentifier(), new ThriftRemoteNodeState(driftClient, uriBuilderFrom(node.getInternalUri()).scheme("thrift").port(node.getThriftPort().getAsInt()).build())); } } else { nodeStates.putIfAbsent(node.getNodeIdentifier(), new HttpRemoteNodeState(httpClient, uriBuilderFrom(node.getInternalUri()).appendPath("/v1/info/state").build())); } } nodeStates.values().forEach(RemoteNodeState::asyncRefresh); refreshNodesInternal(); }</code><technical_language>Is understanding correct guard situation a node changed thrift, announcement internal state management updated state yet? said, theoretically is if a thrift -> http change? Do need handle that? is understanding totally off</technical_language>

Target:
private void pollWorkers() { AllNodes allNodes = getAllNodes(); Set<InternalNode> aliveNodes = ImmutableSet.<InternalNode>builder() .addAll(allNodes.getActiveNodes()) .addAll(allNodes.getShuttingDownNodes()) .build(); ImmutableSet<String> aliveNodeIds = aliveNodes.stream() .map(InternalNode::getNodeIdentifier) .collect(toImmutableSet()); Set<String> deadNodes = difference(nodeStates.keySet(), aliveNodeIds).immutableCopy(); nodeStates.keySet().removeAll(deadNodes); for (InternalNode node : aliveNodes) { switch (protocol) { case HTTP: nodeStates.putIfAbsent(node.getNodeIdentifier(), new HttpRemoteNodeState(httpClient, uriBuilderFrom(node.getInternalUri()).appendPath("/v1/info/state").build())); break; case THRIFT: if (node.getThriftPort().isPresent()) { nodeStates.put(node.getNodeIdentifier(), new ThriftRemoteNodeState(driftClient, uriBuilderFrom(node.getInternalUri()).scheme("thrift").port(node.getThriftPort().getAsInt()).build())); } else { } break; } } nodeStates.values().forEach(RemoteNodeState::asyncRefresh); refreshNodesInternal(); }
Source:
<code>private KalturaLiveEntry onClientConnect(IClient client) { WMSProperties properties = client.getProperties(); String rtmpUrl = properties.getPropertyStr(LiveStreamEntry.CLIENT_PROPERTY_CONNECT_URL); logger.debug("Geting url: " + rtmpUrl); String queryString = getRtmpUrlParameters(rtmpUrl); if (queryString ==null) { logger.error("Invalid rtmp url provided: " + rtmpUrl); client.rejectConnection("Invalid rtmp url provided: " + rtmpUrl); client.shutdownClient(); return null; } try { return onClientConnect(properties, queryString); } catch (KalturaApiException | ClientConnectException e) { <START> logger.error("Entry authentication failed [" + queryString + "]: " + e.getMessage()); <END> client.rejectConnection("Unable to authenticate entry [" + queryString + "]", "Unable to authenticate entry [" + queryString + "]"); client.shutdownClient(); } return null; }</code><technical_language>i put entire url, queryString in logs</technical_language>

Target:
private KalturaLiveEntry onClientConnect(IClient client) { WMSProperties properties = client.getProperties(); String rtmpUrl = properties.getPropertyStr(LiveStreamEntry.CLIENT_PROPERTY_CONNECT_URL); logger.debug("Geting url: " + rtmpUrl+ " from client "+client.getIp()); String queryString = getRtmpUrlParameters(rtmpUrl); if (queryString ==null) { logger.error("Invalid rtmp url provided: " + rtmpUrl); client.rejectConnection("Invalid rtmp url provided: " + rtmpUrl); client.shutdownClient(); return null; } try { return onClientConnect(properties, queryString); } catch (KalturaApiException | ClientConnectException e) { logger.error("Entry authentication failed with url [" + rtmpUrl + "]: " + e.getMessage()); client.rejectConnection("Unable to authenticate ur; [" + rtmpUrl + "]"); client.shutdownClient(); } return null; }
Source:
<code>public static void deleteProperty(String key) throws IOException, KuraException { Properties properties = KuranetConfig.getProperties(); <START> if (!properties.isEmpty()) { <END> if (properties.containsKey(key)) { s_logger.debug("Deleting property {}", key); properties.remove(key); KuranetConfig.storeProperties(properties); } else { s_logger.debug("Property does not exist {}", key); } } }</code><technical_language>above. do need this check</technical_language>

Target:
public static void deleteProperty(String key) throws IOException, KuraException { Properties properties = KuranetConfig.getProperties(); if (properties.containsKey(key)) { s_logger.debug("Deleting property {}", key); properties.remove(key); KuranetConfig.storeProperties(properties); } else { s_logger.debug("Property does not exist {}", key); } }
Source:
<code>public VmSnapshotListModel() { setTitle(ConstantsManager.getInstance().getConstants().snapshotsTitle()); setHelpTag(HelpTag.snapshots); setHashName("snapshots"); setNewCommand(new UICommand("New", this)); setPreviewCommand(new UICommand("Preview", this)); setCustomPreviewCommand(new UICommand("CustomPreview", this)); setCommitCommand(new UICommand("Commit", this)); setUndoCommand(new UICommand("Undo", this)); setRemoveCommand(new UICommand("Remove", this)); setCloneVmCommand(new UICommand("CloneVM", this)); setCloneTemplateCommand(new UICommand("CloneTemplate", this)); setCanSelectSnapshot(new EntityModel()); getCanSelectSnapshot().setEntity(true); setSnapshotsMap(new HashMap<Guid, SnapshotModel>()); setVmDisks(new ArrayList<DiskImage>()); setComparator(new Comparator<Snapshot>() { @Override public int compare(Snapshot s1, Snapshot s2) { <START> if (s1.getType() == SnapshotType.ACTIVE || s1.getType() == SnapshotType.PREVIEW) { return -1; } if (s2.getType() == SnapshotType.ACTIVE || s2.getType() == SnapshotType.PREVIEW) { return 1; } <END> return s2.getCreationDate().compareTo(s1.getCreationDate()); } }); }</code><technical_language>If snapshot is active other is in preview, this generate inconsistent sorting could, theoretically, endless loop while sorting. A correct implementation of this block this: int typeCompare = Boolean.compare( s1.getType() == SnapshotType.ACTIVE || s1.getType() == SnapshotType.PREVIEW), s2.getType() == SnapshotType.ACTIVE || s2.getType() == SnapshotType.PREVIEW)); if (typeCompare != 0) { return typeCompare; } // compare creation dates</technical_language>

Target:
public VmSnapshotListModel() { setTitle(ConstantsManager.getInstance().getConstants().snapshotsTitle()); setHelpTag(HelpTag.snapshots); setHashName("snapshots"); setNewCommand(new UICommand("New", this)); setPreviewCommand(new UICommand("Preview", this)); setCustomPreviewCommand(new UICommand("CustomPreview", this)); setCommitCommand(new UICommand("Commit", this)); setUndoCommand(new UICommand("Undo", this)); setRemoveCommand(new UICommand("Remove", this)); setCloneVmCommand(new UICommand("CloneVM", this)); setCloneTemplateCommand(new UICommand("CloneTemplate", this)); setCanSelectSnapshot(new EntityModel()); getCanSelectSnapshot().setEntity(true); setSnapshotsMap(new HashMap<Guid, SnapshotModel>()); setVmDisks(new ArrayList<DiskImage>()); setComparator(new Comparator<Snapshot>() { @Override public int compare(Snapshot s1, Snapshot s2) { int typeCompare = Boolean.compare( s1.getType() == SnapshotType.ACTIVE || s1.getType() == SnapshotType.PREVIEW, s2.getType() == SnapshotType.ACTIVE || s2.getType() == SnapshotType.PREVIEW); if (typeCompare != 0) { return typeCompare; } return s2.getCreationDate().compareTo(s1.getCreationDate()); } }); }
Source:
<code>public List<Developer> getDevelopersForCertificationBody(final Long certificationBodyId) { <START> String hql = "FROM DeveloperCertificationBodyMapEntity " <END> + "JOIN FETCH main.developer dev " + "JOIN FETCH main.certificationBody cb " + "WHERE cb.id = :certificationBodyId"; return entityManager .createQuery(hql, DeveloperCertificationBodyMapEntity.class) .setParameter("certificationBodyId", certificationBodyId) .getResultList().stream() .map(item -> new Developer(new DeveloperDTO(item.getDeveloper()))) .collect(Collectors.<Developer> toList()); }</code><technical_language>I expecting "FROM DeveloperCertificationBodyMapEntity main " in method above. (ie. I "main" is missing)</technical_language>

Target:
public List<Developer> getDevelopersForCertificationBody(final Long certificationBodyId) { String hql = "FROM DeveloperCertificationBodyMapEntity main" + "JOIN FETCH main.developer dev " + "JOIN FETCH main.certificationBody cb " + "WHERE cb.id = :certificationBodyId"; return entityManager .createQuery(hql, DeveloperCertificationBodyMapEntity.class) .setParameter("certificationBodyId", certificationBodyId) .getResultList().stream() .map(item -> new Developer(new DeveloperDTO(item.getDeveloper()))) .collect(Collectors.<Developer> toList()); }
Source:
<code>private static ImmutableMap<BulkObject,Long> computeRealBlobOffset(final ImmutableMap<BulkObject, Long> blobLengths) { if (Guard.isMapNullOrEmpty(blobLengths)) { return ImmutableMap.of(); } final Map<BulkObject, Long> realOffsets = new HashMap<>(); final ImmutableSortedSet<BulkObject> bulkObjects = ImmutableSortedSet.copyOf(BlobComparator.create(), blobLengths.keySet()); final ImmutableList<BulkObject> sortedList = ImmutableList.copyOf(bulkObjects); final int listLength = sortedList.size(); for(int i = 0; i < listLength; i++) { if(i == 0) { <START> realOffsets.put(sortedList.get(0), 0L); <END> continue; } final BulkObject previous = sortedList.get(i-1); final long previousOffset = realOffsets.get(previous); final long previousSize = blobLengths.get(previous); realOffsets.put(sortedList.get(i), previousOffset + previousSize); } return ImmutableMap.copyOf(realOffsets); }</code><technical_language>is this for loop instead of it</technical_language>

Target:
private static ImmutableMap<BulkObject,Long> computeRealBlobOffset(final ImmutableMap<BulkObject, Long> blobLengths) { if (Guard.isMapNullOrEmpty(blobLengths)) { return ImmutableMap.of(); } final Map<BulkObject, Long> realOffsets = new HashMap<>(); final ImmutableSortedSet<BulkObject> bulkObjects = ImmutableSortedSet.copyOf(BlobComparator.create(), blobLengths.keySet()); final ImmutableList<BulkObject> sortedList = ImmutableList.copyOf(bulkObjects); final int listLength = sortedList.size(); realOffsets.put(sortedList.get(0), 0L); for(int i = 1; i < listLength; i++) { final BulkObject previous = sortedList.get(i-1); final long previousOffset = realOffsets.get(previous); final long previousSize = blobLengths.get(previous); realOffsets.put(sortedList.get(i), previousOffset + previousSize); } return ImmutableMap.copyOf(realOffsets); }
Source:
<code>private static IThemeEngine createThemeEngine(Display display, IEclipseContext appContext) { IContributionFactory contribution = (IContributionFactory) appContext .get(IContributionFactory.class.getName()); IEclipseContext cssContext = EclipseContextFactory.create(); cssContext.set(IContributionFactory.class.getName(), contribution); display.setData("org.eclipse.e4.ui.css.context", cssContext); Bundle bundle = WorkbenchSWTActivator.getDefault().getBundle(); <START> BundleContext context = bundle.getBundleContext(); <END> ServiceReference<?> ref = context .getServiceReference(IThemeManager.class.getName()); IThemeManager mgr = (IThemeManager) context.getService(ref); IThemeEngine themeEngine = mgr.getEngineForDisplay(display); appContext.set(IThemeEngine.class.getName(), themeEngine); return themeEngine; }</code><technical_language>reason this OSGi service out of appContext (so get OSGi EclipseContext)</technical_language>

Target:
private static IThemeEngine createThemeEngine(Display display, IEclipseContext appContext) { IContributionFactory contribution = (IContributionFactory) appContext .get(IContributionFactory.class.getName()); IEclipseContext cssContext = EclipseContextFactory.create(); cssContext.set(IContributionFactory.class.getName(), contribution); display.setData("org.eclipse.e4.ui.css.context", cssContext); IThemeManager mgr = appContext.get(IThemeManager.class); IThemeEngine themeEngine = mgr.getEngineForDisplay(display); appContext.set(IThemeEngine.class.getName(), themeEngine); return themeEngine; }