auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute() throws ExecutionException, InterruptedException { final DefaultAddDiscountCodeFormData addDiscountFormData = new DefaultAddDiscountCodeFormData(); addDiscountFormData.setCode(DISCOUNT_CODE); when: { when(hookRunner.runUnaryOperatorHook(any(), any(), cartUpdateCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(hookRunner.runActionHook(any(), any(), any())) .thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(2))); when(sphereClient.execute(any())) <START> .thenReturn(CompletableFuture.completedFuture(cart)); <END> } final Cart updatedCart = defaultAddDiscountCodeControllerAction.apply(cart, addDiscountFormData) .toCompletableFuture().get(); then: { assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()).hasSize(1); final UpdateAction<Cart> cartUpdateAction = cartUpdateCommand.getUpdateActions().get(0); assertThat(cartUpdateAction).isInstanceOf(AddDiscountCode.class); final AddDiscountCode addDiscountCode = (AddDiscountCode) cartUpdateAction; assertThat(addDiscountCode.getCode()).isEqualTo(DISCOUNT_CODE); } }</code><technical_language>missing meaning of mockings, I do fully understand guess is intention them. I hide meaningful method (mockSphereClientThatReturns...) and/or variable (dummy, fake) names. read purpose of test clear figure out code</technical_language>

Target:
public void execute() throws ExecutionException, InterruptedException { final DefaultAddDiscountCodeFormData addDiscountFormData = new DefaultAddDiscountCodeFormData(); addDiscountFormData.setCode(DISCOUNT_CODE); mockHookRunnerThatReturnsCart(); mockSphereClientThatReturnsCart(); final Cart updatedCart = defaultAddDiscountCodeControllerAction.apply(cart, addDiscountFormData) .toCompletableFuture().get(); assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()) .hasSize(1) .hasOnlyElementsOfType(AddDiscountCode.class); final AddDiscountCode addDiscountCode = (AddDiscountCode) cartUpdateCommand.getUpdateActions().get(0); assertThat(addDiscountCode.getCode()).isEqualTo(DISCOUNT_CODE); }
Source:
<code>public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https://<RESOURCE_NAME>.communication.azure.com"; String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); CommunicationClientCredential credential = new CommunicationClientCredential(accessToken); HttpPipelinePolicy hmacAuthenticationPolicy = new HmacAuthenticationPolicy(credential); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(credential) <START> .addPolicy(hmacAuthenticationPolicy) <END> .httpClient(httpClient) .buildClient(); return phoneNumberClient; }</code><technical_language>This policy is needed. Authentication automatically handled CommunicationClientCredential</technical_language>

Target:
public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https://<RESOURCE_NAME>.communication.azure.com"; String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return phoneNumberClient; }
Source:
<code>public void run() { while (true) { <START> if (shutdown) { <END> return; } try { Thread.sleep(sleepMs); } catch (InterruptedException e) { LOG.error("Sleep interrupted", e); continue; } try { purgeMetrics(); } catch (MetricException e) { LOG.error("Failed to purge metrics", e); if (this.failureMeter != null) { this.failureMeter.mark(); } } } }</code><technical_language>Is this a reason separate if statement instead of while (!shutdown)</technical_language>

Target:
public void run() { while (!shutdown) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { LOG.error("Sleep interrupted", e); continue; } try { purgeMetrics(); } catch (MetricException e) { LOG.error("Failed to purge metrics", e); if (this.failureMeter != null) { this.failureMeter.mark(); } } } }
Source:
<code>private void createContext(final Grid parent, final int row, final int col) { parent.resizeRows(row + 1); final CheckBox cb = new CheckBox(PatchUtil.C.showFullFiles()); cb.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if (event.getValue()) { scriptSettings.setContext(WHOLE_FILE_CONTEXT); } else { initContextLines(); } refresh(false ); } }); parent.setWidget(row, col + 1, cb); if (Gerrit.isSignedIn()) { <START> final CheckBox ku = new CheckBox(PatchUtil.C.keepUnreviewed()); <END> ku.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { updateReviewedStatus(event.getValue() ? 0 : 1); } }); parent.setWidget(row, col + 2, ku); } }</code><technical_language>I I prefer this in row, "Show full files" checkbox (same column). Also, I admit, checkbox me. I if "Reviewed" checked default, check-to-uncheck</technical_language>

