auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public RemoteOperationResult(HttpBaseMethod httpMethod) throws IOException { this(httpMethod.getStatusCode(), httpMethod.getStatusMessage(), httpMethod.getResponseHeaders() ); if (mHttpCode == HttpConstants.HTTP_BAD_REQUEST) { String bodyResponse = httpMethod.getResponseBodyAsString(); if (bodyResponse != null && bodyResponse.length() > 0) { InputStream is = new ByteArrayInputStream(bodyResponse.getBytes()); InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser(); try { if (xmlParser.parseXMLResponse(is)) { mCode = ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER; } } catch (Exception e) { Log_OC.w(TAG, "Error reading exception from server: " + e.getMessage()); } } } switch (mHttpCode) { case HttpConstants.HTTP_FORBIDDEN: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_FORBIDDEN ); break; case HttpConstants.HTTP_UNSUPPORTED_MEDIA_TYPE: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_UNSUPPORTED_MEDIA_TYPE ); break; case HttpConstants.HTTP_SERVICE_UNAVAILABLE: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_SERVICE_UNAVAILABLE ); break; case HttpConstants.HTTP_METHOD_NOT_ALLOWED: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), <START> ResultCode.SPECIFIC_SERVICE_UNAVAILABLE <END> ); default: break; } }</code><technical_language>create a specific code for this case, ResultCode.SPECIFIC_METHOD_NOT_ALLOWED needed</technical_language>

Target:
public RemoteOperationResult(HttpBaseMethod httpMethod) throws IOException { this(httpMethod.getStatusCode(), httpMethod.getStatusMessage(), httpMethod.getResponseHeaders() ); if (mHttpCode == HttpConstants.HTTP_BAD_REQUEST) { String bodyResponse = httpMethod.getResponseBodyAsString(); if (bodyResponse != null && bodyResponse.length() > 0) { InputStream is = new ByteArrayInputStream(bodyResponse.getBytes()); InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser(); try { if (xmlParser.parseXMLResponse(is)) { mCode = ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER; } } catch (Exception e) { Log_OC.w(TAG, "Error reading exception from server: " + e.getMessage()); } } } switch (mHttpCode) { case HttpConstants.HTTP_FORBIDDEN: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_FORBIDDEN ); break; case HttpConstants.HTTP_UNSUPPORTED_MEDIA_TYPE: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_UNSUPPORTED_MEDIA_TYPE ); break; case HttpConstants.HTTP_SERVICE_UNAVAILABLE: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_SERVICE_UNAVAILABLE ); break; case HttpConstants.HTTP_METHOD_NOT_ALLOWED: parseErrorMessageAndSetCode( httpMethod.getResponseBodyAsString(), ResultCode.SPECIFIC_METHOD_NOT_ALLOWED ); default: break; } }
Source:
<code><START> public T getFirstResult() { <END> Collection<T> list = getResult(); if (list == null) { return null; } Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return iterator.next(); } return null; }</code><technical_language>For new API prefer return java.util.Optional<T> instead of null avoid potential NPEs</technical_language>

Target:
public Optional<T> getFirstResult() { Collection<T> list = getResult(); Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return Optional.of(iterator.next()); } return Optional.empty(); }
Source:
<code>public void onBeginNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntOffered) throws UploadPackMayNotContinueException { <START> for (PreUploadHook hook : hooks) { <END> hook.onBeginNegotiateRound(up, wants, cntOffered); } }</code><technical_language>curly braces</technical_language>

Target:
public void onBeginNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntOffered) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onBeginNegotiateRound(up, wants, cntOffered); }
Source:
<code>private void checkExitStatus() { int exitValue = process.exitValue(); if (exitValue != 0) { String timestamp = Long.toString(System.currentTimeMillis()); String backupVepOutput = annotationParameters.getVepOutput().replaceFirst("tsv\\.gz$", timestamp + ".tsv.gz"); String errorLog = backupVepOutput + ".errors.txt"; try { connectStreams(process.getErrorStream(), new FileOutputStream(errorLog)); } catch (IOException e) { throw new ItemStreamException("VEP exited with code " + exitValue + " but the file to dump the errors could not be created: " + errorLog, e); } boolean renamed = new File(annotationParameters.getVepOutput()).renameTo(new File(backupVepOutput)); if (renamed) { <START> logger.info("Renamed VEP output to " + backupVepOutput + " as backup because VEP failed"); <END> } throw new ItemStreamException("Error while running VEP (exit status " + exitValue + "). See " + errorLog + " for the errors description from VEP."); } }</code><technical_language>I of a more clear express this. do of following? Sorted in preference: 1. logger.info("Backup of failed VEP output saved " + backupVepOutput) 2. logger.info("Failed VEP output saved " + backupVepOutput) 3. logger.info("VEP output backed in " + backupVepOutput + " VEP failed")</technical_language>

Target:
private void checkExitStatus() { int exitValue = process.exitValue(); if (exitValue != 0) { String timestamp = Long.toString(System.currentTimeMillis()); String backupVepOutput = annotationParameters.getVepOutput().replaceFirst("tsv\\.gz$", timestamp + ".tsv.gz"); String errorLog = backupVepOutput + ".errors.txt"; try { connectStreams(process.getErrorStream(), new FileOutputStream(errorLog)); } catch (IOException e) { throw new ItemStreamException("VEP exited with code " + exitValue + " but the file to dump the errors could not be created: " + errorLog, e); } boolean renamed = new File(annotationParameters.getVepOutput()).renameTo(new File(backupVepOutput)); if (renamed) { logger.info("Failed VEP output saved to " + backupVepOutput); } throw new ItemStreamException("Error while running VEP (exit status " + exitValue + "). See " + errorLog + " for the errors description from VEP."); } }
Source:
<code>public static void sendUnhandledCaughtException() { String json = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (isReportingEnabled() && !json.isEmpty()) { Log.d(TAG, "AFTER_EXCEPTION : sendCaughtException()"); Gson gson = new Gson(); Throwable exception = gson.fromJson(json, Throwable.class); <START> if (logException(exception)) { <END> preferences.edit().remove(EXCEPTION_FOR_REPORT).commit(); } } }</code><technical_language>please logException return void. - boolean return is utilized here. - true, in line 93 reached isReportingEnabled() is true</technical_language>

