auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Page appendColumn(Block block) { requireNonNull(block, "block is null"); <START> if (positionCount != block.getPositionCount()) { <END> throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = new Block[blocks.length + 1]; System.arraycopy(blocks, 0, newBlocks, 0, blocks.length); newBlocks[blocks.length] = block; return new Page(newBlocks); }</code><technical_language>checkArgument include values (they primitive overloads avoid boxing, free)</technical_language>

Target:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); newBlocks[blocks.length] = block; return new Page(newBlocks); }
Source:
<code>public void standbyShouldNotPerformRestoreAtStartup() throws Exception { final int numMessages = 10; final int key = 1; final Semaphore semaphore = new Semaphore(0); final StreamsBuilder builder = new StreamsBuilder(); builder .table(INPUT_TOPIC_NAME, Consumed.with(Serdes.Integer(), Serdes.Integer()), Materialized.<Integer, Integer, KeyValueStore<Bytes, byte[]>>as(TABLE_NAME) .withCachingDisabled()) .toStream() .peek((k, v) -> semaphore.release()); final KafkaStreams kafkaStreams1 = createKafkaStreams(builder, streamsConfiguration()); final KafkaStreams kafkaStreams2 = createKafkaStreams(builder, streamsConfiguration()); final List<KafkaStreams> kafkaStreamsList = Arrays.asList(kafkaStreams1, kafkaStreams2); produceValueRange(key, 0, 10); final AtomicLong restoreStartOffset = new AtomicLong(-1); kafkaStreamsList.forEach(kafkaStreams -> { kafkaStreams.setGlobalStateRestoreListener(createTrackingRestoreListener(restoreStartOffset, new AtomicLong())); }); <START> startApplicationAndWaitUntilRunning(kafkaStreamsList, 60 * 1000); <END> assertThat(semaphore.tryAcquire(numMessages, 60, TimeUnit.SECONDS), is(equalTo(true))); assertThat(restoreStartOffset.get(), is(equalTo(-1L))); }</code><technical_language>Thinking it, switch Duration (would apply PR, too)</technical_language>

Target:
public void standbyShouldNotPerformRestoreAtStartup() throws Exception { final int numMessages = 10; final int key = 1; final Semaphore semaphore = new Semaphore(0); final StreamsBuilder builder = new StreamsBuilder(); builder .table(INPUT_TOPIC_NAME, Consumed.with(Serdes.Integer(), Serdes.Integer()), Materialized.<Integer, Integer, KeyValueStore<Bytes, byte[]>>as(TABLE_NAME) .withCachingDisabled()) .toStream() .peek((k, v) -> semaphore.release()); final KafkaStreams kafkaStreams1 = createKafkaStreams(builder, streamsConfiguration()); final KafkaStreams kafkaStreams2 = createKafkaStreams(builder, streamsConfiguration()); final List<KafkaStreams> kafkaStreamsList = Arrays.asList(kafkaStreams1, kafkaStreams2); produceValueRange(key, 0, 10); final AtomicLong restoreStartOffset = new AtomicLong(-1); kafkaStreamsList.forEach(kafkaStreams -> { kafkaStreams.setGlobalStateRestoreListener(createTrackingRestoreListener(restoreStartOffset, new AtomicLong())); }); startApplicationAndWaitUntilRunning(kafkaStreamsList, Duration.ofSeconds(60)); assertThat(semaphore.tryAcquire(numMessages, 60, TimeUnit.SECONDS), is(equalTo(true))); assertThat(restoreStartOffset.get(), is(equalTo(-1L))); }
Source:
<code>public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); <START> Object[] temp = (Object[]) innerMap.get(GLUSTER_HOSTS); <END> if (temp != null) { for (int i = 0; i < temp.length; i++) { hostsList.add(prepareHostsEntity((Map<String, Object>) temp[i])); } } }</code><technical_language>I suggest naming this variable 'serversArr' instead of 'temp'</technical_language>

Target:
public GlusterServersListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); Set<GlusterServerInfo> glusterServers = new HashSet<GlusterServerInfo>(); Object[] serversArr = (Object[]) innerMap.get(GLUSTER_HOSTS); if (serversArr != null) { for (int i = 0; i < serversArr.length; i++) { glusterServers.add(prepareHostsEntity((Map<String, Object>) serversArr[i])); } } setServer(glusterServers); }
Source:
<code>public List<TopMenu.MenuEntry> apply(ConfigResource resource) { List<TopMenu.MenuEntry> entries = Lists.newArrayList(); <START> if (returnAllMenusEnabled) { entries.addAll(gerritTopMenus.getTopMenuBar(true, currentProject)); } <END> for (TopMenu extension : extensions) { entries.addAll(extension.getEntries()); } return entries; }</code><technical_language>Conditional implies Provider</technical_language>

Target:
public List<TopMenu.MenuEntry> apply(ConfigResource resource) { List<TopMenu.MenuEntry> entries = Lists.newArrayList(); if (returnAllMenusEnabled) { entries.addAll(topMenusProvider.get().getTopMenuBar(true, currentProject)); } for (TopMenu extension : extensions) { entries.addAll(extension.getEntries()); } return entries; }
Source:
<code>public GaviNestWarden(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{R}{W}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SHAMAN); this.power = new MageInt(2); this.toughness = new MageInt(5); Effect effect = new CyclingZeroCostEffect(filter); effect.setText("You may pay {0} rather than pay the cycling cost of the first card you cycle each turn."); <START> this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect), new GaviNestWardenWatcher()); <END> Ability ability = new DrawSecondCardTriggeredAbility(new CreateTokenEffect(new DinosaurCatToken()), false); this.addAbility(ability); }</code><technical_language>set text for effect in class definition instead of here, need zone in constructor for SimpleStaticAbility default</technical_language>

