auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>int scan(BinaryDeque.BinaryDequeScanner scanner) throws IOException { SegmentReader reader = openForRead(SCANNER_CURSOR); try { validateHeader(); int initialEntryCount = getNumEntries(); if (initialEntryCount == 0) { return 0; } long lastReadId = -1; while (true) { DBBPool.BBContainer cont = null; try { cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY, true); } catch(IOException e) { reader.truncateToCurrentReadIndex(lastReadId); } <START> if (cont == null) { <END> break; } try { lastReadId = scanner.scan(cont); assert(m_startId == -1 || lastReadId != -1); } finally { cont.discard(); } } int entriesScanned = reader.readIndex(); int entriesTruncated = initialEntryCount - entriesScanned; if (!m_isActive && !isFinal() && entriesTruncated == 0) { finalize(false); } return entriesTruncated; } finally { reader.close(); } }</code><technical_language>this change losing information in exception message logged in previous implementation</technical_language>

Target:
int scan(BinaryDeque.BinaryDequeScanner scanner) throws IOException { SegmentReader reader = openForRead(SCANNER_CURSOR); try { validateHeader(); int initialEntryCount = getNumEntries(); if (initialEntryCount == 0) { return 0; } long lastReadId = -1; while (true) { DBBPool.BBContainer cont = null; try { cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY, true); } catch(IOException e) { m_usageSpecificLog.warn("Truncating segment file to the last safe point due to error", e); reader.truncateToCurrentReadIndex(lastReadId); } if (cont == null) { break; } try { lastReadId = scanner.scan(cont); assert(m_startId == -1 || lastReadId != -1); } finally { cont.discard(); } } int entriesScanned = reader.readIndex(); int entriesTruncated = initialEntryCount - entriesScanned; if (!m_isActive && !isFinal() && entriesTruncated == 0) { finalize(false); } return entriesTruncated; } finally { reader.close(); } }
Source:
<code>public Configuration getConfiguration() { <START> return new ConfigurationImpl(srvCtx.getConfiguration()); <END> }</code><technical_language>Do want create a new object getConfiguration() methods called? I thinking of case user code passes ServiceEnv calls getConfiguration().get() frequently create objects. create a single ConfigurationImpl object in ServiceEnvironment constructor</technical_language>

Target:
public Configuration getConfiguration() { return conf; }
Source:
<code>public TiffRasterData readRasterData(Rectangle subImage) throws ImageReadException, IOException { int xRaster; int yRaster; int rasterWidth; int rasterHeight; if (subImage != null) { xRaster = subImage.x; yRaster = subImage.y; rasterWidth = subImage.width; rasterHeight = subImage.height; } else { xRaster = 0; yRaster = 0; rasterWidth = width; rasterHeight = height; } float[] rasterData = new float[rasterWidth * rasterHeight]; <START> final int strip0 = yRaster / rowsPerStrip; <END> final int strip1 = (yRaster + rasterHeight - 1) / rowsPerStrip; for (int strip = strip0; strip <= strip1; strip++) { int yStrip = strip * rowsPerStrip; int rowsRemaining = height - yStrip; int rowsInThisStrip = rowsRemaining > rowsPerStrip ? rowsPerStrip : rowsRemaining; int bytesPerRow = (bitsPerPixel * width + 7) / 8; int bytesPerStrip = rowsInThisStrip * bytesPerRow; final byte[] compressed = imageData.getImageData(strip).getData(); final byte[] decompressed = decompress(compressed, compression, bytesPerStrip, width, rowsInThisStrip); int[] blockData = unpackFloatingPointSamples( width, (int) rowsInThisStrip, width, decompressed, predictor, bitsPerPixel, byteOrder); transferBlockToRaster(0, yStrip, width, (int) rowsInThisStrip, blockData, xRaster, yRaster, rasterWidth, rasterHeight, rasterData); } return new TiffRasterData(rasterWidth, rasterHeight, rasterData); }</code><technical_language>chance-even if remote-that rowsPerStrip zero? of reasons 1.0-alpha1 long (couple years work started?) largely due CVE's created for sanselan. of CVE, if I mistaken, a division zero (or another sort of arithmetic error?), caused exception some infinite loop large memory allocation (allowing users perform DDOS). If zero, need worry. Otherwise, if risk, set a quick validation (here constructor)</technical_language>