Target:
public static void sendUnhandledCaughtException() { String json = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (isReportingEnabled() && !json.isEmpty()) { Log.d(TAG, "AFTER_EXCEPTION : sendCaughtException()"); Gson gson = new Gson(); Throwable exception = gson.fromJson(json, Throwable.class); logException(exception); preferences.edit().remove(EXCEPTION_FOR_REPORT).commit(); } }
Source:
<code>protected String explainPlanForNode(String indent) { String optionalTableName = "*NO MATCH -- USE ALL TABLE NAMES*"; StringBuilder sb = new StringBuilder(" PARTITION BY PLAN: " + super.explainPlanForNode(indent) + "\n"); <START> sb.append(indent).append(" SORT BY: \n"); <END> for (int idx = 0; idx < numberSortExpressions(); idx += 1) { AbstractExpression ae = getSortExpression(idx); SortDirectionType dir = getSortDirection(idx); sb.append(indent) .append(ae.explain(optionalTableName)) .append(": ") .append(dir.name()) .append("\n"); } sb.append(" PARTITION BY:\n"); WindowedExpression we = getWindowedExpression(); for (int idx = 0; idx < numberPartitionByExpressions(); idx += 1) { sb.append(" ") .append(idx).append(": ") .append(we.getPartitionByExpressions().get(idx).toString()) .append("\n"); } return sb.toString(); }</code><technical_language>PARTITION clause in SQL syntax, sense put here</technical_language>

Target:
protected String explainPlanForNode(String indent) { String optionalTableName = "*NO MATCH -- USE ALL TABLE NAMES*"; String newIndent = " " + indent; StringBuilder sb = new StringBuilder(indent + "PARTITION BY PLAN\n"); sb.append(newIndent + "PARTITION BY:\n"); int numExprs = getNumberOfPartitionByExpressions(); for (int idx = 0; idx < numExprs; idx += 1) { AbstractExpression ae = getPartitionByExpression(idx); sb.append(" ") .append(newIndent) .append(idx).append(": ") .append(ae.toString()); } String sep = ""; sb.append(newIndent).append("SORT BY:\n"); numExprs = numberSortExpressions(); for (int idx = 0; idx < numExprs; idx += 1) { AbstractExpression ae = getSortExpression(idx); SortDirectionType dir = getSortDirection(idx); sb.append(sep).append(" ") .append(newIndent) .append(idx).append(":") .append(ae.explain(optionalTableName)) .append(" ") .append(dir.name()); sep = "\n"; } return sb.toString(); }
Source:
<code><START> private void waitForServerDecom(HRegionServer excludeServer) throws IOException { <END> TEST_UTIL.getAdmin().decommissionRegionServers( Collections.singletonList(excludeServer.getServerName()), false); TEST_UTIL.waitFor(3000, () -> { try { List<ServerName> decomServers = TEST_UTIL.getAdmin().listDecommissionedRegionServers(); return decomServers.size() == 1 && decomServers.get(0).equals(excludeServer.getServerName()); } catch (IOException e) { throw new RuntimeException(e); } }); }</code><technical_language>wait for decom happen start region mover tool finally assert of regions in decom node - assuming region plan created decom completed. Else LGTM</technical_language>

Target:
private void waitForServerDecom(HRegionServer excludeServer) { TEST_UTIL.waitFor(3000, () -> { try { List<ServerName> decomServers = TEST_UTIL.getAdmin().listDecommissionedRegionServers(); return decomServers.size() == 1 && decomServers.get(0).equals(excludeServer.getServerName()); } catch (IOException e) { throw new RuntimeException(e); } }); }
Source:
<code>public void run() { try { libaioFile.write(position, bytes, buffer, this); } catch (IOException e) { <START> onIOError(e, "Failed to write to file", sequentialFile); <END> } }</code><technical_language>hmmm.. nice catch... I other catch failures.. proper fix been: callback.onError(-1, errorMessage); onIOError(e, "Failed write file", sequentialFile);</technical_language>

Target:
public void run() { try { libaioFile.write(position, bytes, buffer, this); } catch (IOException e) { callback.onError(-1, e.getMessage()); onIOError(e, "Failed to write to file", sequentialFile); } }
Source:
<code>public Future<?>[] getAllFutures() { <START> return new Future<?>[]{ <END> keyedStateManagedFuture, keyedStateRawFuture, operatorStateManagedFuture, operatorStateRawFuture, }; }</code><technical_language>return inputChannelStateFuture resultSubpartitionStateFuture</technical_language>

Target:
public Future<?>[] getAllFutures() { return new Future<?>[]{ keyedStateManagedFuture, keyedStateRawFuture, operatorStateManagedFuture, operatorStateRawFuture, inputChannelStateFuture, resultSubpartitionStateFuture }; }
Source:
<code>public void propagatesExceptions() { RuntimeException expected = new RuntimeException("foo"); when(delegate.isLatestRound(ROUND_ONE)).thenThrow(expected); <START> assertThatThrownBy(() -> verifier.isLatestRound(1L)).isEqualTo(expected); <END> }</code><technical_language>nit: ROUND_ONE</technical_language>