Target:
public GaviNestWarden(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{R}{W}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SHAMAN); this.power = new MageInt(2); this.toughness = new MageInt(5); Effect effect = new CyclingZeroCostEffect(); this.addAbility(new SimpleStaticAbility(effect), new GaviNestWardenWatcher()); Ability ability = new DrawSecondCardTriggeredAbility(new CreateTokenEffect(new DinosaurCatToken()), false); this.addAbility(ability); }
Source:
<code>public void setValues(double limit, double consumedByOthers, double consumedByUser) { int othersConsumptionPercent = (int) Math.round(consumedByOthers * 100 / limit); int userConsumptionPercent = (int) Math.round(consumedByUser * 100 / limit); double free = limit - consumedByOthers - consumedByUser; <START> switch (getType()) { <END> case STORAGE: String freeStorage = free == 0 ? "0" : diskSizeRenderer.render(free); setTitle(constants.freeStorage() + freeStorage); break; case CPU: setTitle(messages.quotaFreeCpus((int) free)); break; case MEM: String freeMem = free > 4096 ? diskSizeRenderer.render(free/1024) : (int) free + "MB"; setTitle(constants.freeMemory() + freeMem); break; } if (limit == UNLIMITED) { setUnlimited(); } else if (consumedByOthers + consumedByUser == 0) { setZeroValue(); } else if (consumedByOthers + consumedByUser > limit) { switch (getType()) { case STORAGE: setExceeded(messages.exceedingStorage(othersConsumptionPercent + userConsumptionPercent - 100, -free)); break; case CPU: setExceeded(messages.exceedingCpus(othersConsumptionPercent + userConsumptionPercent - 100, (int) -free)); break; case MEM: String freeMem = free < -4096 ? diskSizeRenderer.render(-free/1024) : (int) -free + "MB"; setExceeded(messages.exceedingMem(othersConsumptionPercent + userConsumptionPercent - 100, freeMem)); break; } } else { percentageBarA.setStyleName(style.percentageBarA()); percentageLabelA.setStyleName(style.percentageLabelBlack()); percentageBarB.setVisible(true); setValueA(othersConsumptionPercent); setValueB(userConsumptionPercent); setBars(); } }</code><technical_language>a bit if extract a method (e.g. 'updateTitle'..)</technical_language>

Target:
public void setValues(double limit, double consumedByOthers, double consumedByUser) { int othersConsumptionPercent = (int) Math.round(consumedByOthers * 100 / limit); int userConsumptionPercent = (int) Math.round(consumedByUser * 100 / limit); double free = limit - consumedByOthers - consumedByUser; setTitleInternal(free); if (limit == UNLIMITED) { setUnlimited(); } else if (consumedByOthers + consumedByUser == 0) { setZeroValue(); } else if (consumedByOthers + consumedByUser > limit) { switch (getType()) { case STORAGE: setExceeded(messages.exceedingStorage(othersConsumptionPercent + userConsumptionPercent - 100, -free)); break; case CPU: setExceeded(messages.exceedingCpus(othersConsumptionPercent + userConsumptionPercent - 100, (int) -free)); break; case MEM: String freeMem = free < (-MB_GB_THRESHOLD * GIGA) ? diskSizeRenderer.render(-free/GIGA) : (int) -free + "MB"; setExceeded(messages.exceedingMem(othersConsumptionPercent + userConsumptionPercent - 100, freeMem)); break; } } else { percentageBarA.setStyleName(style.percentageBarA()); percentageLabelA.setStyleName(style.percentageLabelBlack()); percentageBarB.setVisible(true); setValueA(othersConsumptionPercent); setValueB(userConsumptionPercent); setBars(); } }
Source:
<code>public StripeFooter(List<Stream> streams, List<ColumnEncoding> columnEncodings, List<Slice> stripeEncryptionGroups) { this.streams = ImmutableList.copyOf(requireNonNull(streams, "streams is null")); this.columnEncodings = ImmutableList.copyOf(requireNonNull(columnEncodings, "columnEncodings is null")); <START> this.stripeEncryptionGroups = requireNonNull(stripeEncryptionGroups, "stripeEncryptionGroups is null"); <END> }</code><technical_language>ImmutableList.copyOf</technical_language>

Target:
public StripeFooter(List<Stream> streams, List<ColumnEncoding> columnEncodings, List<Slice> stripeEncryptionGroups) { this.streams = ImmutableList.copyOf(requireNonNull(streams, "streams is null")); this.columnEncodings = ImmutableList.copyOf(requireNonNull(columnEncodings, "columnEncodings is null")); this.stripeEncryptionGroups = ImmutableList.copyOf(requireNonNull(stripeEncryptionGroups, "stripeEncryptionGroups is null")); }
Source:
<code>public boolean execute() { final boolean[] result = new boolean[1]; <START> Display display = Display.getCurrent(); <END> BusyIndicator.showWhile(display, () -> result[0] = doExecute()); return result[0]; }</code><technical_language>This reference null in theory if called of UI thread. Display.getDefault()</technical_language>