Target:
private void createContext(final Grid parent, final int row, final int col) { parent.resizeRows(row + 1); final CheckBox cb = new CheckBox(PatchUtil.C.showFullFiles()); cb.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if (event.getValue()) { scriptSettings.setContext(WHOLE_FILE_CONTEXT); } else { initContextLines(); } refresh(false ); } }); parent.setWidget(row, col + 1, cb); if (Gerrit.isSignedIn()) { final CheckBox ku = new CheckBox(PatchUtil.C.reviewed()); ku.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { setReviewedByCurrentUser(event.getValue()); } }); ku.setValue(true); parent.setWidget(row, col + 2, ku); } }
Source:
<code><START> protected IOSample getIOSample(IOLine ioLine) throws TimeoutException, XBeeException { <END> if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); IOSample ioSample; try { ioSample = new IOSample(response.getResponse()); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; }</code><technical_language>Check if ioLine is null throw proper exception</technical_language>

Target:
protected IOSample getIOSample(IOLine ioLine) throws TimeoutException, XBeeException { if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } checkATCommandResponseIsValid(response); IOSample ioSample; try { ioSample = new IOSample(response.getResponse()); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } return ioSample; }
Source:
<code>public static Object fromURL(java.net.URL url) throws JsonParseException, IOException { MappingJsonFactory jsonFactory = new MappingJsonFactory(); URLConnection conn = url.openConnection(); conn.addRequestProperty("Accept", "application/ld+json);"); <START> conn.addRequestProperty("Accept", "application/json;q=0.9, " <END> + "application/javascript;q=0.5, text/javascript;q=0.5, text/plain;q=0.2, " + "*/*;q=0.1"); InputStream in = conn.getInputStream(); try { JsonParser parser = jsonFactory.createParser(in); JsonToken token = parser.nextToken(); Class<?> type; if (token == JsonToken.START_OBJECT) { type = Map.class; } else if(token == JsonToken.START_ARRAY) { type = List.class; } else { type = String.class; } try { return parser.readValueAs(type); } finally { parser.close(); } } finally { in.close(); } }</code><technical_language>I this is add fallbacks. I requests a single Accept header, I happen if multiple headers, choose one, in this case include application/ld+json. include in a single header</technical_language>

Target:
public static Object fromURL(java.net.URL url) throws JsonParseException, IOException { MappingJsonFactory jsonFactory = new MappingJsonFactory(); InputStream in = openStreamFromURL(url); try { JsonParser parser = jsonFactory.createParser(in); JsonToken token = parser.nextToken(); Class<?> type; if (token == JsonToken.START_OBJECT) { type = Map.class; } else if(token == JsonToken.START_ARRAY) { type = List.class; } else { type = String.class; } try { return parser.readValueAs(type); } finally { parser.close(); } } finally { in.close(); } }
Source:
<code>public void render(Screen screen) { Bitmap[][] sheet = Art.getLocalPlayerArt(); <START> if(Options.getAsBoolean(Options.ALTERNATIVE)) { <END> sheet = Art.duchessDonut; } if (team == Team.Team2) { sheet = Art.herrSpeck; } if (dead) { return; } int frame = (walkTime / 4 % 6 + 6) % 6; int facing = this.facing + (carrying != null ? 8 : 0); double xmuzzle = muzzleX + ((facing == 0) ? 4 : 0); double ymuzzle = muzzleY - ((facing == 0) ? 4 : 0); boolean behind = (facing >= 3 && facing <= 5); if (muzzleTicks > 0 && behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } if (hurtTime % 2 != 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ff0000); } else if (flashTime > 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ffff80); } else { screen.blit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8); } if (muzzleTicks > 0 && !behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } renderCarrying(screen, (frame == 0 || frame == 3) ? -1 : 0); }</code><technical_language>getlocalplayerart() if useless</technical_language>

Target:
public void render(Screen screen) { Bitmap[][] sheet = Art.getLocalPlayerArt(); if (dead) { return; } int frame = (walkTime / 4 % 6 + 6) % 6; int facing = this.facing + (carrying != null ? 8 : 0); double xmuzzle = muzzleX + ((facing == 0) ? 4 : 0); double ymuzzle = muzzleY - ((facing == 0) ? 4 : 0); boolean behind = (facing >= 3 && facing <= 5); if (muzzleTicks > 0 && behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } if (hurtTime % 2 != 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ff0000); } else if (flashTime > 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ffff80); } else { screen.blit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8); } if (muzzleTicks > 0 && !behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } renderCarrying(screen, (frame == 0 || frame == 3) ? -1 : 0); }
Source:
<code>public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, LedgerType.PD_JOURNAL) <START> .initiateAdv((long)(-1)); <END> } finally { closeLock.readLock().unlock(); } }</code><technical_language>cast here? change -1L</technical_language>