Target:
public TiffRasterData readRasterData(Rectangle subImage) throws ImageReadException, IOException { int xRaster; int yRaster; int rasterWidth; int rasterHeight; if (subImage != null) { xRaster = subImage.x; yRaster = subImage.y; rasterWidth = subImage.width; rasterHeight = subImage.height; } else { xRaster = 0; yRaster = 0; rasterWidth = width; rasterHeight = height; } float[] rasterData = new float[rasterWidth * rasterHeight]; final int strip0 = yRaster / rowsPerStrip; final int strip1 = (yRaster + rasterHeight - 1) / rowsPerStrip; for (int strip = strip0; strip <= strip1; strip++) { int yStrip = strip * rowsPerStrip; int rowsRemaining = height - yStrip; int rowsInThisStrip = Math.min(rowsRemaining, rowsPerStrip); int bytesPerRow = (bitsPerPixel * width + 7) / 8; int bytesPerStrip = rowsInThisStrip * bytesPerRow; final byte[] compressed = imageData.getImageData(strip).getData(); final byte[] decompressed = decompress(compressed, compression, bytesPerStrip, width, rowsInThisStrip); int[] blockData = unpackFloatingPointSamples( width, (int) rowsInThisStrip, width, decompressed, predictor, bitsPerPixel, byteOrder); transferBlockToRaster(0, yStrip, width, (int) rowsInThisStrip, blockData, xRaster, yRaster, rasterWidth, rasterHeight, rasterData); } return new TiffRasterData(rasterWidth, rasterHeight, rasterData); }
Source:
<code>public WSAuthorizationManager(String serverUrl, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteAuthorizationManagerServiceStub(configCtxt, serverUrl + SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault e) { if (log.isDebugEnabled()) { log.debug(CONNECTION_ERROR_MESSAGE, e); } <START> throw new UserStoreException(); <END> } }</code><technical_language>add some message exception</technical_language>

Target:
public WSAuthorizationManager(String serverUrl, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteAuthorizationManagerServiceStub(configCtxt, serverUrl + SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault e) { throw new UserStoreException("Axis error occurred while creating service client stub", e); } }
Source:
<code>public final void createsKey() throws Exception { final PublicKeys keys = this.keys(); final PublicKey key = keys.create("rsa", "rsa sh"); MatcherAssert.assertThat( keys.iterate().iterator().next(), <START> Matchers.equalTo(key) <END> ); MatcherAssert.assertThat( key.user(), Matchers.equalTo( keys.user() ) ); keys.remove( key.number() ); MatcherAssert.assertThat( keys.iterate(), Matchers.not(Matchers.hasItem(key)) ); }</code><technical_language>This assertion fail if is more public key repo testing on. I a safe assumption. Matchers.hasItem() I think</technical_language>

Target:
public final void createsKey() throws Exception { final PublicKeys keys = this.keys(); final PublicKey key = keys.create("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDS+TF7+bae4UKj6nec1oipiP9Ysc6mBPszB80z13tMZBlsPCOiLVAMO2ER/wpnKHd/VylmYr5c6wc3kSj88846VHUhQDN7fLd/km06KTdW4+9db7HBfvr0063eDdi1lg8jlnccegeeqKsG39+iVQban7ugcPyJtjQE9k7JjYBT+SOgupWkYPVO+5Z3xF6VJL8gUTIMgoovgTabFx60t5h5UPtNaGbdcSlHhLOlWn8I7tHvwbYdhZVqlCC450rieXo8PpjndG3crcuHPZPDVSSXyqRpguIxVEVjXd3B/0vrhXJQJC4u0ukOOytLNL6Gzz3oK7SIB0mqWJ4Mo0Wp+zeX jac.wshmstr@gmail.com"); try { MatcherAssert.assertThat( keys.iterate(), Matchers.hasItem(key) ); MatcherAssert.assertThat( key.user(), Matchers.equalTo( keys.user() ) ); } finally { keys.remove(key.number()); } MatcherAssert.assertThat( keys.iterate(), Matchers.not(Matchers.hasItem(key)) ); }
Source:
<code>public static PinotDataBitSetV2 createBitSet(PinotDataBuffer pinotDataBuffer, int numBitsPerValue) { <START> switch (numBitsPerValue) { <END> case 2: return new Bit2Encoded(pinotDataBuffer, numBitsPerValue); case 4: return new Bit4Encoded(pinotDataBuffer, numBitsPerValue); case 8: return new Bit8Encoded(pinotDataBuffer, numBitsPerValue); case 16: return new Bit16Encoded(pinotDataBuffer, numBitsPerValue); case 32: return new RawInt(pinotDataBuffer, numBitsPerValue); default: throw new UnsupportedOperationException(numBitsPerValue + "not supported by PinotDataBitSetV2"); } }</code><technical_language>0 (all zeros) 1 (0/1)</technical_language>

Target:
public static PinotDataBitSetV2 createBitSet(PinotDataBuffer pinotDataBuffer, int numBitsPerValue) { switch (numBitsPerValue) { case 1: return new Bit1Encoded(pinotDataBuffer, numBitsPerValue); case 2: return new Bit2Encoded(pinotDataBuffer, numBitsPerValue); case 4: return new Bit4Encoded(pinotDataBuffer, numBitsPerValue); case 8: return new Bit8Encoded(pinotDataBuffer, numBitsPerValue); case 16: return new Bit16Encoded(pinotDataBuffer, numBitsPerValue); case 32: return new RawInt(pinotDataBuffer, numBitsPerValue); default: throw new UnsupportedOperationException(numBitsPerValue + "not supported by PinotDataBitSetV2"); } }
Source:
<code>public synchronized CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { <START> if (fCurLocation.hashCode() != fPreviousHashCode) { <END> fPreviousHashCode = fCurLocation.hashCode(); fPreviousCurEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return fPreviousCurEvent; } return null; }</code><technical_language>I thought hashcode matches perfect matches. fCurlocation is a CTFLocation. preferable put a .equals instead. I sick yesterday reviewing code. :)</technical_language>