Target:
public boolean execute() { final boolean[] result = new boolean[1]; Display display = Display.getDefault(); BusyIndicator.showWhile(display, () -> result[0] = doExecute()); return result[0]; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_apps_limit_view); boolean installAttemptCameFromAppManager = getIntent().getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); Button toManagerButton = (Button)findViewById(R.id.back_to_manager_button); if (installAttemptCameFromAppManager) { <START> toManagerButton.setText("Back to App Manager"); <END> toManagerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_OK); finish(); } }); } else { toManagerButton.setText("Go to App Manager"); toManagerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MultipleAppsLimitWarningActivity.this, AppManagerActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } }); } }</code><technical_language>load strings string.xml prevent lint warnings/allow for android-level translations</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_apps_limit_view); boolean installAttemptCameFromAppManager = getIntent() .getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); setupUI(installAttemptCameFromAppManager); }
Source:
<code>public void tryStartWorkspace() { final WorkspaceConfigDto workspaceConfigDto = factory.getWorkspace(); if (workspaceConfigDto == null) { <START> notificationManager.showError("Workspace config is not defined"); <END> } getWorkspaceToStart().then(startWorkspace()).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { Log.error(getClass(), arg.getMessage()); } }); }</code><technical_language>add return here</technical_language>

Target:
public void tryStartWorkspace() { final WorkspaceConfigDto workspaceConfigDto = factory.getWorkspace(); if (workspaceConfigDto == null) { notificationManager.showError(locale.workspaceConfigUndefined()); return; } getWorkspaceToStart().then(startWorkspace()).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { Log.error(getClass(), arg.getMessage()); } }); }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) { <END> return true; } if (o == null || getClass() != o.getClass()) { return false; } Quantity quantity = (Quantity) o; return getNormalizedValue(this) .toBigInteger() .equals(getNormalizedValue(quantity).toBigInteger()); }</code><technical_language>hashCode implementation</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Quantity quantity = (Quantity) o; return getAmountInBytes(this) .toBigInteger() .equals(getAmountInBytes(quantity).toBigInteger()); }
Source:
<code><START> SolrInputDocument toDoc(Question q) { <END> SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("tags", Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } })); doc.addField("type", Question.class.getCanonicalName()); return doc; }</code><technical_language>this method private</technical_language>

Target:
private SolrInputDocument toDoc(Question q) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("tags", Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } })); doc.addField("type", Question.class.getCanonicalName()); return doc; }
Source:
<code>public Map<KOut, List<VOut>> removeLRUEntry() { <START> Map<KOut, List<VOut>> lrus = new HashMap<KOut, List<VOut>>(1); <END> synchronized (this) { Iterator<KOut> iterator = store.keySet().iterator(); if (iterator.hasNext()){ KOut out = iterator.next(); List<VOut> list = store.remove(out); lrus.put(out, list); emitCount.addAndGet(list.size() * -1); } } return lrus; }</code><technical_language>return a Collections.singletonMap(key, list)</technical_language>

Target:
public Map<KOut, List<VOut>> removeLRUEntry() { Map<KOut, List<VOut>> lrus = Collections.emptyMap(); synchronized (this) { Iterator<KOut> iterator = store.keySet().iterator(); if (iterator.hasNext()){ KOut out = iterator.next(); List<VOut> list = store.remove(out); lrus = Collections.singletonMap(out, list); emitCount.addAndGet(-list.size()); } } return lrus; }
Source:
<code>public void writeAsBibtexCitation(OutputStream os) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); if(getFileTitle() !=null && isDirect()) { out.write("@incollection{"); } else { out.write("@data{"); } out.write(persistentId.getIdentifier() + "_" + year + "," + "\r\n"); out.write("author = {"); out.write(String.join(" and ", authors)); out.write("},\r\n"); out.write("publisher = {"); out.write(publisher); out.write("},\r\n"); if(getFileTitle() !=null && isDirect()) { out.write("title = {"); out.write(fileTitle); out.write("},\r\n"); out.write("booktitle = {"); out.write(title); out.write("},\r\n"); } else { out.write("title = {"); out.write(title); out.write("},\r\n"); } if(getUNF() != null){ out.write("UNF = {"); <START> out.write(UNF); <END> out.write("},\r\n"); } out.write("year = {"); out.write(year); out.write("},\r\n"); out.write("version = {"); out.write(version); out.write("},\r\n"); out.write("doi = {"); out.write(persistentId.getAuthority()); out.write("/"); out.write(persistentId.getIdentifier()); out.write("},\r\n"); out.write("url = {"); out.write(persistentId.toURL().toString()); out.write("}\r\n"); out.write("}\r\n"); out.flush(); }</code><technical_language>Is a reason getUNF() UNF in block</technical_language>