Target:
public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, LedgerType.PD_JOURNAL) .initiateAdv(BookieProtocol.INVALID_LEDGER_ID); } finally { closeLock.readLock().unlock(); } }
Source:
<code>public boolean equalsWrappedBytes(WrappedBytes other) { <START> return Arrays.equals(bytes, other.getBytes()); <END> }</code><technical_language>~~Unfortunately do this. is guarantee getBytes return a byte[]. For example heap this null.~~ This thinking heap, for now</technical_language>

Target:
public boolean equalsWrappedBytes(WrappedBytes other) { int length = getLength(); if (other.getLength() != length) return false; if (other.hashCode() != hashCode()) return false; for (int i = 0; i < length; ++i) { if (getByte(i) != other.getByte(i)) return false; } return true; }
Source:
<code>public void setItems(Collection value) { genVersionToBaseTemplate(value); <START> final List<VmTemplate> sortedValues = sortTemplates(value); <END> super.setItems(sortedValues); }</code><technical_language>this affect sorting webadmin - webadmin support sortable columns. Please move this logic UserPortalTemplateListModel</technical_language>

Target:
public void setItems(Collection value) { genVersionToBaseTemplate(value); super.setItems(value); }
Source:
<code>@Override public boolean isAlwaysFalse() { switch (getKind()) { case IS_NOT_NULL: return operands.get(0).isAlwaysNull(); case IS_NULL: case IS_UNKNOWN: return !operands.get(0).getType().isNullable(); case IS_FALSE: case IS_NOT_TRUE: case NOT: return operands.get(0).isAlwaysTrue(); case IS_NOT_FALSE: case IS_TRUE: case CAST: case MAX: case MIN: return operands.get(0).isAlwaysFalse(); case OR: for (RexNode operand : operands) { <START> if (!operand.isAlwaysFalse()) { <END> return false; } } return true; case AND: for (RexNode operand : operands) { if (operand.isAlwaysFalse()) { return true; } } return false; case EQUALS: case NOT_EQUALS: { RexNode o0 = operands.get(0); RexNode o1 = operands.get(1); if (!getType().isNullable() && o0.equals(o1)) { return getKind() == SqlKind.NOT_EQUALS; } int k0 = o0.isAlwaysTrue() ? 1 : (o0.isAlwaysFalse() ? 2 : 0); if (k0 != 0) { int k1 = o1.isAlwaysTrue() ? 1 : (o1.isAlwaysFalse() ? 2 : 0); return k1 != 0 && k0 != k1 ^ (getKind() != SqlKind.EQUALS); } return false; } default: return false; } }</code><technical_language>I this is a bit much...it work; a single isAlwaysTrue() call do a full visit subtree... a public method I takes O(1) time... I cases handled RexSimplify</technical_language>

Target:
@Override public boolean isAlwaysFalse() { switch (getKind()) { case IS_NOT_NULL: return operands.get(0).isAlwaysNull(); case IS_NULL: case IS_UNKNOWN: return !operands.get(0).getType().isNullable(); case IS_FALSE: case IS_NOT_TRUE: case NOT: return operands.get(0).isAlwaysTrue(); case IS_NOT_FALSE: case IS_TRUE: case CAST: return operands.get(0).isAlwaysFalse(); default: return false; } }
Source:
<code>public boolean isStep() { <START> if (content.size() > 0) { <END> int type = getTokenType(0); if (type == Token.QNAME || type == Token.WILDCARD || type == Token.NSWILDCARD || type == Token.AT || type == Token.DOT || type == Token.DBL_DOT) { return true; } else if (content.get(0) instanceof ASTNodeFunctionCall) { String name = ((ASTNodeFunctionCall)content.get(0)).name.toString(); return (name.equals("node") || name.equals("text") || name.equals("comment") || name.equals("processing-instruction")); } else { return false; } } else { return false; } }</code><technical_language>sense this class's size() method here, exists</technical_language>