Target:
public void propagatesExceptions() { RuntimeException expected = new RuntimeException("foo"); when(delegate.isLatestRound(ROUND_ONE)).thenThrow(expected); assertThatThrownBy(() -> verifier.isLatestRound(ROUND_ONE)).isEqualTo(expected); }
Source:
<code>public <T> void setAttribute(Object object, int attributeId, T value) { ArtifactReadable artifact = getArtifact(object); boolean found = false; for (AttributeReadable<Object> attribute : artifact.getAttributes()) { if (attribute.getGammaId() == attributeId) { getTransaction().setAttributeById(artifact, attribute, value); found = true; break; } } if (!found) { throw new OseeStateException("Attribute Id %d does not exist on Artifact %s", attributeId, object); <START> } <END> }</code><technical_language>add object here?</technical_language>

Target:
public <T> void setAttribute(Object object, int attributeId, T value) { ArtifactReadable artifact = getArtifact(object); boolean found = false; for (AttributeReadable<Object> attribute : artifact.getAttributes()) { if (attribute.getGammaId() == attributeId) { getTransaction().setAttributeById(artifact, attribute, value); found = true; break; } } if (!found) { throw new OseeStateException("Attribute Id %d does not exist on Artifact %s", attributeId, object); } add(object); }
Source:
<code>protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { <START> if (((String) msg).contains("$")) { <END> return decodeMictrackLowAltitudeFlight(channel, remoteAddress, msg); } return decodeMictrackStandard(channel, remoteAddress, msg); }</code><technical_language>I check for MT prefix instead</technical_language>

Target:
protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { String sentence = ((String) msg).trim(); if (sentence.startsWith("MT")) { return decodeStandard(channel, remoteAddress, sentence); } else { return decodeLowAltitude(channel, remoteAddress, sentence); } }
Source:
<code>protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create().ofTypes(ORG_JUNIT_ASSERT) .names("assertEquals", "assertSame", "assertNotSame") .withAnyParameters() .build(), MethodMatchers.create().ofTypes(ORG_JUNIT5_ASSERTIONS) .names("assertArrayEquals", "assertEquals", "assertIterableEquals", "assertLinesMatch", "assertNotEquals", "assertNotSame", "assertSame") .withAnyParameters() .build(), MethodMatchers.create().ofTypes("org.assertj.core.api.Assertions") <START> .names("assertThat") <END> .addParametersMatcher(MethodMatchers.ANY) .build() ); }</code><technical_language>support assertThatObject</technical_language>

Target:
protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create().ofTypes(ORG_JUNIT_ASSERT) .names("assertEquals", "assertSame", "assertNotSame") .withAnyParameters() .build(), MethodMatchers.create().ofTypes(ORG_JUNIT5_ASSERTIONS) .names("assertArrayEquals", "assertEquals", "assertIterableEquals", "assertLinesMatch", "assertNotEquals", "assertNotSame", "assertSame") .withAnyParameters() .build(), MethodMatchers.create().ofTypes("org.assertj.core.api.Assertions") .names("assertThat", "assertThatObject") .addParametersMatcher(MethodMatchers.ANY) .build() ); }
Source:
<code>public void fetch(final FetchState fetchState, final Callback callback) { final Future<?> future = mExecutorService.submit( new Runnable() { @Override public void run() { HttpURLConnection connection = null; Uri uri = fetchState.getUri(); String uriString = uri.toString(); InputStream is; try { connection = createGetConnection(uriString); int redirectCount = 0; while (connection.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { uriString = connection.getHeaderField("Location"); connection.disconnect(); connection = createGetConnection(uriString); ++redirectCount; } <START> if (redirectCount > MAX_REDIRECT_COUNT) { <END> callback.onFailure(new Exception("RedirectCount more than " + MAX_REDIRECT_COUNT)); return; } is = connection.getInputStream(); callback.onResponse(is, -1); } catch (Exception e) { callback.onFailure(e); } finally { if (connection != null) { connection.disconnect(); } } } }); fetchState.getContext().addCallbacks( new BaseProducerContextCallbacks() { @Override public void onCancellationRequested() { if (future.cancel(false)) { callback.onCancellation(); } } }); }</code><technical_language>redirectCount larger MAX_REDIRECT_COUNT? redirectCount is equal MAX_REDIRECT_COUNT, statements while block executed increase</technical_language>

Target:
public void fetch(final FetchState fetchState, final Callback callback) { final Future<?> future = mExecutorService.submit( new Runnable() { @Override public void run() { HttpURLConnection connection = null; Uri uri = fetchState.getUri(); String uriString = uri.toString(); InputStream is; try { connection = createGetConnection(uriString); int redirectCount = 0; while (connection.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { uriString = connection.getHeaderField("Location"); connection.disconnect(); connection = createGetConnection(uriString); ++redirectCount; } if (redirectCount >= MAX_REDIRECT_COUNT) { callback.onFailure(new Exception("RedirectCount more than " + MAX_REDIRECT_COUNT)); return; } is = connection.getInputStream(); callback.onResponse(is, -1); } catch (Exception e) { callback.onFailure(e); } finally { if (connection != null) { connection.disconnect(); } } } }); fetchState.getContext().addCallbacks( new BaseProducerContextCallbacks() { @Override public void onCancellationRequested() { if (future.cancel(false)) { callback.onCancellation(); } } }); }
Source:
<code><START> public EJBReceiver[] getEjbReceivers() { <END> EJBReceiver[] ejbReceivers = null; synchronized (this.ejbReceiverAssociations) { ejbReceivers = this.ejbReceiverAssociations.keySet().toArray(new EJBReceiver[this.ejbReceiverAssociations.size()]); } return ejbReceivers; }</code><technical_language>This API change is allowed</technical_language>

Target:
private EJBReceiver[] getEjbReceivers() { EJBReceiver[] ejbReceivers = null; synchronized (this.ejbReceiverAssociations) { ejbReceivers = this.ejbReceiverAssociations.keySet().toArray(new EJBReceiver[this.ejbReceiverAssociations.size()]); } return ejbReceivers; }
Source:
<code>protected Pair<ATNConfigSet,ATNConfigSet> splitAccordingToSemanticValidity( ATNConfigSet configs, ParserRuleContext outerContext) { ATNConfigSet succeeded = new ATNConfigSet(configs.fullCtx); ATNConfigSet failed = new ATNConfigSet(configs.fullCtx); for (ATNConfig c : configs) { if ( c.semanticContext!=SemanticContext.NONE ) { boolean requiresFullContext = false; <START> boolean predicateEvaluationResult = evalSemanticContext(c.semanticContext, outerContext, c.alt, requiresFullContext); <END> if ( predicateEvaluationResult ) { succeeded.add(c); } else { failed.add(c); } } else { succeeded.add(c); } } return new Pair<ATNConfigSet, ATNConfigSet>(succeeded,failed); }</code><technical_language>This configs.fullCtx instead of assuming false. change in behavior consistent initialization of succeeded failed a lines above</technical_language>

Target:
protected Pair<ATNConfigSet,ATNConfigSet> splitAccordingToSemanticValidity( ATNConfigSet configs, ParserRuleContext outerContext) { ATNConfigSet succeeded = new ATNConfigSet(configs.fullCtx); ATNConfigSet failed = new ATNConfigSet(configs.fullCtx); for (ATNConfig c : configs) { if ( c.semanticContext!=SemanticContext.NONE ) { boolean predicateEvaluationResult = evalSemanticContext(c.semanticContext, outerContext, c.alt, configs.fullCtx); if ( predicateEvaluationResult ) { succeeded.add(c); } else { failed.add(c); } } else { succeeded.add(c); } } return new Pair<ATNConfigSet, ATNConfigSet>(succeeded,failed); }
Source:
<code>private void onTest() { if (!validateConnectionSettings()) { getTestResult().setEntity(ConstantsManager.getInstance().getConstants().testFailedInsufficientParams()); return; } flush(); startProgress(null); if (provider.getUrl().startsWith(Uri.SCHEME_HTTPS)) { AsyncDataProvider.getInstance().getProviderCertificateChain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { boolean ok = false; certificate = null; if (returnValue != null) { List<CertificateInfo> certs = (List<CertificateInfo>) returnValue; <START> if (certs.size() > 0) { <END> certificate = certs.get(0).getPayload(); ConfirmationModel confirmationModel = getImportCertificateConfirmationModel(certs.get(0)); sourceListModel.setConfirmWindow(confirmationModel); ok = true; } } if (!ok) { stopProgress(); getTestResult().setEntity(ConstantsManager.getInstance() .getConstants() .testFailedUnknownErrorMsg()); } } }), provider); } else { testProviderConnectivity(); } }</code><technical_language>'proper' java test empty list/collections is: if (!certs.isEmpty()) {</technical_language>

Target:
private void onTest() { if (!validateConnectionSettings()) { getTestResult().setEntity(ConstantsManager.getInstance().getConstants().testFailedInsufficientParams()); return; } flush(); startProgress(null); if (provider.getUrl().startsWith(Uri.SCHEME_HTTPS)) { AsyncDataProvider.getInstance().getProviderCertificateChain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { boolean ok = false; certificate = null; if (returnValue != null) { List<CertificateInfo> certs = (List<CertificateInfo>) returnValue; if (!certs.isEmpty()) { certificate = certs.get(certs.size() - 1).getPayload(); ConfirmationModel confirmationModel = getImportCertificateConfirmationModel(certs.get(0)); sourceListModel.setConfirmWindow(confirmationModel); ok = true; } } if (!ok) { stopProgress(); getTestResult().setEntity(ConstantsManager.getInstance() .getConstants() .testFailedUnknownErrorMsg()); } } }), provider); } else { testProviderConnectivity(); } }
Source:
<code>public void matchRequiredVersions_shouldAllowRequiredVersionWithPlus() { String openmrsVersion = "1.4.3"; String requiredOpenmrsVersion = "1.4.2+"; <START> Assert.assertTrue(ModuleUtil.matchRequiredVersions(openmrsVersion, requiredOpenmrsVersion)); <END> }</code><technical_language>Please test edges. in this case values as: "1.4.1", "1.4.1.99", "1.4.2", "1.4.3", "1.5.0", ... etc. need reassign openmrsVersion time then, good like: java String requiredOpenmrsVersion = "1.4.2+"; Assert.assertFalse(ModuleUtil.matchRequiredVersions("1.4.1", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.2", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.3", requiredOpenmrsVersion)); ..</technical_language>