Target:
public void writeAsBibtexCitation(OutputStream os) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); if(getFileTitle() !=null && isDirect()) { out.write("@incollection{"); } else { out.write("@data{"); } out.write(persistentId.getIdentifier() + "_" + year + "," + "\r\n"); out.write("author = {"); out.write(String.join(" and ", authors)); out.write("},\r\n"); out.write("publisher = {"); out.write(publisher); out.write("},\r\n"); if(getFileTitle() !=null && isDirect()) { out.write("title = {"); out.write(fileTitle); out.write("},\r\n"); out.write("booktitle = {"); out.write(title); out.write("},\r\n"); } else { out.write("title = {"); out.write(title); out.write("},\r\n"); } if(UNF != null){ out.write("UNF = {"); out.write(UNF); out.write("},\r\n"); } out.write("year = {"); out.write(year); out.write("},\r\n"); out.write("version = {"); out.write(version); out.write("},\r\n"); out.write("doi = {"); out.write(persistentId.getAuthority()); out.write("/"); out.write(persistentId.getIdentifier()); out.write("},\r\n"); out.write("url = {"); out.write(persistentId.toURL().toString()); out.write("}\r\n"); out.write("}\r\n"); out.flush(); }
Source:
<code>public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length == 64) { bits = input.getLong(); <START> } else if (length > 32) { <END> long newPos = input.position() + length; bits = input.getLong(); input.position(newPos); long signedBit = 1L << length; long mask = signedBit - 1; bits &= mask; if (signed && signedBit != 0) { bits |= ~mask; } } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }</code><technical_language>This test is wrong. read a int of 78 bits here. integer larger 64 bits throw exception</technical_language>

Target:
public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length > 64) { throw new IllegalArgumentException("Cannot read an integer with over 64 bits. Length given: " + length ); } else if (length == 64) { bits = input.getLong(); } else if (length > 32) { bits = input.getLong(length, signed); } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }
Source:
<code>private void serializeEntity(CanonicalPath entity, JsonGenerator jsonGenerator, String fieldName) throws IOException { jsonGenerator.writeFieldName(fieldName); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName(FIELD_ID); <START> jsonGenerator.writeString(Inventory.getStableId(entity)); <END> jsonGenerator.writeFieldName(FIELD_SHORT_ID); jsonGenerator.writeString(entity.getSegment().getElementId()); jsonGenerator.writeFieldName(FIELD_TYPE); jsonGenerator.writeString(entity.getSegment().getElementType().getSimpleName()); jsonGenerator.writeEndObject(); }</code><technical_language>Returning entity.toString() ok. iirc, stable id canonical path for long canonical paths</technical_language>

Target:
private void serializeEntity(CanonicalPath entity, JsonGenerator jsonGenerator, String fieldName) throws IOException { jsonGenerator.writeFieldName(fieldName); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName(FIELD_ID); jsonGenerator.writeString(entity.getPath().toString()); jsonGenerator.writeFieldName(FIELD_SHORT_ID); jsonGenerator.writeString(entity.getSegment().getElementId()); jsonGenerator.writeFieldName(FIELD_TYPE); jsonGenerator.writeString(entity.getSegment().getElementType().getSimpleName()); jsonGenerator.writeEndObject(); }
Source:
<code>private String restoreSome(final Ds3ClientHelpers.ObjectChannelBuilder getter) throws IOException, SignatureException, XmlProcessingException, SSLSetupException { final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> contents = helper.listObjects(this.bucketName, this.prefix); <START> Iterable<Contents> filteredContents = null; <END> if (sync) { filteredContents = filterContents(contents, this.outputPath); if (Iterables.isEmpty(filteredContents)) { return "SUCCESS: All files are up to date"; } } final Iterable<Ds3Object> objects = Iterables.transform( filteredContents == null ? contents : filteredContents, new Function<Contents, Ds3Object>() { @Override public Ds3Object apply(final Contents input) { return new Ds3Object(input.getKey(), input.getSize()); } }); final Ds3ClientHelpers.Job job = helper.startReadJob(this.bucketName, objects, ReadJobOptions.create() .withPriority(this.priority)); job.transfer(new LoggingFileObjectGetter(getter)); if (sync) { if (prefix != null) { return "SUCCESS: Synced all the objects that start with '" + this.prefix + "' from " + this.bucketName + " to " + this.outputPath.toString(); } else { return "SUCCESS: Synced all the objects from " + this.bucketName + " to " + this.outputPath.toString(); } } return "SUCCESS: Wrote all the objects that start with '"+ this.prefix +"' from " + this.bucketName + " to " + this.outputPath.toString(); }</code><technical_language>This final else if (sync) assigns null</technical_language>

Target:
private String restoreSome(final Ds3ClientHelpers.ObjectChannelBuilder getter) throws IOException, SignatureException, XmlProcessingException, SSLSetupException { final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> contents = helper.listObjects(this.bucketName, this.prefix); final Iterable<Contents> filteredContents; if (sync) { filteredContents = filterContents(contents, this.outputPath); if (Iterables.isEmpty(filteredContents)) { return "SUCCESS: All files are up to date"; } } else { filteredContents = null; } final Iterable<Ds3Object> objects = Iterables.transform( filteredContents == null ? contents : filteredContents, new Function<Contents, Ds3Object>() { @Override public Ds3Object apply(final Contents input) { return new Ds3Object(input.getKey(), input.getSize()); } }); final Ds3ClientHelpers.Job job = helper.startReadJob(this.bucketName, objects, ReadJobOptions.create() .withPriority(this.priority)); job.transfer(new LoggingFileObjectGetter(getter)); if (sync) { if (prefix != null) { return "SUCCESS: Synced all the objects that start with '" + this.prefix + "' from " + this.bucketName + " to " + this.outputPath.toString(); } else { return "SUCCESS: Synced all the objects from " + this.bucketName + " to " + this.outputPath.toString(); } } return "SUCCESS: Wrote all the objects that start with '"+ this.prefix +"' from " + this.bucketName + " to " + this.outputPath.toString(); }
Source:
<code>public AddChargeParams build() { <START> AddChargeParams addChargeParams = new AddChargeParams(); <END> addChargeParams.amount = this.amount; addChargeParams.version = this.version; addChargeParams.returnUrl = this.returnUrl; addChargeParams.reference = this.reference; addChargeParams.chargeId = this.chargeId; addChargeParams.delayedCapture = this.delayedCapture; addChargeParams.externalMetadata = this.externalMetadata; addChargeParams.transactionId = this.transactionId; addChargeParams.createdDate = this.createdDate; addChargeParams.language = this.language; addChargeParams.externalChargeId = this.externalChargeId; addChargeParams.gatewayAccountId = this.gatewayAccountId; addChargeParams.description = this.description; addChargeParams.email = this.email; addChargeParams.corporateSurcharge = this.corporateSurcharge; addChargeParams.status = this.status; return addChargeParams; }</code><technical_language>Slightly approach class built a constructor builder. Out of interest reason choose this approach this time</technical_language>

Target:
public AddChargeParams build() { return new AddChargeParams(this); }
Source:
<code>public void whenEventExistsFindByNameReturnsSomething() throws NakadiException, DuplicatedEventTypeNameException, NoSuchEventTypeException { EventType eventType = buildEventType(); <START> repository.saveEventType(eventType); <END> EventType persistedEventType = repository.findByName(eventType.getName()); assertThat(persistedEventType, notNullValue()); }</code><technical_language>test findByName method. I bootstrap is perform EventTypeRepository, jdbcTemplate prepared statement</technical_language>

Target:
public void whenEventExistsFindByNameReturnsSomething() throws Exception { EventType eventType1 = buildEventType(); EventType eventType2 = buildEventType(); eventType2.setName("event-name-2"); String insertSQL = "INSERT INTO zn_data.event_type (et_name, et_event_type_object) VALUES (?, to_json(?::json))"; template.update(insertSQL, eventType1.getName(), mapper.writer().writeValueAsString(eventType1)); template.update(insertSQL, eventType2.getName(), mapper.writer().writeValueAsString(eventType2)); EventType persistedEventType = repository.findByName(eventType2.getName()); assertThat(persistedEventType, notNullValue()); }
Source:
<code>protected void performPut(long address, long newAddress, WrappedBytes key) { if (address == 0) { memoryLookup.putMemoryAddress(key, newAddress); entryCreated(newAddress); size.incrementAndGet(); } else { boolean shouldCreate = false; boolean foundKey = false; long prevAddress = 0; while (address != 0) { long nextAddress = offHeapEntryFactory.getNext(address); <START> if (!foundKey) { <END> if (offHeapEntryFactory.equalsKey(address, key)) { entryReplaced(newAddress, address); foundKey = true; if (prevAddress == 0) { if (nextAddress == 0) { shouldCreate = true; } else { memoryLookup.putMemoryAddress(key, nextAddress); } } else { offHeapEntryFactory.setNext(prevAddress, nextAddress); address = nextAddress; continue; } } } prevAddress = address; address = nextAddress; } if (!foundKey) { entryCreated(newAddress); size.incrementAndGet(); } if (shouldCreate) { memoryLookup.putMemoryAddress(key, newAddress); } else { offHeapEntryFactory.setNext(prevAddress, newAddress); } } }</code><technical_language>I deallocation happen in entryReplaced(). entry replaced LRU list hash table read other threads, free memory holding lock. Ideally want allocation deallocation happen level, i.e. in performPut performRemove</technical_language>

Target:
protected void performPut(long address, long newAddress, WrappedBytes key) { if (address == 0) { memoryLookup.putMemoryAddress(key, newAddress); entryCreated(newAddress); size.incrementAndGet(); } else { boolean replaceHead = false; boolean foundKey = false; long prevAddress = 0; while (address != 0) { long nextAddress = offHeapEntryFactory.getNext(address); if (!foundKey) { if (offHeapEntryFactory.equalsKey(address, key)) { entryReplaced(newAddress, address); foundKey = true; if (prevAddress == 0) { if (nextAddress == 0) { replaceHead = true; } else { memoryLookup.putMemoryAddress(key, nextAddress); } } else { offHeapEntryFactory.setNext(prevAddress, nextAddress); address = nextAddress; continue; } } } prevAddress = address; address = nextAddress; } if (!foundKey) { entryCreated(newAddress); size.incrementAndGet(); } if (replaceHead) { memoryLookup.putMemoryAddress(key, newAddress); } else { offHeapEntryFactory.setNext(prevAddress, newAddress); } } }
Source:
<code>protected void getTasksRequest(){ mSwipeLayout.setRefreshing(true); HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); TaskListRequest taskListRequest = new TaskListRequest(getActivity(), params, new Response.Listener<ArrayList<Task>>() { @Override public void onResponse(ArrayList<Task> tasks) { if (mArgs.getInt(OPTION) == USER) { tasks = getUserTasks(tasks); if (tasks.size() > 0) { showList(); setUserTasks(tasks); mUserTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mUserTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } else { if (tasks.size() > 0) { showList(); setAllTasks(tasks); mAllTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mAllTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } new CountDownTimer(2000, 1000) { public void onTick(long millisUntilFinished) public void onFinish() { if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false); if (mNoTasks != null) mNoTasks.setRefreshing(false); } <START> }.start(); <END> } }, mSwipeLayout); mNetworkManager.getRequestQueue().add(taskListRequest); }</code><technical_language>leaving loading spinner for 2 seconds if data is loaded</technical_language>

Target:
protected void getTasksRequest(){ mSwipeLayout.setRefreshing(true); HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); TaskListRequest taskListRequest = new TaskListRequest(getActivity(), params, new Response.Listener<ArrayList<Task>>() { @Override public void onResponse(ArrayList<Task> tasks) { if (mArgs.getInt(OPTION) == USER) { tasks = getUserTasks(tasks); if (tasks.size() > 0) { showList(); setUserTasks(tasks); mUserTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mUserTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } else { if (tasks.size() > 0) { showList(); setAllTasks(tasks); mAllTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mAllTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } new CountDownTimer(1000, 1000) { public void onTick(long millisUntilFinished) public void onFinish() { if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false); if (mNoTasks != null) mNoTasks.setRefreshing(false); } }.start(); } }, mSwipeLayout); mNetworkManager.getRequestQueue().add(taskListRequest); }
Source:
<code>protected void endVmCommand() { super.endVmCommand(); <START> getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); <END> }</code><technical_language>this vm is unlocked in super.endVmCommand();</technical_language>

Target:
protected void endVmCommand() { getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); super.endVmCommand(); }
Source:
<code>protected boolean processPayeeAchAccountNew(PayeeACHAccount payeeAchAccountNew, PayeeACHAccount payeeAchAccount) { <START> boolean isSuccessful = true; <END> try { payeeAchAccountNew = businessObjectService.save(payeeAchAccountNew); } catch (Exception e) { GlobalVariables.getMessageMap().putError("payeeAchAccount", KFSKeyConstants.ERROR_CUSTOM, e.getCause().getMessage()); if (ObjectUtils.isNotNull(payeeAchAccount)) { payeeAchAccount.setActive(true); payeeAchAccount = businessObjectService.save(payeeAchAccount); } isSuccessful = false; } return isSuccessful; }</code><technical_language>isSuccessful is defaulted true set false more sense opposed is defaulted false</technical_language>

Target:
protected boolean processPayeeAchAccountNew(PayeeACHAccount payeeAchAccountNew, PayeeACHAccount payeeAchAccount) { boolean successful = true; try { payeeAchAccountNew = businessObjectService.save(payeeAchAccountNew); } catch (Exception e) { GlobalVariables.getMessageMap().putError("payeeAchAccount", KFSKeyConstants.ERROR_CUSTOM, e.getCause().getMessage()); if (ObjectUtils.isNotNull(payeeAchAccount)) { payeeAchAccount.setActive(true); payeeAchAccount = businessObjectService.save(payeeAchAccount); } successful = false; } return successful; }
Source:
<code>public void onContactsUpdate(final UpdateContacts updateContacts) { <START> if (mPages == null || mPages.isEmpty()) { <END> return; } for (BaseContactFragment fragment : mPages) { fragment.updateContacts(); } }</code><technical_language>I remove return place for (BaseContactFragment fragment: mPages) if block</technical_language>

Target:
public void onContactsUpdate(final UpdateContacts updateContacts) { if (mPages != null && !mPages.isEmpty()) { for (BaseContactFragment fragment : mPages) { fragment.updateContacts(); } } }
Source:
<code>public float onSeekBarProgressChanged(SeekBar seekBar, int progress, boolean fromUser, TextView txtvPosition, TextView seekDisplay) { if (fromUser && playbackService != null && media != null) { float prog = progress / ((float) seekBar.getMax()); int duration = media.getDuration(); TimeSpeedConverter converter = new TimeSpeedConverter(playbackService.getCurrentPlaybackSpeed()); int position = converter.convert((int) (prog * duration)); txtvPosition.setText(Converter.getDurationStringLong(position)); <START> seekDisplay.setText(Converter.getDurationStringLong(position)); <END> return prog; } return 0; }</code><technical_language>I wondering if need update position TextView in line above, now. seeking, interesting started from</technical_language>

Target:
public float onSeekBarProgressChanged(SeekBar seekBar, int progress, boolean fromUser, TextView txtvPosition, TextView seekDisplay) { if (fromUser && playbackService != null && media != null) { float prog = progress / ((float) seekBar.getMax()); int duration = media.getDuration(); if (duration == -1) duration = getDuration(); TimeSpeedConverter converter = new TimeSpeedConverter(playbackService.getCurrentPlaybackSpeed()); int position = converter.convert((int) (prog * duration)); txtvPosition.setText(Converter.getDurationStringLong(position)); seekDisplay.setText(Converter.getDurationStringLong(position)); return prog; } return 0; }
Source:
<code>public LinkedHashMap<String,S> process(final int max) throws IOException, CompoundNotFoundException { <START> if(closed) throw new IOException("Cannot perform action: resource has been closed."); <END> LinkedHashMap<String,S> sequences = new LinkedHashMap<>(); @SuppressWarnings("unchecked") int i=0; while(true) { if(max>0 && i>=max) break; i++; String seqString = genbankParser.getSequence(bufferedReader, 0); if(seqString==null) break; @SuppressWarnings("unchecked") S sequence = (S) sequenceCreator.getSequence(seqString, 0); genbankParser.getSequenceHeaderParser().parseHeader(genbankParser.getHeader(), sequence); genbankParser.getFeatures().values().stream() .flatMap(List::stream) .forEach(sequence::addFeature); ArrayList<DBReferenceInfo> dbQualifier = genbankParser.getDatabaseReferences().get("db_xref"); if (dbQualifier != null){ DBReferenceInfo q = dbQualifier.get(0); sequence.setTaxonomy(new TaxonomyID(q.getDatabase()+":"+q.getId(), DataSource.GENBANK)); } sequences.put(sequence.getAccession().getID(), sequence); } return sequences; }</code><technical_language>code style, java if (closed) { throw new IOException... }</technical_language>

Target:
public LinkedHashMap<String,S> process(final int max) throws IOException, CompoundNotFoundException { if(closed){ throw new IOException("Cannot perform action: resource has been closed."); } LinkedHashMap<String,S> sequences = new LinkedHashMap<>(); @SuppressWarnings("unchecked") int i=0; while(true) { if(max>0 && i>=max) break; i++; String seqString = genbankParser.getSequence(bufferedReader, 0); if(seqString==null) break; @SuppressWarnings("unchecked") S sequence = (S) sequenceCreator.getSequence(seqString, 0); genbankParser.getSequenceHeaderParser().parseHeader(genbankParser.getHeader(), sequence); genbankParser.getFeatures().values().stream() .flatMap(List::stream) .forEach(sequence::addFeature); ArrayList<DBReferenceInfo> dbQualifier = genbankParser.getDatabaseReferences().get("db_xref"); if (dbQualifier != null){ DBReferenceInfo q = dbQualifier.get(0); sequence.setTaxonomy(new TaxonomyID(q.getDatabase()+":"+q.getId(), DataSource.GENBANK)); } sequences.put(sequence.getAccession().getID(), sequence); } return sequences; }
Source:
<code>public Set<String> getResourceTypes() { <START> if (myResourceNames == null) { <END> myResourceNames = buildResourceNames(); } return myResourceNames; }</code><technical_language>This threadsafe - fixing</technical_language>

Target:
public Set<String> getResourceTypes() { Set<String> resourceNames = myResourceNames; if (resourceNames == null) { resourceNames = buildResourceNames(); myResourceNames = resourceNames; } return resourceNames; }
Source:
<code>public void shouldUpdateModifiedTimestamp() { Person p = new Person("John", "Phiri"); p.setId(3); logNextTimestamp("now"); personDAO.insert(p); verifyLastTimestamp(T0); <START> when(clock.instant()).thenReturn(T0.plusSeconds(10).toInstant()); <END> Person personAfterCreate = personDAO.get(3); personAfterCreate.setLastName("Banda"); personDAO.updatePerson(personAfterCreate); verifyLastTimestamp(T0.plusSeconds(10)); Person personAfterUpdate = personDAO.get(3); assertThat(personAfterUpdate.getLastName()).isEqualToIgnoringCase("Banda"); assertThat(personAfterUpdate.getCreated()) .isEqualTo(T0_TIMESTAMP) .isEqualTo(personAfterCreate.getCreated()); assertThat(personAfterUpdate.getModified()) .isEqualTo(Timestamp.from(T0.plusSeconds(10).toInstant())); }</code><technical_language>In previous projects folks implement a FakeClock class, methods advance(Duration) simplify simulating passage of time</technical_language>

Target:
public void shouldUpdateModifiedTimestamp() { Person p = new Person("John", "Phiri"); p.setId(3); logNextTimestamp("now"); personDAO.insert(p); verifyLastTimestamp(T0); clock.advance(10, SECONDS); Person personAfterCreate = personDAO.get(3); personAfterCreate.setLastName("Banda"); personDAO.updatePerson(personAfterCreate); verifyLastTimestamp(T0.plusSeconds(10)); Person personAfterUpdate = personDAO.get(3); assertThat(personAfterUpdate.getLastName()).isEqualToIgnoringCase("Banda"); assertThat(personAfterUpdate.getCreated()) .isEqualTo(T0_TIMESTAMP) .isEqualTo(personAfterCreate.getCreated()); assertThat(personAfterUpdate.getModified()) .isEqualTo(Timestamp.from(T0.plusSeconds(10).toInstant())); }
Source:
<code>protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IgniteCache<Integer, BinarylizableWrapper> cache = getIgniteCache(sessionIdentifier); <START> if (cache != null) { <END> BinarylizableWrapper wrapper = cache.get(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Got for session '{}' and page id '{}'", wrapper, sessionIdentifier, id); } if (wrapper != null) { return wrapper.page; } } return null; }</code><technical_language>need check for null ignite.getOrCreateCache(cacheName); Is ignite.getCache(cacheName); create if is need</technical_language>

Target:
protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IgniteCache<Integer, BinarylizableWrapper> cache = getIgniteCache(sessionIdentifier, false); if (cache != null) { BinarylizableWrapper wrapper = cache.get(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Got for session '{}' and page id '{}'", wrapper, sessionIdentifier, id); } if (wrapper != null) { return wrapper.page; } } return null; }
Source:
<code>public void failValidationWithoutSchema() throws Exception { final Environment env = new Environment.Mock() .withFile( "src/main/resources/noschema.xml", "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ); final Validator validator = new XmlValidator(true); <START> validator.validate(env); <END> }</code><technical_language>@Happy-Neko java new XmlValidator(true).validate( new Environment.Mock().withFile( ... ) );</technical_language>

Target:
public void failValidationWithoutSchema() throws Exception { new XmlValidator(true).validate(new Environment.Mock() .withFile( "src/main/resources/noschema.xml", "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ) ); }
Source:
<code>public void checkPrice(ProductItemPrice price) { assert price.getId() > 0 : price; assert price.getItemId() > 0 : price; <START> assert price.getRecurringFee() != null || price.getHourlyRecurringFee() != null : price; <END> }</code><technical_language>Please TestNG [asserts](<LINK_0> in tests</technical_language>

Target:
public void checkPrice(ProductItemPrice price) { assertTrue(price.getId() > 0, "price id must be more than 0"); assertTrue(price.getItemId() > 0, "price itemId must be more than 0"); assertTrue(price.getRecurringFee() != null || price.getHourlyRecurringFee() != null, "price.getRecurringFee() must be not null OR price.getHourlyRecurringFee() must be not null"); }
Source:
<code>private void checkPrivileges(User user) { List<String> requiredPrivs = user.getAllRoles().stream().peek(this::checkSuperUserPrivilege) .map(Role::getPrivileges).filter(Objects::nonNull).flatMap(Collection::stream) .map(Privilege::getPrivilege).filter(p -> !Context.hasPrivilege(p)).collect(Collectors.toList()); if (requiredPrivs.size() == 1) { throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) }); } else if (requiredPrivs.size() > 1) { throw new APIException(String.format(ERROR_FORMAT, String.join(", ", requiredPrivs))); } <START> } <END></code><technical_language>This indented level</technical_language>

Target:
private void checkPrivileges(User user) { List<String> requiredPrivs = user.getAllRoles().stream().peek(this::checkSuperUserPrivilege) .map(Role::getPrivileges).filter(Objects::nonNull).flatMap(Collection::stream) .map(Privilege::getPrivilege).filter(p -> !Context.hasPrivilege(p)).collect(Collectors.toList()); if (requiredPrivs.size() == 1) { throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) }); } else if (requiredPrivs.size() > 1) { throw new APIException(String.format("ERROR_FORMAT", String.join(", ", requiredPrivs))); } }
Source:
<code>public void testPersistentWatchInBackground() throws Exception { try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) { client.start(); client.blockUntilConnected(); <START> CountDownLatch backgroundLatch = new CountDownLatch(1); <END> BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); CountDownLatch latch = new CountDownLatch(3); Watcher watcher = event -> latch.countDown(); client.watchers().add().withMode(AddWatchMode.PERSISTENT).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test/foo"); client.create().creatingParentsIfNeeded().forPath("/test/foo"); client.setData().forPath("/test/foo", "hey".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(timing.awaitLatch(latch)); } }</code><technical_language>purpose of backgroundLatch? get (beyond counted down)</technical_language>

Target:
public void testPersistentWatchInBackground() throws Exception { try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) { client.start(); client.blockUntilConnected(); CountDownLatch backgroundLatch = new CountDownLatch(1); BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); CountDownLatch latch = new CountDownLatch(3); Watcher watcher = event -> latch.countDown(); client.watchers().add().withMode(AddWatchMode.PERSISTENT).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test/foo"); client.create().creatingParentsIfNeeded().forPath("/test/foo"); client.setData().forPath("/test/foo", "hey".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(timing.awaitLatch(backgroundLatch)); Assert.assertTrue(timing.awaitLatch(latch)); } }
Source:
<code>public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { <START> Preconditions.checkArgument( <END> request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } request.setConfig(requestConfig.build()); return new ApacheHttpResponse(request, httpClient.execute(request)); }</code><technical_language>checkState</technical_language>

Target:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } request.setConfig(requestConfig.build()); return new ApacheHttpResponse(request, httpClient.execute(request)); }
Source:
<code>public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); if(this.convertedState==null){ <START> System.err.println("this converted state is null? "); <END> } copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }</code><technical_language>shouldnt System.out.println / System.out.err.println CmdLine.java ZestPrinter.java. If indication of a serious problem throw exception :)</technical_language>

Target:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }
Source:
<code>private CompareInputAdapter getCompareInputAdapter(TreeNode node) { <START> final Iterator<CompareInputAdapter> candidates = Iterables.filter(node.eAdapters(), <END> CompareInputAdapter.class).iterator(); if (candidates.hasNext()) { return candidates.next(); } return null; }</code><technical_language>final Iterator<CompareInputAdapter> candidates = Iterators.filter(node.eAdapters().iterator(), CompareInputAdadpter.class); avoids create intermediate iterable (see Iterables.filter implementation)</technical_language>

Target:
private CompareInputAdapter getCompareInputAdapter(TreeNode node) { return (CompareInputAdapter)Iterators.tryFind(node.eAdapters().iterator(), instanceOf(CompareInputAdapter.class)).orNull(); }