Target:
public boolean isStep() { if (size() > 0) { int type = getTokenType(0); if (type == Token.QNAME || type == Token.WILDCARD || type == Token.NSWILDCARD || type == Token.AT || type == Token.DOT || type == Token.DBL_DOT) { return true; } else if (content.get(0) instanceof ASTNodeFunctionCall) { String name = ((ASTNodeFunctionCall)content.get(0)).name.toString(); return (name.equals("node") || name.equals("text") || name.equals("comment") || name.equals("processing-instruction")); } else { return false; } } else { return false; } }
Source:
<code>public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ListModel<?>) { ListModel<?> listmodel = (ListModel<?>) base; Integer idx = coerce(property); boolean itemIdx = true; if (idx == null) { itemIdx = false; if (property instanceof String) { try { property = Fields.get(base, (String) property); } catch (NoSuchMethodException e) { } idx = coerce(property); } if (idx == null) { return null; <START> } <END> } context.setPropertyResolved(true); if (idx >= 0 && idx < listmodel.getSize() && itemIdx == true) { return listmodel.getElementAt(idx); } else if (itemIdx == false) { return idx; } } return null; }</code><technical_language>A workaround in ListModelELResolver is absolutely wrong. In fact, ListELResolver is wrong (<LINK_0> If property is a number, return null (and throw exception) BeanELResolver handle it</technical_language>

Target:
public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ListModel<?>) { ListModel<?> listmodel = (ListModel<?>) base; Integer idx = coerce(property); if (idx == null) { return null; } context.setPropertyResolved(true); if (idx >= 0 && idx < listmodel.getSize()) { return listmodel.getElementAt(idx); } } return null; }
Source:
<code>public Factory<PaxosAcceptorNetworkClient> acceptor() { return client -> { List<PaxosAcceptor> remoteAcceptors = TimelockPaxosAcceptorAdapter .wrap(useCase(), remoteClients()) .apply(client); PaxosAcceptor localAcceptor = components().acceptor(client); <START> LocalAndRemotes<PaxosAcceptor> allAcceptors = LocalAndRemotes.of(localAcceptor, remoteAcceptors); <END> return new SingleLeaderAcceptorNetworkClient( allAcceptors.all(), quorumSize(), allAcceptors.withSharedExecutor(sharedExecutor())); }; }</code><technical_language>enhanceRemotes</technical_language>

Target:
public Factory<PaxosAcceptorNetworkClient> acceptor() { return client -> { List<PaxosAcceptor> remoteAcceptors = TimelockPaxosAcceptorAdapter .wrap(useCase(), remoteClients()) .apply(client); PaxosAcceptor localAcceptor = components().acceptor(client); LocalAndRemotes<PaxosAcceptor> allAcceptors = LocalAndRemotes.of(localAcceptor, remoteAcceptors) .enhanceRemotes(remote -> metrics().instrument(PaxosAcceptor.class, remote, client)); SingleLeaderAcceptorNetworkClient uninstrumentedAcceptor = new SingleLeaderAcceptorNetworkClient( allAcceptors.all(), quorumSize(), allAcceptors.withSharedExecutor(sharedExecutor())); return metrics().instrument(PaxosAcceptorNetworkClient.class, uninstrumentedAcceptor); }; }
Source:
<code>private void createPodPathControls(Composite parent, DataBindingContext dbc) { Label deployPathLabel = new Label(parent, SWT.NONE); deployPathLabel.setText("Pod Deployment Path: "); applyAlignData(SWT.BEGINNING, SWT.CENTER,deployPathLabel); deployPathText = new Text(parent, SWT.BORDER); applyGridData(2, 1, SWT.FILL, SWT.CENTER,true, false,deployPathText); deployPathModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { execute(new ServerWorkingCopyPropertyTextCommand(input.getServer(), "Set Deploy Path", deployPathText, deployPathText.getText(), OpenShiftServerUtils.ATTR_POD_PATH, this)); } }; ModifyListener deployPathDecoration = new TextboxDecoratorSupport(deployPathText, new IValidator() { @Override public IStatus validate(Object value) { if (!(value instanceof String) || StringUtils.isEmpty(value)) { return ValidationStatus.cancel("Please provide a path to deploy to on the pod."); } if (!Path.isValidPosixPath((String)value)) { <START> return ValidationStatus.error("Please provide a valid path to deploy to on the pod"); <END> } return Status.OK_STATUS; } }); deployPathText.addModifyListener(deployPathDecoration); }</code><technical_language>written in a more jdk8 fashion lambda: ModifyListener deployPathDecoration = new TextboxDecoratorSupport(deployPathText, -> { // TODO validate if (!(value instanceof String) || StringUtils.isEmpty(value)) { return ValidationStatus.cancel("Please provide a path deploy pod."); } if (!Path.isValidPosixPath((String)value)) { return ValidationStatus.error("Please provide a valid path deploy pod"); } return Status.OK_STATUS; }); of listeners use</technical_language>

Target:
private void createPodPathControls(Composite parent, DataBindingContext dbc) { Label deployPathLabel = new Label(parent, SWT.NONE); deployPathLabel.setText("Pod Deployment Path: "); GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(deployPathLabel); deployPathText = new Text(parent, SWT.BORDER); GridDataFactory.fillDefaults().span(2,1).align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(deployPathText); deployPathModifyListener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { execute(new ServerWorkingCopyPropertyTextCommand(input.getServer(), "Set Deploy Path", deployPathText, deployPathText.getText(), OpenShiftServerUtils.ATTR_POD_PATH, (ModifyListener) this)); } }; ModifyListener deployPathDecoration = new TextboxDecoratorSupport(deployPathText, value -> { if (!(value instanceof String) || StringUtils.isEmpty(value)) { return ValidationStatus.cancel("Please provide a path to deploy to on the pod."); } if (!Path.isValidPosixPath((String)value)) { return ValidationStatus.error("Please provide a valid path to deploy to on the pod"); } return Status.OK_STATUS; }); deployPathText.addModifyListener(deployPathDecoration); }
Source:
<code>private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); Instant now = Instant.now(); <START> Files.setLastModifiedTime(probe, FileTime.from(now)); <END> FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant tset = t1.toInstant(); while (t2.compareTo(t1) <= 0) { tset = tset.plusNanos(1); Files.setLastModifiedTime(probe, FileTime.from(tset)); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); saveFileTimeResolution(s, fsResolution.plus(clockResolution)); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }</code><technical_language>this is necessary, right? current mod time of file, increase change</technical_language>

Target:
private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); Instant now = Instant.now(); Files.setLastModifiedTime(probe, FileTime.from(now)); FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant t1i = t1.toInstant(); for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 200) { Files.setLastModifiedTime(probe, FileTime.from(t1i.plusNanos(i * 1000))); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); fsResolution = fsResolution.plus(clockResolution); saveFileTimeResolution(s, fsResolution); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }
Source:
<code><START> public double getArmorRemainingPercent() { <END> if(getPosition() == null) { return 100; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 100; } return (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition())) / (initialBuildingCF + initialBuildingArmor); }</code><technical_language>logic in a previous file 1.0 if percent a fraction. This insinuate percents</technical_language>

Target:
public double getArmorRemainingPercent() { if(getPosition() == null) { return 1.0; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 1.0; } return (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition())) / (initialBuildingCF + initialBuildingArmor); }
Source:
<code>private LoadingCache<String, TransportNetwork> createCache(int size) { RemovalListener<String, TransportNetwork> removalListener = removalNotification -> { String id = removalNotification.getKey(); if (sourceBucket != null) { String[] extensions = {".db", ".db.p", ".zip"}; for (String type : extensions) { File file = new File(cacheDir, id + type); file.delete(); } } }; return CacheBuilder.newBuilder() .maximumSize(size) .removalListener(removalListener) <START> .build(new CacheLoader() { <END> public TransportNetwork load(Object s) throws Exception { return getNetwork((String) s); } }); }</code><technical_language>a lambda function here</technical_language>

Target:
private LoadingCache createCache(int size) { RemovalListener<String, TransportNetwork> removalListener = removalNotification -> { String id = removalNotification.getKey(); if (sourceBucket != null) { String[] extensions = {".db", ".db.p", ".zip"}; for (String type : extensions) { File file = new File(cacheDir, id + type); file.delete(); } } }; return CacheBuilder.newBuilder() .maximumSize(size) .removalListener(removalListener) .build(new CacheLoader() { public TransportNetwork load(Object s) throws Exception { return loadNetwork((String) s); } }); }
Source:
<code>private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { String engineSessionId = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)).getActionReturnValue(); <START> if (StringUtils.isNotEmpty(engineSessionId)) { <END> try { VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, new VdcQueryParametersBase(), new EngineContext().withSessionId(engineSessionId)); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } } return jsonVms; }</code><technical_language>please do check return code implicitly, I is getSucceeded() raise exception</technical_language>

Target:
private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { VdcReturnValueBase loginResult = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)); if (!loginResult.getSucceeded()) { throw new RuntimeException("Unable to create session using LoginOnBehalf"); } String engineSessionId = loginResult.getActionReturnValue(); try { VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, new VdcQueryParametersBase(), new EngineContext().withSessionId(engineSessionId)); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } return jsonVms; }
Source:
<code>public long fetchLastModifiedDate(SyncManager syncManager, String objectType, String objectId) throws JSONException, IOException { boolean isNewer = false; long serverLastModified = -1L; final String query = SOQLBuilder.getInstanceWithFields(Constants.LAST_MODIFIED_DATE) .from(objectType) .where(Constants.ID + " = '" + objectId + "'") .build(); <START> RestResponse lastModResponse = syncManager.sendSyncWithSmartSyncUserAgent(RestRequest.getRequestForQuery(syncManager.apiVersion, query)); <END> if (lastModResponse != null && lastModResponse.isSuccess()) { final JSONObject responseJSON = lastModResponse.asJSONObject(); if (responseJSON != null) { final JSONArray records = responseJSON.optJSONArray(Constants.RECORDS); if (records != null && records.length() > 0) { final JSONObject obj = records.optJSONObject(0); if (obj != null) { final String lastModStr = obj.optString(Constants.LAST_MODIFIED_DATE); if (!TextUtils.isEmpty(lastModStr)) { try { serverLastModified = Constants.TIMESTAMP_FORMAT.parse(lastModStr).getTime(); } catch (ParseException e) { Log.e("SyncUpTarget:fetchLastModifiedDate", "Error during date parsing", e); } } } } } } return serverLastModified; }</code><technical_language>concerned this happening synchronously? is this in area parent context is asynchronous</technical_language>

Target:
public String fetchLastModifiedDate(SyncManager syncManager, String objectType, String objectId) throws JSONException, IOException { final String query = SOQLBuilder.getInstanceWithFields(Constants.LAST_MODIFIED_DATE) .from(objectType) .where(Constants.ID + " = '" + objectId + "'") .build(); RestResponse lastModResponse = syncManager.sendSyncWithSmartSyncUserAgent(RestRequest.getRequestForQuery(syncManager.apiVersion, query)); return lastModResponse.asJSONObject().optJSONArray(Constants.RECORDS).optJSONObject(0).optString(Constants.LAST_MODIFIED_DATE); }
Source:
<code>public void testInvalidXpath() throws IOException { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final Path file = Files.createTempFile("", ""); Files.write(file, fileContent.getBytes(StandardCharsets.UTF_8)); try { XpathUtil.printXpathBranch("\\ file.toFile()); fail("Should end with exception"); } catch (CheckstyleException ex) { final String expectedMessage = "Error during xpath evaluation"; assertEquals("Exception message is different", expectedMessage, ex.getMessage()); } <START> } <END></code><technical_language>start practicing assertThat ? do concern assertThat</technical_language>

Target:
public void testInvalidXpath() throws IOException { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final File file = tempFolder.newFile(); Files.write(file.toPath(), fileContent.getBytes(StandardCharsets.UTF_8)); final String invalidXpath = "\\ try { XpathUtil.printXpathBranch(invalidXpath, file); fail("Should end with exception"); } catch (CheckstyleException ex) { final String expectedMessage = "Error during evaluation for xpath: " + invalidXpath + ", file: " + file.getCanonicalPath(); assertThat("Exception message is different", ex.getMessage(), is(expectedMessage)); } }
Source:
<code>public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", <START> "Teammates Institute", "American", GenderType.OTHER, <END> new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); assertEquals(studentProfile.getGender(), profileAttributes.gender); assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }</code><technical_language>Minor: enum</technical_language>

Target:
public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", "Teammates Institute", "American", GenderType.MALE, new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); assertEquals(studentProfile.getGender(), profileAttributes.gender); assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }
Source:
<code>private void createChannel() { NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); mChannel.setDescription(CHANNEL_DESCRIPTION); mChannel.setShowBadge(true); mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); <START> mNotificationManager.createNotificationChannel(mChannel); <END> }</code><technical_language>mNotificationManager null</technical_language>

Target:
private void createChannel() { NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); if (mNotificationManager == null) { return; } NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); mChannel.setDescription(CHANNEL_DESCRIPTION); mChannel.setShowBadge(true); mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); mNotificationManager.createNotificationChannel(mChannel); }
Source:
<code>public static TraceLogLevel valueOfString(String name) { if (name == null) { <START> throw new InvalidParameterException(); <END> } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } return LEVEL_UNKNOWN; }</code><technical_language>InvalidArgumentException instead</technical_language>

Target:
public static TraceLogLevel valueOfString(String name) { if (name == null) { throw new IllegalArgumentException(); } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } return LEVEL_UNKNOWN; }
Source:
<code>private List<Device> findDevices(final List<DeviceModel> deviceModels) { LOGGER.info("Trying to find devices for device models for manufacturer..."); final List<Device> devices = new ArrayList<>(); for (final DeviceModel deviceModel : deviceModels) { <START> final List<Device> devs = this.deviceRepository.findByDeviceModelAndInMaintenanceFalse(deviceModel); <END> devices.addAll(devs); } if (devices.isEmpty()) { LOGGER.warn("No devices found for device models for manufacturer"); } else { LOGGER.info("{} devices found for device models for manufacturer", devices.size()); } return devices; }</code><technical_language>include SSLDs? Otherwise, if Kaifa smart meters in a system, contacting for events well</technical_language>

Target:
private List<Device> findDevices(final List<DeviceModel> deviceModels) { LOGGER.info("Trying to find devices for device models for manufacturer..."); final List<Device> devices = new ArrayList<>(); for (final DeviceModel deviceModel : deviceModels) { final List<Device> devs = this.deviceRepository.findByDeviceModelAndDeviceTypeAndInMaintenance(deviceModel, Ssld.SSLD_TYPE, false); devices.addAll(devs); } if (devices.isEmpty()) { LOGGER.warn("No devices found for device models for manufacturer"); } else { LOGGER.info("{} devices found for device models for manufacturer", devices.size()); } return devices; }
Source:
<code>private void addDefinedContracts() { Parameters contractEmulations = getMergedParameters(Constants.DEFINE_CONTRACT); <START> contracts.collectContracts("emulated", contractEmulations); <END> }</code><technical_language>emulated in string variable name. is bnd configuration vs. a jar file</technical_language>

Target:
private void addDefinedContracts() { Parameters definedContracts = getMergedParameters(Constants.DEFINE_CONTRACT); contracts.collectContracts(Constants.DEFINE_CONTRACT, definedContracts); }
Source:
<code>private static void sortStudentResultList(List<StudentAttributes> studentList) { studentList.sort(Comparator.comparing((StudentAttributes student) -> student.course) .thenComparing(student -> student.section) .thenComparing(student -> student.team) .thenComparing(student -> student.name) <START> .thenComparing(student -> student.name)); <END> }</code><technical_language>careful copy-pasting..</technical_language>

Target:
private static void sortStudentResultList(List<StudentAttributes> studentList) { studentList.sort(Comparator.comparing((StudentAttributes student) -> student.course) .thenComparing(student -> student.section) .thenComparing(student -> student.team) .thenComparing(student -> student.name) .thenComparing(student -> student.email)); }
Source:
<code>public ImmutableSet<E> getDirectParents(E element) { final ImmutableSet.Builder<E> builder = ImmutableSet.builder(); builder.addAll(graph.getDirectParents(element)); <START> return builder.build(); <END> }</code><technical_language>return ImmutableSet.copyOf(graph.getDirectParents(element));</technical_language>

Target:
public ImmutableSet<E> getDirectParents(E element) { return ImmutableSet.copyOf(graph.getDirectParents(element)); }
Source:
<code>public boolean startup( IPentahoSession session ) { Response status; Map<String, JSONObject> jsonFiles = new HashMap<>(); try { if ( environmentVariablesFilepath != null ) { JSONObject environmentVariables = getJsonFromFile( new File( environmentVariablesFilepath ) ); jsonFiles.put( environmentVariablesFilepath, environmentVariables ); } else { jsonFiles = parseJsonFiles(); } for ( String filename : jsonFiles.keySet() ) { JSONObject json = jsonFiles.get( filename ); WorkItemRequestPayload payload = new WorkItemRequestPayload( json ); if ( !payload.isValid() ) { logger.error( "File: " + filename + " is missing required parameters, skipping" ); } else { status = issueRequest( payload ); if ( status == null ) { logger.error( "File: " + filename + " has parameters formatted in an unparsable way. Could not process work item." ); } } <START> renameFile( filename ); <END> } } catch ( ParseException | IOException | SecurityException e ) { logger.error( e.getMessage(), e ); } return true; }</code><technical_language>Suggestion: adding a try-finally clause for loop, ends happening ( successful execution, NPE some other unchecked exception ), renaming file append timestamp: for ( String filename : jsonFiles.keySet() ) { try { JSONObject json = jsonFiles.get( filename ); WorkItemRequestPayload payload = new WorkItemRequestPayload( json ); if ( !payload.isValid() ) { logger.error( "File: " + filename + " is missing required parameters, skipping" ); } else { status = issueRequest( payload ); if ( status == null ) { logger.error( "File: " + filename + " parameters formatted in unparsable way. process work item." ); } //todo- sometype of status handling WI lifecycle is defined } } finally { renameFile( filename ); } }</technical_language>

Target:
public boolean startup( IPentahoSession session ) { Response status; Map<String, JSONObject> jsonFiles = new HashMap<>(); if ( environmentVariablesFilepath != null ) { JSONObject environmentVariables = getJsonFromFile( new File( environmentVariablesFilepath ) ); jsonFiles.put( environmentVariablesFilepath, environmentVariables ); } else { jsonFiles = parseJsonFiles(); } for ( String filename : jsonFiles.keySet() ) { JSONObject json = jsonFiles.get( filename ); WorkItemRequestPayload payload = new WorkItemRequestPayload( json ); if ( !payload.isValid() ) { logger.error( "File: " + filename + " is missing required parameters, skipping" ); renameFile( filename ); } else { try { status = issueRequest( payload ); if ( status == null ) { logger.error( "File: " + filename + " has parameters formatted in an unparsable way. Could not process work item." ); } } catch ( Exception e ) { logger.error( "Error processing " + filename + " skipping" ); } finally { renameFile( filename ); } } } return true; }
Source:
<code>public String getValue(DynamicOptions dynamicOptions) { if (value != null) { return value; <START> } else if (dynamicOptions.getVariableOptionIndex() != 1){ <END> return variableValues.get(dynamicOptions.getVariableOptionIndex()); } else if (templateBuilder != null) { return templateBuilder.build(dynamicOptions.getEvent()); } else { return null; } }</code><technical_language>!= -1</technical_language>

Target:
public String getValue(DynamicOptions dynamicOptions) { if (dynamicOptions.getVariableOptionIndex() != -1 && !variableValues.isEmpty()) { return variableValues.get(dynamicOptions.getVariableOptionIndex()); } else if (value != null) { return value; } else if (templateBuilder != null) { return templateBuilder.build(dynamicOptions.getEvent()); } else { return null; } }
Source:
<code>public Constraint copyOver(RelationalSymbolicValue.Kind kind) { if(kind == GREATER_THAN_OR_EQUAL || kind == LESS_THAN) { return null; } <START> return Constraint.super.copyOver(kind); <END> }</code><technical_language>I more readable inline logic super switch (kind) { case EQUAL: case METHOD_EQUALS: return this; case LESS_THAN: case GREATER_THAN_OR_EQUAL: return null; default: return inverse(); }</technical_language>

Target:
public Constraint copyOver(RelationalSymbolicValue.Kind kind) { switch (kind) { case LESS_THAN: case GREATER_THAN_OR_EQUAL: return null; case EQUAL: case METHOD_EQUALS: return this; default: return inverse(); } }
Source:
<code>public void testGetConsumerInputPartioning() { int partitionBlockSize = 5; ConsumerCurator curator = Mockito.spy(consumerCurator); when(curator.getInBlockSize()).thenReturn(partitionBlockSize); <START> Map<String, Consumer> consumers = new HashMap<>(); <END> for (int i = 0; i < partitionBlockSize * 5; ++i) { Consumer consumer = new Consumer("consumer-" + i, "user-" + i, owner, ct); consumer.setUuid("uuid-" + i); curator.create(consumer); consumers.put(consumer.getUuid(), consumer); } curator.flush(); Set<String> input = new HashSet<>(); Set<Consumer> expected = new HashSet<>(); for (int i = 0; i < partitionBlockSize * 3 + 1; ++i) { Consumer consumer = consumers.get("uuid-" + i); input.add(consumer.getId()); expected.add(consumer); } Collection<Consumer> output = curator.getConsumers(input); assertEquals(output.size(), expected.size()); for (Consumer consumer : expected) { assertTrue(output.contains(consumer)); } }</code><technical_language>This test setup is noisy is repeated in multiple tests readability extracting methods</technical_language>

Target:
public void testGetConsumerInputPartioning() { int partitionBlockSize = 5; ConsumerCurator curator = Mockito.spy(consumerCurator); when(curator.getInBlockSize()).thenReturn(partitionBlockSize); Map<String, Consumer> consumers = new HashMap<>(); for (int i = 0; i < partitionBlockSize * 5; ++i) { Consumer consumer = new Consumer("consumer-" + i, "user-" + i, owner, ct); consumer.setUuid("uuid-" + i); curator.create(consumer); consumers.put(consumer.getUuid(), consumer); } curator.flush(); Set<String> input = new HashSet<>(); Set<Consumer> expected = new HashSet<>(); for (int i = 0; i < partitionBlockSize * 10; ++i) { Consumer consumer = consumers.get("uuid-" + i); if (consumer != null) { expected.add(consumer); input.add(consumer.getId()); } else { input.add("id-" + i); } } Collection<Consumer> output = curator.getConsumers(input); assertEquals(output.size(), expected.size()); for (Consumer consumer : expected) { assertTrue(output.contains(consumer)); } }