Target:
public void matchRequiredVersions_shouldAllowRequiredVersionWithPlus() { String requiredOpenmrsVersion = "1.4.2+"; Assert.assertFalse(ModuleUtil.matchRequiredVersions("1.4.1", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.2", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.3", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.2.99", requiredOpenmrsVersion)); Assert.assertFalse(ModuleUtil.matchRequiredVersions("1.4.1.99", requiredOpenmrsVersion)); Assert.assertTrue(ModuleUtil.matchRequiredVersions("1.4.99", requiredOpenmrsVersion)); Assert.assertFalse(ModuleUtil.matchRequiredVersions("1.5.1", requiredOpenmrsVersion)); }
Source:
<code>public void testReadAvro() throws IOException { Path sequenceFilePath = new Path(new File(mTempDir.getRoot(), "output.seq").getPath()); writeSequenceFile(sequenceFilePath, AvroKey.class, AvroValue.class, Schema.create(Schema.Type.STRING), Schema.create(Schema.Type.INT), new AvroKey<CharSequence>("one"), new AvroValue<>(1), new AvroKey<CharSequence>("two"), new AvroValue<>(2)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); AvroSequenceFile.Reader.Options options = new AvroSequenceFile.Reader.Options().withFileSystem(fs) .withInputPath(sequenceFilePath).withKeySchema(Schema.create(Schema.Type.STRING)) .withValueSchema(Schema.create(Schema.Type.INT)).withConfiguration(conf); SequenceFile.Reader reader = new AvroSequenceFile.Reader(options); AvroKey<CharSequence> key = new AvroKey<>(); AvroValue<Integer> value = new AvroValue<>(); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("one", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(1, value.datum().intValue()); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("two", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(2, value.datum().intValue()); assertNull("Should be no more records.", reader.next(key)); <START> reader.close(); <END> }</code><technical_language>a try-with-resource pattern here</technical_language>

Target:
public void testReadAvro() throws IOException { Path sequenceFilePath = new Path(new File(mTempDir.getRoot(), "output.seq").getPath()); writeSequenceFile(sequenceFilePath, AvroKey.class, AvroValue.class, Schema.create(Schema.Type.STRING), Schema.create(Schema.Type.INT), new AvroKey<CharSequence>("one"), new AvroValue<>(1), new AvroKey<CharSequence>("two"), new AvroValue<>(2)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); AvroSequenceFile.Reader.Options options = new AvroSequenceFile.Reader.Options().withFileSystem(fs) .withInputPath(sequenceFilePath).withKeySchema(Schema.create(Schema.Type.STRING)) .withValueSchema(Schema.create(Schema.Type.INT)).withConfiguration(conf); try (SequenceFile.Reader reader = new AvroSequenceFile.Reader(options)) { AvroKey<CharSequence> key = new AvroKey<>(); AvroValue<Integer> value = new AvroValue<>(); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("one", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(1, value.datum().intValue()); key = (AvroKey<CharSequence>) reader.next(key); assertNotNull(key); assertEquals("two", key.datum().toString()); value = (AvroValue<Integer>) reader.getCurrentValue(value); assertNotNull(value); assertEquals(2, value.datum().intValue()); assertNull("Should be no more records.", reader.next(key)); } }
Source:
<code>public static void calculateKMap() throws Exception { String projectId = "your-project-id"; String datasetId = "your-bigquery-dataset-id"; String tableId = "your-bigquery-table-id"; String topicId = "pub-sub-topic"; String subscriptionId = "pub-sub-subscription"; <START> List<String> quasiIdColumns = Arrays.asList("age", "gender"); <END> List<String> infoTypeNames = Arrays.asList("AGE", "GENDER"); calculateKMap( projectId, datasetId, tableId, topicId, subscriptionId, quasiIdColumns, infoTypeNames); }</code><technical_language>quasiIdColumns infoTypeNames inlined</technical_language>

Target:
public static void calculateKMap() throws Exception { String projectId = "your-project-id"; String datasetId = "your-bigquery-dataset-id"; String tableId = "your-bigquery-table-id"; String topicId = "pub-sub-topic"; String subscriptionId = "pub-sub-subscription"; calculateKMap(projectId, datasetId, tableId, topicId, subscriptionId); }
Source:
<code>private static Exception extractAcceptedDeploymentException(Class<? extends Exception> acceptedDeploymentExceptionType, Throwable exception) { if ( acceptedDeploymentExceptionType.isAssignableFrom( exception.getClass() ) ) { return (Exception) exception; } if ( exception instanceof InvocationTargetException ) { Exception acceptedDeploymentException = extractAcceptedDeploymentException( acceptedDeploymentExceptionType, ( (InvocationTargetException) exception ).getTargetException() ); if ( acceptedDeploymentException != null ) { return acceptedDeploymentException; } } if ( exception.getCause() != null ) { <START> Exception acceptedDeploymentException = extractAcceptedDeploymentException( acceptedDeploymentExceptionType, exception.getCause() ); <END> if ( acceptedDeploymentException != null ) { return acceptedDeploymentException; } } return null; }</code><technical_language>Agreed a bit odd, in a real world situation deployment exceptions catchable java code, matter if this data is in exception message a proper chained exception user perspective. Thanks for this promptly btw! working collecting full set of classes effected now</technical_language>

Target:
private static Exception extractAcceptedDeploymentException(Class<? extends Exception> acceptedDeploymentExceptionType, Throwable exception) { if ( acceptedDeploymentExceptionType.isAssignableFrom( exception.getClass() ) ) { return (Exception) exception; } if ( exception instanceof InvocationTargetException ) { Exception acceptedDeploymentException = extractAcceptedDeploymentException( acceptedDeploymentExceptionType, ( (InvocationTargetException) exception ).getTargetException() ); if ( acceptedDeploymentException != null ) { return acceptedDeploymentException; } } if ( exception.getCause() != null ) { Exception acceptedDeploymentException = extractAcceptedDeploymentException( acceptedDeploymentExceptionType, exception.getCause() ); if ( acceptedDeploymentException != null ) { return acceptedDeploymentException; } } for ( Throwable suppressedException : exception.getSuppressed() ) { Exception acceptedDeploymentException = extractAcceptedDeploymentException( acceptedDeploymentExceptionType, suppressedException ); if ( acceptedDeploymentException != null ) { return acceptedDeploymentException; } } if ( exception.getMessage().contains( acceptedDeploymentExceptionType.getName() ) ) { try { Constructor<? extends Exception> exceptionConstructor = acceptedDeploymentExceptionType.getConstructor( String.class ); return exceptionConstructor.newInstance( "Forged exception" ); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { } } return null; }
Source:
<code><START> static String findOuiByMacAddressIfPossible(String mac) { <END> return vmMacAddressOUI.entrySet().stream() .filter(entry -> mac.startsWith(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining()); }</code><technical_language>this public private</technical_language>

Target:
public static String findOuiByMacAddressIfPossible(String mac) { return vmMacAddressOUI.entrySet().stream() .filter(entry -> mac.startsWith(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining()); }
Source:
<code>public static boolean isDisplayTypeSupported(int osId, DisplayType defaultDisplayType, List<String> reasons, Version clusterVersion) { boolean result = VmValidationUtils.isDisplayTypeSupported(osId, clusterVersion, defaultDisplayType); if (!result) { <START> reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS.toString()); <END> } return result; }</code><technical_language>enum name() instead of toString()</technical_language>

Target:
public static boolean isDisplayTypeSupported(int osId, DisplayType defaultDisplayType, List<String> reasons, Version clusterVersion) { boolean result = VmValidationUtils.isDisplayTypeSupported(osId, clusterVersion, defaultDisplayType); if (!result) { reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS.name()); } return result; }
Source:
<code>public CertificateClientBuilder credential(TokenCredential credential) { <START> Objects.requireNonNull(credential, "Token credential cannot be null."); <END> this.credential = credential; return this; }</code><technical_language>suggestion Objects.requireNonNull(credential, "'credential' null.");</technical_language>

Target:
public CertificateClientBuilder credential(TokenCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); this.credential = credential; return this; }
Source:
<code>private void persistToFile() throws IOException { Assert.isTrue(resourceProvider.hasOutput()); XStream xs = getConfiguredXStreamWithContext(new GeoWebCacheXStream(), Context.PERSIST); <START> OutputStreamWriter writer = null; <END> try { try { writer = new OutputStreamWriter(resourceProvider.out(), "UTF-8"); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); throw new IOException(uee.getMessage()); } catch (FileNotFoundException fnfe) { throw fnfe; } try { String currentSchemaVersion = getCurrentSchemaVersion(); gwcConfig.setVersion(currentSchemaVersion); writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); xs.toXML(gwcConfig, writer); } catch (IOException e) { throw (IOException) new IOException("Error writing to " + resourceProvider.getId() + ": " + e.getMessage()).initCause(e); } } finally { IOUtils.closeQuietly(writer); } log.info("Wrote configuration to " + resourceProvider.getId()); }</code><technical_language>a try-with-resources</technical_language>

Target:
private void persistToFile() throws IOException { Assert.isTrue(resourceProvider.hasOutput()); XStream xs = getConfiguredXStreamWithContext(new GeoWebCacheXStream(), Context.PERSIST); try (OutputStreamWriter writer = new OutputStreamWriter(resourceProvider.out(), "UTF-8")) { String currentSchemaVersion = getCurrentSchemaVersion(); gwcConfig.setVersion(currentSchemaVersion); writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); xs.toXML(gwcConfig, writer); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); throw new IOException(uee.getMessage()); } catch (FileNotFoundException fnfe) { throw fnfe; } catch (IOException e) { throw (IOException) new IOException("Error writing to " + resourceProvider.getId() + ": " + e.getMessage()).initCause(e); } log.info("Wrote configuration to " + resourceProvider.getId()); }
Source:
<code>public void testBlockUseHostCpuWithPPCArch() { mockConfig(); AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v3_3); doReturn(Collections.<DiskImageBase> emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); Cluster cluster = createPpcCluster(); when(clusterDao.get(any(Guid.class))).thenReturn(cluster); <START> SimpleDependencyInjector.getInstance().bind(DbFacade.class, dbFacade); <END> doReturn(clusterDao).when(dbFacade).getClusterDao(); doReturn(true).when(cmd).areParametersLegal(Collections.<String> emptyList()); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); mockOsRepository(); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(2); ValidateTestUtils.runAndAssertValidateFailure (cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }</code><technical_language>This is called test in initTest()</technical_language>

Target:
public void testBlockUseHostCpuWithPPCArch() { mockConfig(); AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.<DiskImageBase> emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); Cluster cluster = createPpcCluster(); when(clusterDao.get(any(Guid.class))).thenReturn(cluster); doReturn(clusterDao).when(dbFacade).getClusterDao(); doReturn(true).when(cmd).areParametersLegal(Collections.<String> emptyList()); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(2); ValidateTestUtils.runAndAssertValidateFailure (cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }
Source:
<code>public void testWriteLargerThanThreshold() { byte[] largeRecord = randomString.substring(0, 2 * THRESHOLD).getBytes(); byte[] largeRecordFirstHalf = randomString.substring(0, THRESHOLD).getBytes(); byte[] largeRecordSecondHalf = randomString.substring(THRESHOLD, 2 * THRESHOLD).getBytes(); byte[] compressB = randomString.substring(0, THRESHOLD / 2).getBytes(); <START> doReturn(compressB).when(mockCompression).compress(largeRecordFirstHalf); doReturn(compressB).when(mockCompression).compress(largeRecordSecondHalf); <END> azureBlobOutputStream.write(largeRecord, 0, 2 * THRESHOLD); azureBlobOutputStream.close(); verify(mockCompression).compress(largeRecordFirstHalf); verify(mockCompression).compress(largeRecordSecondHalf); ArgumentCaptor<Flux> argument = ArgumentCaptor.forClass(Flux.class); verify(mockBlobAsyncClient).stageBlock(eq(blockIdEncoded(0)), argument.capture(), eq((long) compressB.length)); verify(mockBlobAsyncClient).stageBlock(eq(blockIdEncoded(1)), argument.capture(), eq((long) compressB.length)); argument.getAllValues().forEach(flux -> { Assert.assertEquals(ByteBuffer.wrap(compressB), flux.blockFirst()); }); verify(mockMetrics).updateWriteByteMetrics(2 * THRESHOLD); verify(mockMetrics, times(2)).updateAzureUploadMetrics(); }</code><technical_language>Please consider returning "compressed bytes" for half. test more complete ensure correct bytes for half</technical_language>

Target:
public void testWriteLargerThanThreshold() { byte[] largeRecord = RANDOM_STRING.substring(0, 2 * THRESHOLD).getBytes(); byte[] largeRecordFirstHalf = RANDOM_STRING.substring(0, THRESHOLD).getBytes(); byte[] largeRecordSecondHalf = RANDOM_STRING.substring(THRESHOLD, 2 * THRESHOLD).getBytes(); byte[] compressB1 = RANDOM_STRING.substring(0, THRESHOLD / 2).getBytes(); byte[] compressB2 = RANDOM_STRING.substring(THRESHOLD / 2, THRESHOLD).getBytes(); doReturn(compressB1).when(mockCompression).compress(largeRecordFirstHalf); doReturn(compressB2).when(mockCompression).compress(largeRecordSecondHalf); azureBlobOutputStream.write(largeRecord, 0, 2 * THRESHOLD); azureBlobOutputStream.close(); verify(mockCompression).compress(largeRecordFirstHalf); verify(mockCompression).compress(largeRecordSecondHalf); ArgumentCaptor<Flux> argument0 = ArgumentCaptor.forClass(Flux.class); ArgumentCaptor<Flux> argument1 = ArgumentCaptor.forClass(Flux.class); verify(mockBlobAsyncClient).stageBlock(eq(blockIdEncoded(0)), argument0.capture(), eq((long) compressB1.length)); verify(mockBlobAsyncClient).stageBlock(eq(blockIdEncoded(1)), argument1.capture(), eq((long) compressB2.length)); Assert.assertEquals(ByteBuffer.wrap(compressB1), argument0.getAllValues().get(0).blockFirst()); Assert.assertEquals(ByteBuffer.wrap(compressB2), argument1.getAllValues().get(0).blockFirst()); verify(mockMetrics).updateWriteByteMetrics(2 * THRESHOLD); verify(mockMetrics, times(2)).updateAzureUploadMetrics(); }
Source:
<code>public static GetTokensByCodeResponse tokenByInvalidCode(ClientInterface client, RegisterSiteResponse site, String userId, String userSecret, String nonce) { final String state = CoreUtils.secureRandomString(); final String code = CoreUtils.secureRandomString(); String testOxdId = site.getOxdId(); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(testOxdId); params.setCode(code); params.setState(state); GetTokensByCodeResponse resp = null; try { resp = client.getTokenByCode(Tester.getAuthorization(), params); <START> assertTrue(false); <END> } catch (Exception ex) { assertTrue(true); } return resp; }</code><technical_language>assert 400, "bad_request", "'code' is invalid." added above</technical_language>

Target:
public static GetTokensByCodeResponse tokenByInvalidCode(ClientInterface client, RegisterSiteResponse site, String userId, String userSecret, String nonce) { final String state = CoreUtils.secureRandomString(); codeRequest(client, site.getOxdId(), userId, userSecret, state, nonce); final String code = CoreUtils.secureRandomString(); String testOxdId = site.getOxdId(); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(testOxdId); params.setCode(code); params.setState(state); GetTokensByCodeResponse resp = null; try { resp = client.getTokenByCode(Tester.getAuthorization(), params); assertNotNull(resp); notEmpty(resp.getAccessToken()); notEmpty(resp.getIdToken()); notEmpty(resp.getRefreshToken()); } catch (BadRequestException ex) { assertEquals(ex.getMessage(), "HTTP 400 Bad Request"); } return resp; }
Source:
<code>public static ControllerMethod instanceFor(Class<?> type, Method method) { <START> CDIProxies.extractRawTypeIfPossible(type); <END> return new DefaultControllerMethod(new DefaultBeanClass(type), method); }</code><technical_language>tabs instead of spaces</technical_language>

Target:
public static ControllerMethod instanceFor(Class<?> type, Method method) { type = extractRawTypeIfPossible(type); return new DefaultControllerMethod(new DefaultBeanClass(type), method); }
Source:
<code>public void run() { <START> if (historyPage.getCurrentRepo() == null) <END> return; dialog = new GitHistoryRefFilterConfigurationDialog( historyPage.getSite().getWorkbenchWindow().getShell(), historyPage.getCurrentRepo(), historyPage.helper); if (dialog.open() == Window.OK) { historyPage.refresh(historyPage.selectedCommit()); } }</code><technical_language>missing braces</technical_language>

Target:
public void run() { if (historyPage.getCurrentRepo() == null) { return; } dialog = new GitHistoryRefFilterConfigurationDialog( historyPage.getSite().getWorkbenchWindow().getShell(), historyPage.getCurrentRepo(), historyPage.helper); if (dialog.open() == Window.OK) { historyPage.refresh(historyPage.selectedCommit()); } }
Source:
<code><START> private List<Integer> getIndices(Shape rect) { <END> List<Integer> indices = new ArrayList<>(); double verticalMidpoint = bounds.getX() + (bounds.getWidth() / 2); double horizontalMid = bounds.getY() + (bounds.getHeight() / 2); boolean topQuadrant = rect.getY() < horizontalMid; boolean bottomQuadrant = rect.getY() > horizontalMid || rect.getY() + rect.getHeight() > horizontalMid; if (rect.getX() < verticalMidpoint) { if (topQuadrant) { indices.add(1); } if (bottomQuadrant) { indices.add(2); } } if (rect.getX() > verticalMidpoint || rect.getX() + rect.getWidth() > verticalMidpoint) { if (topQuadrant) { indices.add(0); } if (bottomQuadrant) { indices.add(3); } } return indices; }</code><technical_language>This method is long, split smaller pieces? < layout, organisation</technical_language>

Target:
private List<Integer> getIndices(Shape rect) { List<Integer> indices = new ArrayList<>(); double verticalMidpoint = bounds.getX() + (bounds.getWidth() / 2); double horizontalMid = bounds.getY() + (bounds.getHeight() / 2); checkLeftQuadrants(indices, rect, verticalMidpoint, horizontalMid); checkRightQuadrants(indices, rect, verticalMidpoint, horizontalMid); return indices; }
Source:
<code>public String newDocumentId( String parentId, Name newDocumentName, Name newDocumentPrimaryType ) { StringBuilder documentIdBuilder = new StringBuilder(parentId); if (!parentId.endsWith(DELIMITER)) { documentIdBuilder.append(DELIMITER); } if (!StringUtil.isBlank(newDocumentName.getNamespaceUri())) { <START> documentIdBuilder.append(newDocumentName.getNamespaceUri()); <END> } documentIdBuilder.append(newDocumentName.getLocalName()); return documentIdBuilder.toString(); }</code><technical_language>Is this line adding namespace **URI** id? While is more stable, wondering if string form of name (produced namespace registry, wrap URI in curly brackets) namespace separated name (and more easily parsed, if connector wants do this). Also, IDs properly handled creating files/folders</technical_language>

Target:
public String newDocumentId( String parentId, Name newDocumentName, Name newDocumentPrimaryType ) { StringBuilder documentIdBuilder = new StringBuilder(parentId); if (!parentId.endsWith(DELIMITER)) { documentIdBuilder.append(DELIMITER); } if (!StringUtil.isBlank(newDocumentName.getNamespaceUri())) { getLogger().warn(JcrI18n.fileConnectorNamespaceIgnored, getSourceName(), newDocumentName.getNamespaceUri()); } documentIdBuilder.append(newDocumentName.getLocalName()); return documentIdBuilder.toString(); }
Source:
<code>public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); <START> OvfDataUpdater.getInstance().InitOvfDataUpdater(); <END> log.infoFormat("OvfDataUpdater: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); }</code><technical_language>hmm, need C# coding style here. initXXX InitXXXX</technical_language>

Target:
public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); OvfDataUpdater.getInstance().initOvfDataUpdater(); log.infoFormat("OvfDataUpdater: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); }
Source:
<code>private static Point tileXYToLatitudeLongitude(int tileX, int tileY, int zoomLevel) { <START> double mapSize = mapSize(zoomLevel); <END> double x = (clip(tileX * TILE_PIXELS, 0, mapSize - 1) / mapSize) - 0.5; double y = 0.5 - (clip(tileY * TILE_PIXELS, 0, mapSize - 1) / mapSize); double latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI; double longitude = 360 * x; return new Point(longitude, latitude); }</code><technical_language>int mapSize</technical_language>

Target:
private static Point tileXYToLatitudeLongitude(int tileX, int tileY, int zoomLevel) { int mapSize = mapSize(zoomLevel); double x = (clip(tileX * TILE_PIXELS, 0, mapSize - 1) / mapSize) - 0.5; double y = 0.5 - (clip(tileY * TILE_PIXELS, 0, mapSize - 1) / mapSize); double latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI; double longitude = 360 * x; return new Point(longitude, latitude); }
Source:
<code>public String generate() { <START> final Random random = ThreadLocalRandom.current(); <END> final ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES * 2); buffer.putLong(random.nextLong()); buffer.putLong(random.nextLong()); final byte[] bytes = buffer.array(); return "R" + encoder.encodeToString(bytes).replace("=", "").substring(1); }</code><technical_language>return new UUID(random.nextLong(), random.nextLong()</technical_language>

Target:
public String generate() { final byte[] bytes = new byte[LENGTH]; ThreadLocalRandom.current().nextBytes(bytes); final byte[] encoded = encoder.encode(bytes); encoded[0] = 'R'; return new String(encoded, US_ASCII); }
Source:
<code>public Iterable<PConstraint> getPConstraintTraces(PConstraint derivative) { if (child != null){ <START> Iterable<PConstraint> derivatives = child.getPConstraintTraces(derivative); <END> return Iterables.concat(Iterables.transform(derivatives, new Function<PConstraint, Iterable<PConstraint>>() { @Override public Iterable<PConstraint> apply(PConstraint input) { Iterable<PConstraint> pConstraintTraces = traces.get(input); return pConstraintTraces == null ? Collections.<PConstraint>emptyList() : pConstraintTraces; } })); } return traces.get(derivative); }</code><technical_language>TODO rename clarify: 'derivatives' direct derivatives of this trace, while 'derivate' is ultimate derivative</technical_language>

Target:
public Iterable<PConstraint> getPConstraintTraces(PConstraint derivative) { if (child != null){ Iterable<PConstraint> directDerivatives = child.getPConstraintTraces(derivative); return Sets.newHashSet(Iterables.concat(Iterables.transform(directDerivatives, new Function<PConstraint, Iterable<PConstraint>>() { @Override public Iterable<PConstraint> apply(PConstraint input) { Iterable<PConstraint> pConstraintTraces = traces.get(input); return pConstraintTraces == null ? Collections.<PConstraint>emptyList() : pConstraintTraces; } }))); } return traces.get(derivative); }