Target:
public synchronized CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { if (!fCurLocation.equals(fPreviousLocation)) { fPreviousLocation = fCurLocation; fPreviousEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return fPreviousEvent; } return null; }
Source:
<code>public void putTokenInfo(final UUID tokenUUID, final Map<String, Object> tokenInfo, final ByteBuffer principalKeyBuffer, final int ttl){ Preconditions.checkNotNull(tokenUUID, "tokenUUID is required"); Preconditions.checkNotNull(tokenUUID, "tokenInfo is required"); <START> Preconditions.checkNotNull(ttl, "ttl is required"); <END> logger.trace("putTokenInfo, token UUID: {}, tokenInfo: {}, ttl: {}", tokenUUID, tokenInfo, ttl); final BatchStatement batchStatement = new BatchStatement(); final Using usingTTL = QueryBuilder.ttl(ttl); tokenInfo.forEach((key, value) -> { ByteBuffer valueBuffer; if(key.equalsIgnoreCase(TOKEN_STATE)){ valueBuffer = toByteBuffer(value); }else{ valueBuffer = DataType.serializeValue(value, ProtocolVersion.NEWEST_SUPPORTED); } batchStatement.add( QueryBuilder.insertInto(TOKENS_TABLE) .value("key", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("column1", DataType.serializeValue(key, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", valueBuffer) .using(usingTTL)); }); if(principalKeyBuffer != null){ batchStatement.add( QueryBuilder.insertInto(PRINCIPAL_TOKENS_TABLE) .value("key", principalKeyBuffer) .value("column1", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", ByteBuffer.wrap( new byte[] { 0 } )) .using(usingTTL)); } session.execute(batchStatement); }</code><technical_language>null check for int</technical_language>

Target:
public void putTokenInfo(final UUID tokenUUID, final Map<String, Object> tokenInfo, final ByteBuffer principalKeyBuffer, final int ttl){ Preconditions.checkNotNull(tokenUUID, "tokenUUID is required"); Preconditions.checkNotNull(tokenUUID, "tokenInfo is required"); Preconditions.checkArgument(ttl > -1 , "ttl is required to be positive"); logger.trace("putTokenInfo, token UUID: {}, tokenInfo: {}, ttl: {}", tokenUUID, tokenInfo, ttl); final BatchStatement batchStatement = new BatchStatement(); final Using usingTTL = QueryBuilder.ttl(ttl); tokenInfo.forEach((key, value) -> { ByteBuffer valueBuffer; if(key.equalsIgnoreCase(TOKEN_STATE)){ valueBuffer = toByteBuffer(value); }else{ valueBuffer = DataType.serializeValue(value, ProtocolVersion.NEWEST_SUPPORTED); } batchStatement.add( QueryBuilder.insertInto(TOKENS_TABLE) .value("key", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("column1", DataType.serializeValue(key, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", valueBuffer) .using(usingTTL)); }); if(principalKeyBuffer != null){ batchStatement.add( QueryBuilder.insertInto(PRINCIPAL_TOKENS_TABLE) .value("key", principalKeyBuffer) .value("column1", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", ByteBuffer.wrap( new byte[] { 0 } )) .using(usingTTL)); } session.execute(batchStatement); }
Source:
<code><START> public synchronized void flush() throws IOException { <END> checkpoint(Checkpoint.MAX); }</code><technical_language>is a mix of synchronized blocks usage of readwrite locks. I checked flows. curious locks</technical_language>

Target:
public void flush() throws IOException { checkpoint(Checkpoint.MAX); }
Source:
<code>public ExecutionResult execute(Project project) { setProject(project); IRepositoryService service = (IRepositoryService) GlobalServiceRegister.getDefault().getService(IRepositoryService.class); IProxyRepositoryFactory factory = service.getProxyRepositoryFactory(); ExecutionResult executeFinal = null; List<IRepositoryViewObject> list = new ArrayList<IRepositoryViewObject>(); try { for (ERepositoryObjectType curTyp : getAllTypes()) { if (curTyp != null && curTyp.isResourceItem()) { list.addAll(factory.getAll(project, curTyp, true, true)); } } if (list.isEmpty()) { return ExecutionResult.NOTHING_TO_DO; } for (IRepositoryViewObject object : list) { ExecutionResult execute = null; if ((object.getProperty().eResource() == null || object.getProperty().getItem().eResource() == null) && (object instanceof RepositoryObject)) { Property updatedProperty = factory.reload(object.getProperty()); ((RepositoryObject) object).setProperty(updatedProperty); } <START> execute = this.migrateProjectSettings(project); <END> if (execute == ExecutionResult.FAILURE) { return ExecutionResult.FAILURE; } Item item = object.getProperty().getItem(); execute = execute(item); unloadObject(object); if (execute == ExecutionResult.FAILURE) { executeFinal = ExecutionResult.FAILURE; } if (executeFinal != ExecutionResult.FAILURE) { executeFinal = execute; } } return executeFinal; } catch (PersistenceException e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } }</code><technical_language>need execute migrateProjectSettings in loop ? try check project migration times . a time check migration</technical_language>

Target:
public ExecutionResult execute(Project project) { ExecutionResult result = super.execute(project); if (result == ExecutionResult.FAILURE) { return result; } result = this.migrateProjectSettings(project); return result; }
Source:
<code><START> public DoubleColumnSelector makeDoubleColumnSelector(String columnName) <END> { DoubleColumnSelector existing = doubleColumnSelectorMap.get(columnName); if (existing != null) { return existing; } else { DoubleColumnSelector newSelector = delegate.makeDoubleColumnSelector(columnName); DoubleColumnSelector prev = doubleColumnSelectorMap.putIfAbsent( columnName, newSelector ); return prev != null ? prev : newSelector; } }</code><technical_language>Put this method other similar methods implementation alike</technical_language>

Target:
public DoubleColumnSelector makeDoubleColumnSelector(String columnName) { final DoubleColumnSelector existing = doubleColumnSelectorMap.get(columnName); if (existing != null) { return existing; } return doubleColumnSelectorMap.computeIfAbsent(columnName, delegate::makeDoubleColumnSelector); }
Source:
<code>private String summary(String functionName, List<String> paramNames) { <START> Deque<List<String>> paramLines = wrap(functionName, paramNames, 80); <END> List<String> paramLinks = paramLines .stream() .map(params -> params .stream() .map(param -> String.format("<a href=\"#%s-%s\">%s</a>", functionName, param, param)) .collect(Collectors.joining(", "))) .collect(Collectors.toList()); return String.format( "%s(%s)", functionName, Joiner.on(String.format(",\n%s", Strings.repeat(" ", functionName != null ? functionName.length() + 1 : 0))) .join(paramLinks) ); }</code><technical_language>Extract 80 a constant, please. 100 sound? Is wide for display</technical_language>

Target:
private String summary(String functionName, List<String> paramNames) { List<List<String>> paramLines = wrap(functionName, paramNames, MAX_LINE_LENGTH); List<String> paramLinksLines = new ArrayList<>(); for (List<String> params : paramLines) { String paramLinksLine = params .stream() .map(param -> String.format("<a href=\"#%s-%s\">%s</a>", functionName, param, param)) .collect(Collectors.joining(", ")); paramLinksLines.add(paramLinksLine); } String paramList = Joiner .on(String.format(",\n%s", Strings.repeat(" ", functionName.length() + 1))) .join(paramLinksLines); return String.format("%s(%s)", functionName, paramList); }
Source:
<code>public void testCreatePerson() { BufferedMockRequest mockRequest =new BufferedMockRequest(tester.getApplication(), tester.getHttpSession(), tester.getServletContext(), "POST"); String jsonObj = gson.toJson(new PersonPojo("James", "Smith", "changeit")); mockRequest.setTextAsRequestBody(jsonObj); tester.setRequest(mockRequest); <START> tester.executeUrl("./personsmanager/persons"); <END> tester.getRequest().setMethod("GET"); tester.executeUrl("./personsmanager/persons"); assertTrue(tester.getLastResponseAsString().contains(jsonObj)); }</code><technical_language>assertions</technical_language>

Target:
public void testCreatePerson() { BufferedMockRequest mockRequest =new BufferedMockRequest(tester.getApplication(), tester.getHttpSession(), tester.getServletContext(), "POST"); String jsonObj = gson.toJson(new PersonPojo("James", "Smith", "changeit")); mockRequest.setTextAsRequestBody(jsonObj); tester.setRequest(mockRequest); tester.executeUrl("./personsmanager/persons"); assertEquals(jsonObj, tester.getLastResponseAsString()); tester.getRequest().setMethod("GET"); tester.executeUrl("./personsmanager/persons"); assertTrue(tester.getLastResponseAsString().contains(jsonObj)); }
Source:
<code>public void queries(@HttpQueryParameter("queries") String queries, EntityManager entityManager, ObjectResponse<World[]> response) { ThreadLocalRandom random = ThreadLocalRandom.current(); int count = getQueryCount(queries); World[] worlds = new World[count]; for (int i = 0; i < worlds.length; i++) { <START> worlds[i] = entityManager.find(World.class, random.nextInt(1, 10000)); <END> } response.send(worlds); }</code><technical_language>missed this before, ThreadLocalRandom's nextInt() upper bound is exclusive. change 10001</technical_language>

Target:
public void queries(@HttpQueryParameter("queries") String queries, EntityManager entityManager, ObjectResponse<World[]> response) { ThreadLocalRandom random = ThreadLocalRandom.current(); int count = getQueryCount(queries); World[] worlds = new World[count]; for (int i = 0; i < worlds.length; i++) { worlds[i] = entityManager.find(World.class, random.nextInt(1, 10001)); } response.send(worlds); }
Source:
<code>private void initEditMode(ChangeInfo info) { if (Gerrit.isSignedIn() && info.status().isOpen()) { RevisionInfo rev = info.revision(revision); if (isEditModeEnabled(info, rev)) { editMode.setVisible(fileTableMode == FileTable.Mode.REVIEW); addFile.setVisible(!editMode.isVisible()); reviewMode.setVisible(!editMode.isVisible()); addFileAction = new AddFileAction( changeId, info.revision(revision), style, addFile); } else { editMode.setVisible(false); addFile.setVisible(false); reviewMode.setVisible(false); } boolean hasEdit = info.has_edit() && info.current_revision().equals(info.edit().name()); reply.setVisible(!hasEdit); quickApprove.setVisible(!hasEdit); if (hasEdit) { <START> NativeMap<ActionInfo> actions = info.edit().has_actions() ? info.edit().actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (actions.containsKey("publish")) { publishEdit.setVisible(true); publishEdit.setTitle(actions.get("publish").title()); } <END> if (actions.containsKey("/")) { deleteEdit.setVisible(true); deleteEdit.setTitle(actions.get("/").title()); } } } }</code><technical_language>If coded, consider drop this actions GET edit endpoint hard code here</technical_language>

Target:
private void initEditMode(ChangeInfo info) { if (Gerrit.isSignedIn() && info.status().isOpen()) { RevisionInfo rev = info.revision(revision); if (isEditModeEnabled(info, rev)) { editMode.setVisible(fileTableMode == FileTable.Mode.REVIEW); addFile.setVisible(!editMode.isVisible()); reviewMode.setVisible(!editMode.isVisible()); addFileAction = new AddFileAction( changeId, info.revision(revision), style, addFile); } else { editMode.setVisible(false); addFile.setVisible(false); reviewMode.setVisible(false); } if (rev.is_edit()) { reply.setVisible(false); quickApprove.setVisible(false); NativeMap<ActionInfo> actions = info.edit().has_actions() ? info.edit().actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (actions.containsKey("publish")) { publishEdit.setVisible(true); publishEdit.setTitle(actions.get("publish").title()); } if (actions.containsKey("/")) { deleteEdit.setVisible(true); deleteEdit.setTitle(actions.get("/").title()); } } } }
Source:
<code>public static void checkExisting(Datastream datastream) { checkNew(datastream); Objects.requireNonNull(datastream.getDestination(), "invalid datastream destination"); Objects.requireNonNull(datastream.getDestination().getConnectionString(), "invalid destination connection"); Objects.requireNonNull(datastream.getDestination().getPartitions(), "invalid destination partitions"); if (datastream.getDestination().getPartitions() <= 0) { <START> throw new IllegalArgumentException("invalid Kafka topic partition count."); <END> } }</code><technical_language>fixing here, wanna fix this line</technical_language>

Target:
public static void checkExisting(Datastream datastream) { checkNew(datastream); Objects.requireNonNull(datastream.getDestination(), "invalid datastream destination"); Objects.requireNonNull(datastream.getDestination().getConnectionString(), "invalid destination connection"); Objects.requireNonNull(datastream.getDestination().getPartitions(), "invalid destination partitions"); if (datastream.getDestination().getPartitions() <= 0) { throw new IllegalArgumentException("invalid destination partition count."); } }
Source:
<code><START> URL getDatasetsUrl(String projectId, String datasetName, boolean fetchResults, Map<String, ?> queryParams) throws KeenQueryClientException { <END> try { StringBuilder url = new StringBuilder(String.format(Locale.US, "%s/%s/projects/%s/%s", this.baseUrl, this.apiVersion, projectId, KeenQueryConstants.DATASETS )); if (datasetName != null) { url.append("/").append(datasetName); if (fetchResults) { url.append("/results"); } } if (queryParams != null && !queryParams.isEmpty()) { StringBuilder query = new StringBuilder(); for (Map.Entry<String, ?> entry : queryParams.entrySet()) { query.append(String.format("%s=", URLEncoder.encode(entry.getKey(), "UTF-8"))); query.append(String.format("%s&", URLEncoder.encode(entry.getValue().toString(), "UTF-8"))); } url.append("?").append(query.toString().replaceFirst("&$", "")); } return new URL(url.toString()); } catch (IOException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format dataset URL.", ex); throw new KeenQueryClientException("Failed to format dataset URL.", ex); } }</code><technical_language>Split this method methods. hard understand on</technical_language>

Target:
URL getDatasetsUrl(String projectId, String datasetName, boolean fetchResults, Map<String, ?> queryParams) throws KeenQueryClientException { try { StringBuilder url = createBaseDatasetsUrl(projectId); if (datasetName != null) { appendDatasetName(url, datasetName); if (fetchResults) { appendFetchResults(url); } } if (queryParams != null && !queryParams.isEmpty()) { appendQueryParams(url, queryParams); } return new URL(url.toString()); } catch (IOException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format dataset URL.", ex); throw new KeenQueryClientException("Failed to format dataset URL.", ex); } }
Source:
<code>public Object execute(JobExecutionContext context) throws JobExecutionException { try { final JobArguments arguments = context.getJobArguments(); final String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : <START> ""; <END> throw new BadRequestException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage)); } final Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); final StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Healing event sent for consumer: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("EntitlerJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }</code><technical_language>need for this a line of</technical_language>

Target:
public Object execute(JobExecutionContext context) throws JobExecutionException { try { final JobArguments arguments = context.getJobArguments(); final String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : ""; throw new BadRequestException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage)); } final Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); final StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Successfully healed consumer with UUID: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("HealEntireOrgJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }
Source:
<code>public void testNXQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "test1-nx.metric.gstatic.com"; mDns.query(network, dname, FLAG_NO_CACHE_LOOKUP, mHandler, answerList -> { <START> if (answerList.size() == 0) { <END> latch.countDown(); } } ); String msg = "InetAddress query " + dname + " got unexpected answer"; try { assertTrue(msg, latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }</code><technical_language>Style : 8-spaces, 12</technical_language>

Target:
public void testNXQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "test1-nx.metric.gstatic.com"; String msg = "InetAddress query " + dname; mDns.query(network, dname, FLAG_NO_CACHE_LOOKUP, mHandler, answerList -> { if (answerList.size() == 0) { latch.countDown(); return; } fail(msg + " but get valid answers"); } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }
Source:
<code>public AggStats build(){ checkNotNull(accountId, "accountId cannot be null"); checkNotNull(dateLocal, "dateLocal cannot be null"); checkNotNull(externalDeviceId, "externalDeviceId cannot be null"); return new AggStats( this.accountId, this.dateLocal, this.externalDeviceId, this.deviceDataLength, this.trackerMotionLength, this.avgDailyTemp, this.maxDailyTemp, this.minDailyTemp, this.avgDailyHumidity, this.avgDailyDustDensity, <START> this.sumLengthMicroLuxHourMap); <END> }</code><technical_language>this null, be. create empty map, check if null before</technical_language>

Target:
public AggStats build(){ checkNotNull(accountId, "accountId cannot be null"); checkNotNull(dateLocal, "dateLocal cannot be null"); checkNotNull(externalDeviceId, "externalDeviceId cannot be null"); return new AggStats( this.accountId, this.dateLocal, this.externalDeviceId, this.deviceDataCount, this.trackerMotionCount, this.avgDailyTemp, this.maxDailyTemp, this.minDailyTemp, this.avgDailyHumidity, this.avgDailyDustDensity, this.sumCountMicroLuxHourMap); }
Source:
<code>public int findAndSelect(int widgetOffset, String findString, <START> boolean searchForward, boolean caseSensitive, boolean wholeWord) { <END> int matchIndex = 0; String searchString = text.getText(); if (widgetOffset < 0) { widgetOffset = searchForward ? 0 : searchString.length(); } if (!caseSensitive) { searchString = searchString.toLowerCase(); findString = findString.toLowerCase(); } if (searchForward) { matchIndex = searchString.indexOf(findString, widgetOffset); } else { matchIndex = searchString.lastIndexOf(findString, widgetOffset); } if (matchIndex != -1) { text.setSelection(matchIndex, matchIndex + findString.length()); } return matchIndex; }</code><technical_language>gain wholeWord, need implement consistent options available</technical_language>

Target:
public int findAndSelect(int widgetOffset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord) { int matchIndex = -1; String searchString = text.getText(); String findRegex = findString; if (widgetOffset < 0) { widgetOffset = searchForward ? 0 : searchString.length(); } if (wholeWord) { findRegex = WORD_BOUNDARY + findRegex + WORD_BOUNDARY; } int caseFlag = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile(findRegex, caseFlag); Matcher matcher = pattern.matcher(searchString); if (searchForward) { matchIndex = matcher.find(widgetOffset) ? matcher.start() : -1; } else { matcher.region(0, widgetOffset); while (matcher.find()) { matchIndex = matcher.start(); } } if (matchIndex != -1) { text.setSelection(matchIndex, matchIndex + findString.length()); } return matchIndex; }
Source:
<code>private void push(Path location) { String remoteBranch = view.getRemoteBranch(); String remote = remoteBranch.split("/")[0]; String branch = remoteBranch.split("/")[1]; service .push(location, singletonList(branch), remote, false) .then( result -> { notificationManager.notify(constant.pushSuccess(remote), SUCCESS, FLOAT_MODE); }) .catchError( error -> { final String providerName = GitUtil.getProviderNameFromError(error); <START> if (!StringUtils.isNullOrEmpty(providerName)) { <END> pushAuthenticated(location, branch, remote, providerName); return; } notificationManager.notify(constant.pushFail(), FAIL, FLOAT_MODE); }); }</code><technical_language>I is static import for isNullOrEmpty() method</technical_language>

Target:
private void push(Path location) { String remoteBranch = view.getRemoteBranch(); String remote = remoteBranch.split("/")[0]; String branch = remoteBranch.split("/")[1]; performOperationWithTokenRequestIfNeeded( new RemoteGitOperation<PushResponse>() { @Override public Promise<PushResponse> perform(Credentials credentials) { return service.push(location, singletonList(branch), remote, false, credentials); } }) .then( result -> { notificationManager.notify(locale.pushSuccess(remote), SUCCESS, FLOAT_MODE); }) .catchError( error -> { notificationManager.notify(locale.pushFail(), FAIL, FLOAT_MODE); }); }
Source:
<code>public BranchMergeOperation exclude(Iterable<String> ids) { <START> this.exclusions = Sets.newHashSet(ids); <END> return this; }</code><technical_language>here, ImmutableSet.copyOf(E[] elements). This prevent copying array vararg method</technical_language>

Target:
public BranchMergeOperation exclude(Iterable<String> ids) { this.exclusions = ImmutableSet.copyOf(ids); return this; }
Source:
<code>public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setDouble(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getDouble())) { state.setDouble(value); } } catch (Throwable t) { <START> throwIfInstanceOf(t, Error.class); <END> throwIfInstanceOf(t, PrestoException.class); throw new PrestoException(GENERIC_INTERNAL_ERROR, t); } }</code><technical_language>add a utility method replace lines</technical_language>

Target:
public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setDouble(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getDouble())) { state.setDouble(value); } } catch (Throwable t) { throw internalError(t); } }
Source:
<code>@Override public ServiceContextImpl serviceContext(String name) { if (!enterBusy()) return null; try { Collection<ServiceContextImpl> ctxs = serviceContexts(name); <START> if (F.isEmpty(ctxs)) <END> return null; synchronized (ctxs) { for (ServiceContextImpl ctx : ctxs) { if (ctx.service() != null) return ctx; } } return null; } finally { leaveBusy(); } }</code><technical_language>Missing synchronization</technical_language>

Target:
@Override public ServiceContextImpl serviceContext(String name) { if (!enterBusy()) return null; try { Collection<ServiceContextImpl> ctxs = serviceContexts(name); if (ctxs == null) return null; synchronized (ctxs) { if (F.isEmpty(ctxs)) return null; for (ServiceContextImpl ctx : ctxs) { if (ctx.service() != null) return ctx; } } return null; } finally { leaveBusy(); } }
Source:
<code>public RiakHll extractDatatype(RiakDatatype element) { <START> return element.getAsHLL(); <END> }</code><technical_language>Hll (lowercase l characters) is elsewhere. I I version looks, :smile:</technical_language>

Target:
public RiakHll extractDatatype(RiakDatatype element) { return element.getAsHll(); }
Source:
<code>public void onEvent(CacheEvent<K, V> event) { ExecutorService executor; if (storeEventSource.isEventOrdering()) { executor= orderedExecutor; } else { executor = unOrderedExectuor; } Future<?> future = null; if (!syncListenersList.isEmpty()) { future = executor.submit(new EventDispatchTask<K, V>(event, syncListenersList)); } if (!aSyncListenersList.isEmpty()) { executor.submit(new EventDispatchTask<K, V>(event, aSyncListenersList)); } <START> if (future != null) { <END> try { future.get(); } catch (Exception e) { LOGGER.error("Cache Event Listener failed for event type due to ", event.getType(), e); } } }</code><technical_language>avoid null check pushing future de-ref if, scope change too</technical_language>

Target:
public void onEvent(CacheEvent<K, V> event) { ExecutorService executor; if (storeEventSource.isEventOrdering()) { executor= orderedExecutor; } else { executor = unOrderedExectuor; } if (!aSyncListenersList.isEmpty()) { executor.submit(new EventDispatchTask<K, V>(event, aSyncListenersList)); } if (!syncListenersList.isEmpty()) { Future<?> future = executor.submit(new EventDispatchTask<K, V>(event, syncListenersList)); try { future.get(); } catch (Exception e) { LOGGER.error("Exception received as result from synchronous listeners", e); } } }
Source:
<code>public void process(GeneratingRegion region) { SurfaceHeightFacet facet = region.getRegionFacet(SurfaceHeightFacet.class); PlayAreaFacet playAreaFacet = region.getRegionFacet(PlayAreaFacet.class); <START> float mountainHeight = 40; <END> float hillHeight = 10; Rect2i processRegion = facet.getWorldRegion(); for (BaseVector2i position : processRegion.contents()) { float additiveMountainHeight = mountainNoise.noise(position.x(), position.y()) * mountainHeight; additiveMountainHeight = TeraMath.clamp(additiveMountainHeight, 0, mountainHeight); if (!playAreaFacet.getWorld((Vector2i) position)) { facet.setWorld(position, facet.getWorld(position) + additiveMountainHeight + 10); } } }</code><technical_language>Magic numbers in line</technical_language>

Target:
public void process(GeneratingRegion region) { SurfaceHeightFacet facet = region.getRegionFacet(SurfaceHeightFacet.class); PlayAreaFacet playAreaFacet = region.getRegionFacet(PlayAreaFacet.class); float mountainHeight = 40; Rect2i processRegion = facet.getWorldRegion(); for (BaseVector2i position : processRegion.contents()) { float additiveMountainHeight = mountainNoise.noise(position.x(), position.y()) * mountainHeight; additiveMountainHeight = TeraMath.clamp(additiveMountainHeight, 0, mountainHeight); if (!playAreaFacet.getWorld((Vector2i) position)) { facet.setWorld(position, facet.getWorld(position) + additiveMountainHeight + 10); } } }
Source:
<code>private static String toLuceneDateTime(Date date) { try { <START> SimpleDateFormat df = new SimpleDateFormat(LUCENE_DATE_TIME_FORMAT); <END> String returnValue = df.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }</code><technical_language>this a constant</technical_language>

Target:
private static String toLuceneDateTime(Date date) { try { String returnValue = LUCENE_DATE_TIME_FORMAT.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }
Source:
<code>public Selector parseRawSelector(String selector) { if (tokenPattern.matcher(selector).matches()) { <START> SelectorBuilder builder = createEmptyBuilder().type(SelectorTypes.valueOf(selector.substring(1, 2)).get()); <END> String argString = selector.substring(selector.indexOf('[') + 1, selector.lastIndexOf(']')); for (String argument : argString.split(",")) { int index = argument.indexOf('='); builder.addArgument(argument.substring(0, index), argument.substring(index) + 1); } return builder.build(); } return null; }</code><technical_language>account for this odd behavior: > If arguments (up four) simply values identifying arguments, assumed be, in order, x, y, z, r. Thus, commands identical: > /gamemode creative @a[x=10,y=20,z=30,r=4] > /gamemode creative @a[10,20,30,4] Edit: applies entire function, making a working version</technical_language>

Target:
public Selector parseRawSelector(String selector) { checkArgument(tokenPattern.matcher(selector).matches()); SelectorBuilder builder = createEmptyBuilder().type(SelectorTypes.valueOf(selector.substring(1, 2)).get()); setArguments(builder, selector.substring(selector.indexOf('[') + 1, selector.lastIndexOf(']'))); return builder.build(); }
Source:
<code>public void isNotAuthorizedWithInvalidCredentials() throws Exception { <START> assertThat(BASIC_AUTH.isAuthorized("Basic wrong:password")).isFalse(); <END> }</code><technical_language>Is test for encoded wrong credentials missing</technical_language>

Target:
public void isNotAuthorizedWithInvalidCredentials() throws Exception { assertThat(BASIC_AUTH.isAuthorized("Basic " + encode("username:wrong"))).isFalse(); }
Source:
<code>public static <T> Merger<T> getMerger(Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("returnType is null"); } Merger result; if (returnType.isArray()) { Class type = returnType.getComponentType(); result = mergerCache.get(type); if (result == null) { loadMergers(); result = mergerCache.get(type); } if (result == null && !type.isPrimitive()) { result = ArrayMerger.INSTANCE; } } else { result = mergerCache.get(returnType); if (result == null) { loadMergers(); result = mergerCache.get(returnType); } } <START> if (result == null) { <END> throw new IllegalArgumentException(returnType.getName() + " is not supported"); } return result; }</code><technical_language>I throw exception, return null</technical_language>

Target:
public static <T> Merger<T> getMerger(Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("returnType is null"); } Merger result; if (returnType.isArray()) { Class type = returnType.getComponentType(); result = mergerCache.get(type); if (result == null) { loadMergers(); result = mergerCache.get(type); } if (result == null && !type.isPrimitive()) { result = ArrayMerger.INSTANCE; } } else { result = mergerCache.get(returnType); if (result == null) { loadMergers(); result = mergerCache.get(returnType); } } return result; }
Source:
<code>public void highlightNode(JsonRpcPeer peer, JSONObject params) { HighlightNodeRequest request = mObjectMapper.convertValue(params, HighlightNodeRequest.class); <START> if (request.nodeId != null) { <END> Object element = getElementForNodeId(request.nodeId); mDOMProvider.highlightElement(element); } }</code><technical_language>complexities of debugging network protocols, strongly prefer else block sends logcat (via LogUtil)</technical_language>

Target:
public void highlightNode(JsonRpcPeer peer, JSONObject params) { HighlightNodeRequest request = mObjectMapper.convertValue(params, HighlightNodeRequest.class); if (request.nodeId == null) { LogUtil.w("highlightNode was not given a nodeId; JS objectId is not supported"); } else { Object element = mObjectIdMapper.getObjectForId(request.nodeId); mDOMProvider.highlightElement( element, request.highlightConfig.contentColor.getColor(), request.highlightConfig.paddingColor.getColor(), request.highlightConfig.borderColor.getColor(), request.highlightConfig.marginColor.getColor()); } }
Source:
<code>static <E> Gen<E> choose(E[] values) { if(values.length == 0) <START> return Gen.fail("Emtpy array"); <END> else return random -> Gen.choose(0, values.length - 1).map(i -> values[i]).apply(random); }</code><technical_language>typo: s/Emtpy/Empty/</technical_language>

Target:
static <E> Gen<E> choose(E[] values) { Objects.requireNonNull(values, "values is null"); if(values.length == 0) return Gen.fail("Empty array"); else return random -> Gen.choose(0, values.length - 1).map(i -> values[i]).apply(random); }
Source:
<code>public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); } catch (Exception e) { <START> consumer.close(); <END> log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info("Started KafkaSupervisor[%s], first run in [%s]", dataSource, ioConfig.getStartDelay()); } }</code><technical_language>@pjain1 move code it: firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], run in [%s], spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); try-catch well? do a (if consumer != null) {consumer.close();} avoid NPE</technical_language>

Target:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], first run in [%s], with spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); } catch (Exception e) { if (consumer != null) { consumer.close(); } log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } } }