auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public OpenSshCertificate loadCertificate(SessionContext session, String keyType) throws IOException, GeneralSecurityException { return StreamSupport.stream(loadCertificates(session).spliterator(), false) <START> .filter(pubKey -> pubKey.getKeyType().equals(keyType)) <END> .findFirst().orElse(null); }</code><technical_language>Let;s use: filter(pubKey -> Objects.equals(keyType, pubKey.getKeyType()))</technical_language>

Target:
public OpenSshCertificate loadCertificate(SessionContext session, String keyType) throws IOException, GeneralSecurityException { return StreamSupport.stream(loadCertificates(session).spliterator(), false) .filter(pubKey -> Objects.equals(pubKey.getKeyType(), keyType)) .findFirst().orElse(null); }
Source:
<code>@Test public void invalidClientAuthEvents() throws Throwable { server.enqueue(new MockResponse().setBody("abc")); clientCert = new HeldCertificate.Builder() .signedBy(clientIntermediateCa) .serialNumber(4L) .commonName("Jethro Willis") <START> .addSubjectAlternativeName("jethrowillis.com") <END> .validityInterval(1, 2) .build(); OkHttpClient client = buildClient(clientCert, clientIntermediateCa.certificate()); RecordingEventListener listener = new RecordingEventListener(); client = client.newBuilder() .eventListener(listener) .build(); SSLSocketFactory socketFactory = buildServerSslSocketFactory(); server.useHttps(socketFactory, false); server.requireClientAuth(); Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); try { call.execute(); fail(); } catch (IOException expected) { } assertEquals(asList( "CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectFailed", "CallFailed" ), listener.recordedEventTypes()); }</code><technical_language>Is this a cultural reference? I it</technical_language>

Target:
@Test public void invalidClientAuthEvents() throws Throwable { server.enqueue(new MockResponse().setBody("abc")); clientCert = new HeldCertificate.Builder() .signedBy(clientIntermediateCa) .serialNumber(4L) .commonName("Jethro Willis") .addSubjectAlternativeName("jethrowillis.com") .validityInterval(1, 2) .build(); OkHttpClient client = buildClient(clientCert, clientIntermediateCa.certificate()); RecordingEventListener listener = new RecordingEventListener(); client = client.newBuilder() .eventListener(listener) .build(); SSLSocketFactory socketFactory = buildServerSslSocketFactory(); server.useHttps(socketFactory, false); server.requireClientAuth(); Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); try { call.execute(); fail(); } catch (IOException expected) { } List<String> recordedEventTypes = listener.recordedEventTypes(); assertThat(recordedEventTypes).startsWith( "CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart"); assertThat(recordedEventTypes).endsWith("CallFailed"); }
Source:
<code>private void generateClassEquals(String className, StructSpec struct, boolean elementKeysAreEqual) { buffer.printf("@Override%n"); buffer.printf("public boolean %s(Object obj) {%n", elementKeysAreEqual ? "elementKeysAreEqual" : "equals"); buffer.incrementIndent(); buffer.printf("if (!(obj instanceof %s)) return false;%n", className); if (!struct.fields().isEmpty()) { buffer.printf("%s other = (%s) obj;%n", className, className); for (FieldSpec field : struct.fields()) { <START> if ((!elementKeysAreEqual) || field.mapKey()) { <END> generateFieldEquals(field); } } } buffer.printf("return true;%n"); buffer.decrementIndent(); buffer.printf("}%n"); }</code><technical_language>nit: unneeded parenthesis</technical_language>

Target:
private void generateClassEquals(String className, StructSpec struct, boolean elementKeysAreEqual) { buffer.printf("@Override%n"); buffer.printf("public boolean %s(Object obj) {%n", elementKeysAreEqual ? "elementKeysAreEqual" : "equals"); buffer.incrementIndent(); buffer.printf("if (!(obj instanceof %s)) return false;%n", className); if (!struct.fields().isEmpty()) { buffer.printf("%s other = (%s) obj;%n", className, className); for (FieldSpec field : struct.fields()) { if (!elementKeysAreEqual || field.mapKey()) { generateFieldEquals(field); } } } buffer.printf("return true;%n"); buffer.decrementIndent(); buffer.printf("}%n"); }
Source:
<code>protected void doWakeUp() { IJobManager <START> jobManager = <END> Job.getJobManager(); jobManager.wakeUp(TestJob.FAMILY_TEST_JOB); }</code><technical_language>replace Platform Job? below</technical_language>

Target:
protected void doWakeUp() { Job.getJobManager().wakeUp(TestJob.FAMILY_TEST_JOB); }
Source:
<code>protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); try { outState.putInt("tab", mPager.getCurrentItem()); }catch (NoClassDefFoundError e){ <START> Log.w(TAG, "Busgnag is unsupported when building from Eclipse", e); <END> } }</code><technical_language>a error message. Eclipse long deprecated exception generated current item a non-existent bad pager control</technical_language>

Target:
protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); try { outState.putInt("tab", mPager.getCurrentItem()); }catch (NoClassDefFoundError e){ Log.w(TAG, "Failing to get current page "); e.printStackTrace(); } }
Source:
<code>public void testImport() { testModules( "import name from 'other'; use(name);", LINE_JOINER.join("goog.require('module$other');", "use(module$other.default);")); testModules("import {n as name} from 'other';", "goog.require('module$other');"); testModules( "import x, {f as foo, b as bar} from 'other'; use(x);", LINE_JOINER.join("goog.require('module$other');", "use(module$other.default);")); testModules( "import {default as name} from 'other'; use(name);", <START> LINE_JOINER.join("goog.require('module$other');", "use(module$other.default);")); <END> }</code><technical_language>purpose of line joiner is put strings line reads more naturally. do put line in string</technical_language>

Target:
public void testImport() { testModules( "import name from 'other'; use(name);", "goog.require('module$other'); use(module$other.default);"); testModules("import {n as name} from 'other';", "goog.require('module$other');"); testModules( "import x, {f as foo, b as bar} from 'other'; use(x);", "goog.require('module$other'); use(module$other.default);"); testModules( "import {default as name} from 'other'; use(name);", "goog.require('module$other'); use(module$other.default);"); testModules( "import {class as name} from 'other'; use(name);", "goog.require('module$other'); use(module$other.class);"); }
Source:
<code><START> public CompletableFuture<Void> initiate() { <END> ReadLastConfirmedOp rlcop = new ReadLastConfirmedOp(lh, clientCtx.getBookieClient(), lh.getCurrentEnsemble(), new ReadLastConfirmedOp.LastConfirmedDataCallback() { public void readLastConfirmedDataComplete(int rc, RecoveryData data) { if (rc == BKException.Code.OK) { synchronized (lh) { lh.lastAddPushed = lh.lastAddConfirmed = data.getLastAddConfirmed(); lh.length = data.getLength(); lh.pendingAddsSequenceHead = lh.lastAddConfirmed; startEntryToRead = endEntryToRead = lh.lastAddConfirmed; } metadataForRecovery = new LedgerMetadata(lh.getLedgerMetadata()); doRecoveryRead(); } else if (rc == BKException.Code.UnauthorizedAccessException) { submitCallback(rc); } else { submitCallback(BKException.Code.ReadException); } } }); rlcop.initiateWithFencing(); return promise; }</code><technical_language>return CompletableFuture<LedgerHandle>? is easier chain operations</technical_language>

Target:
public CompletableFuture<LedgerHandle> initiate() { ReadLastConfirmedOp rlcop = new ReadLastConfirmedOp(lh, clientCtx.getBookieClient(), lh.getCurrentEnsemble(), new ReadLastConfirmedOp.LastConfirmedDataCallback() { public void readLastConfirmedDataComplete(int rc, RecoveryData data) { if (rc == BKException.Code.OK) { synchronized (lh) { lh.lastAddPushed = lh.lastAddConfirmed = data.getLastAddConfirmed(); lh.length = data.getLength(); lh.pendingAddsSequenceHead = lh.lastAddConfirmed; startEntryToRead = endEntryToRead = lh.lastAddConfirmed; } metadataForRecovery = new LedgerMetadata(lh.getLedgerMetadata()); doRecoveryRead(); } else if (rc == BKException.Code.UnauthorizedAccessException) { submitCallback(rc); } else { submitCallback(BKException.Code.ReadException); } } }); rlcop.initiateWithFencing(); return promise; }
Source:
<code>private String buildCustomizedRelation(final boolean caseSensitive, IConditionFieldAutoCompleter conditionFieldAC, IConditionValueAutoCompleter conditionValueAC, String fieldName, SyntaxObject previous, SyntaxObjectType prevType) { String customizedRelation; if (prevType != SyntaxObjectType.CONDITION_RELATION) { customizedRelation = "="; } else { customizedRelation = previous.getBody(); <START> } <END> if(conditionValueAC == null && ("".equals(fieldName) || String.class.equals(conditionFieldAC.getDbFieldType(fieldName)))) { if ("=".equals(customizedRelation)) { customizedRelation = BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive); } else if ("!=".equals(customizedRelation)) { customizedRelation = "NOT " + BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive); } } return customizedRelation; }</code><technical_language>This improved to: String customizedRelation= "="; // free text of default search object if (prevType == SyntaxObjectType.CONDITION_RELATION) { customizedRelation = previous.getBody(); } do think</technical_language>

Target:
private String buildCustomizedRelation(final boolean caseSensitive, IConditionFieldAutoCompleter conditionFieldAC, IConditionValueAutoCompleter conditionValueAC, String fieldName, SyntaxObject previous, SyntaxObjectType prevType) { String customizedRelation = "="; if (prevType == SyntaxObjectType.CONDITION_RELATION) { customizedRelation = previous.getBody(); } if(conditionValueAC == null && ("".equals(fieldName) || String.class.equals(conditionFieldAC.getDbFieldType(fieldName)))) { if ("=".equals(customizedRelation)) { customizedRelation = BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive); } else if ("!=".equals(customizedRelation)) { customizedRelation = "NOT " + BaseConditionFieldAutoCompleter.getLikeSyntax(caseSensitive); } } return customizedRelation; }
Source:
<code>private static void executeCopyTask(TableReference srcTable, TableReference dstTable, CopyStats stats, CopyTask task, MutableRange range) throws InterruptedException { <START> final RangeRequest request = range.getRangeRequest(); <END> long startTime = System.currentTimeMillis(); PartialCopyStats partialStats = task.call(request, range); stats.rowsCopied.addAndGet(partialStats.rowsCopied); stats.cellsCopied.addAndGet(partialStats.cellsCopied); log.info("Copied rows, cells from to in ms.", partialStats.rowsCopied, partialStats.cellsCopied, srcTable, dstTable, System.currentTimeMillis() - startTime); }</code><technical_language>nit: This needs final more, "magic" in task.call()</technical_language>

Target:
private static void executeCopyTask(TableReference srcTable, TableReference dstTable, CopyStats stats, CopyTask task, MutableRange range) throws InterruptedException { long startTime = System.currentTimeMillis(); PartialCopyStats partialStats = task.call(range.getRangeRequest(), range); stats.rowsCopied.addAndGet(partialStats.rowsCopied); stats.cellsCopied.addAndGet(partialStats.cellsCopied); log.info("Copied rows, cells from to in ms.", SafeArg.of("rowsCopied", partialStats.rowsCopied), SafeArg.of("cellsCopied", partialStats.cellsCopied), LoggingArgs.tableRef("srcTable", srcTable), LoggingArgs.tableRef("dstTable", dstTable), SafeArg.of("timeTaken", System.currentTimeMillis() - startTime)); }
Source:
<code>private Boolean shouldLogMultiPart() { <START> return parseBoolean(System.getProperty(CLIENT_LOGGING_LOG_MULTIPART, "false")); <END> }</code><technical_language>if interested is a Boolean.getBoolean(yourSystemProperty)</technical_language>

Target:
private Boolean shouldLogMultiPart() { return Boolean.getBoolean(CLIENT_LOGGING_LOG_MULTIPART); }
Source:
<code>public Object[][] createData() { if(System.getProperty("os.name").contains("indows")) return new Object[][] { { "normal" } }; else <START> return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, { "path/foo" }, { "colon:" }, <END> { "asteri*k" }, { "quote\"" }, { "{great<r}" }, { "lesst>en" }, { "p|pe" } }; }</code><technical_language>this break Windows, is this fixed instead</technical_language>

Target:
public Object[][] createData() { if (System.getProperty("os.name").toLowerCase().contains("windows")) { return new Object[][] { { "normal" }, { "sp ace" } }; } else { return new Object[][] { { "normal" }, { "sp ace" }, { "qu?stion" }, { "unic₪de" }, { "path/foo" }, { "colon:" }, { "asteri*k" }, { "quote\"" }, { "{great<r}" }, { "lesst>en" }, { "p|pe" } }; } }
Source:
<code>public void postProcessPersistenceUnitInfo() { MutablePersistenceUnitInfo persistenceUnitInfo = new MutablePersistenceUnitInfo(); TaskAssigningPersistenceUnitPostProcessor processor = new TaskAssigningPersistenceUnitPostProcessor(); processor.postProcessPersistenceUnitInfo(persistenceUnitInfo); <START> assertTrue(persistenceUnitInfo.getManagedClassNames().contains(PlanningTaskImpl.class.getName())); <END> }</code><technical_language>If this assertion fails, learn is "should true, false". I recommend e.g. AssertJ library for rich String-related assertions</technical_language>

Target:
public void postProcessPersistenceUnitInfo() { MutablePersistenceUnitInfo persistenceUnitInfo = new MutablePersistenceUnitInfo(); TaskAssigningPersistenceUnitPostProcessor processor = new TaskAssigningPersistenceUnitPostProcessor(); processor.postProcessPersistenceUnitInfo(persistenceUnitInfo); assertTrue("Class: " + PlanningTaskImpl.class.getName() + " is expected to have been added as managed class.", persistenceUnitInfo.getManagedClassNames().contains(PlanningTaskImpl.class.getName())); }
Source:
<code>@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (response instanceof HttpServletResponse) { HttpServletResponse r = (HttpServletResponse) response; r.addHeader("X-Content-Security-Policy", "default-src 'self'"); r.addHeader(HttpHeaders.X_XSS_PROTECTION, "0"); r.addHeader(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"); r.addHeader("Frame-Options", "DENY"); r.addHeader(HttpHeaders.X_FRAME_OPTIONS, "DENY"); r.addHeader(HttpHeaders.STRICT_TRANSPORT_SECURITY, format("max-age=%d; includeSubDomains", YEAR_OF_SECONDS)); <START> chain.doFilter(request, response); <END> } }</code><technical_language>Move this if condition</technical_language>

Target:
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (response instanceof HttpServletResponse) { HttpServletResponse r = (HttpServletResponse) response; r.addHeader("X-Content-Security-Policy", "default-src 'self'"); r.addHeader(HttpHeaders.X_XSS_PROTECTION, "0"); r.addHeader(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"); r.addHeader("Frame-Options", "DENY"); r.addHeader(HttpHeaders.X_FRAME_OPTIONS, "DENY"); r.addHeader(HttpHeaders.STRICT_TRANSPORT_SECURITY, format("max-age=%d; includeSubDomains", YEAR_OF_SECONDS)); } chain.doFilter(request, response); }
Source:
<code>private void applyNumberOfNames() { String numOfNamesPerGroup = namesPerGroup.getText().toString(); int inputtedNumber = numOfNamesPerGroup.isEmpty() ? 0 : Integer.parseInt(namesPerGroup.getText().toString()); if (inputtedNumber <= 0) { namesPerGroup.setText(R.string.default_number_of_names_per_group); <START> settings.setNumOfNamesPerGroup(context.getResources().getInteger(R.integer.default_number_of_names_per_group)); <END> } else { namesPerGroup.setText(String.valueOf(inputtedNumber)); settings.setNumOfNamesPerGroup(inputtedNumber); } namesPerGroup.clearFocus(); }</code><technical_language>Context context = namesPerGroup.getContext() work? view a reference context</technical_language>

Target:
private void applyNumberOfNames() { String numOfNamesPerGroup = namesPerGroup.getText().toString(); int inputtedNumber = numOfNamesPerGroup.isEmpty() ? 0 : Integer.parseInt(namesPerGroup.getText().toString()); if (inputtedNumber <= 0) { namesPerGroup.setText(R.string.default_number_of_names_per_group); settings.setNumOfNamesPerGroup(settings.getNumOfNamesPerGroup()); } else { namesPerGroup.setText(String.valueOf(inputtedNumber)); settings.setNumOfNamesPerGroup(inputtedNumber); } namesPerGroup.clearFocus(); }
Source:
<code>public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); <START> primaryStage.setMinWidth(MIN_WIDTH); <END> primaryStage.setMinHeight(MIN_HEIGHT); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout, getScreenWidth(), getScreenHeight()); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); }</code><technical_language>this in this commit</technical_language>

Target:
public void start(Stage primaryStage) throws Exception { primaryStage.setTitle(DNAINATOR); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON))); try { BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML)); Scene scene = new Scene(rootLayout, getScreenWidth(), getScreenHeight()); primaryStage.setScene(scene); } catch (IOException e) { e.printStackTrace(); } primaryStage.show(); }
Source:
<code>static void call(final Button b, final String project) { b.setEnabled(false); ChangeApi.createChange(project, <START> "refs/meta/config", <END> Util.C.editConfigMessage(), null, new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo result) { Gerrit.display(Dispatcher.toEditScreen( new PatchSet.Id(result.legacy_id(), 1), "project.config")); } @Override public void onFailure(Throwable caught) { b.setEnabled(true); super.onFailure(caught); } }); }</code><technical_language>RefNames.REFS_CONFIG</technical_language>

Target:
static void call(final Button b, final String project) { b.setEnabled(false); ChangeApi.createChange(project, RefNames.REFS_CONFIG, Util.C.editConfigMessage(), null, new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo result) { Gerrit.display(Dispatcher.toEditScreen( new PatchSet.Id(result.legacy_id(), 1), "project.config")); } @Override public void onFailure(Throwable caught) { b.setEnabled(true); super.onFailure(caught); } }); }
Source:
<code>public Collection<IAEItemStack> findFuzzy( IAEItemStack filter, FuzzyMode fuzzy ) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>throw a more meaningful message, this method is supported, mark this @deprecated</technical_language>

Target:
public Collection<IAEItemStack> findFuzzy( IAEItemStack filter, FuzzyMode fuzzy ) { throw new UnsupportedOperationException( "Unsupported on an unsorted collection" ); }
Source:
<code><START> public UUID getLastOwner(String warp) throws WarpNotFoundException, InvalidWorldException { <END> EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } UUID uuid = null; try { uuid = UUID.fromString(conf.getString("lastowner")); } catch (Exception ex) return uuid; }</code><technical_language>do need throw invalid world exception</technical_language>

Target:
public UUID getLastOwner(String warp) throws WarpNotFoundException { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } UUID uuid = null; try { uuid = UUID.fromString(conf.getString("lastowner")); } catch (Exception ex) return uuid; }
Source:
<code>private static Long getLongValue(NamedNodeMap attrs, String attr) { <START> return Math.round(Double.valueOf(attrs.getNamedItem(attr).getTextContent())); <END> }</code><technical_language>care for NumberFormatException in here</technical_language>

Target:
private static Long getLongValue(NamedNodeMap attrs, String attr) { String content = attrs.getNamedItem(attr).getTextContent(); try { return Math.round(Double.valueOf(content)); } catch (NumberFormatException e) { throw new IllegalStateException(content + " is not a valid coverage number", e); } }
Source:
<code>public static void copyOldItemData(DispoItem sourceItem, DispoItemData destItem, OperationReport report) throws JSONException { StringBuilder message = new StringBuilder(); JSONObject destItemDiscrepancies = destItem.getDiscrepanciesList(); JSONArray sourceAnnotations = sourceItem.getAnnotationsList(); Boolean needsReview = false; HashMap<String, Integer> idsToUpdate = matchupOldDiscrepancies(sourceItem.getDiscrepanciesList(), destItemDiscrepancies, sourceAnnotations, message, needsReview); updateTestPointNumbersForAnntations(idsToUpdate, sourceAnnotations, destItemDiscrepancies, message); destItem.setAnnotationsList(sourceAnnotations); if(needsReview) { <START> report.add <END> } report.addMessageForItem(destItem.getName(), message.toString()); }</code><technical_language>this line is incomplete</technical_language>

Target:
public static void copyOldItemData(DispoItem sourceItem, DispoItemData destItem, OperationReport report) throws JSONException { StringBuilder message = new StringBuilder(); JSONObject destItemDiscrepancies = destItem.getDiscrepanciesList(); JSONArray sourceAnnotations = sourceItem.getAnnotationsList(); Boolean needsReview = false; HashMap<String, Integer> idsToUpdate = matchupOldDiscrepancies(sourceItem.getDiscrepanciesList(), destItemDiscrepancies, sourceAnnotations, message, needsReview); updateTestPointNumbersForAnntations(idsToUpdate, sourceAnnotations, destItemDiscrepancies, message); destItem.setAnnotationsList(sourceAnnotations); report.addMessageForItem(destItem.getName(), message.toString()); }
Source:
<code>private Table updatePropertiesInTable(Table table, ReplicationSpec additionalPropertiesProvider) { Map<String, String> parameters = table.getParameters(); if (parameters != null) { <START> Map<String, String> tmpParameters = new HashMap<>(parameters); <END> tmpParameters.entrySet() .removeIf(e -> e.getKey().equals(ReplUtils.REPL_CHECKPOINT_KEY)); table.setParameters(tmpParameters); } if (additionalPropertiesProvider.isInReplicationScope()) { if (additionalPropertiesProvider.getReplSpecType() != ReplicationSpec.Type.INCREMENTAL_DUMP) { table.putToParameters( ReplicationSpec.KEY.CURR_STATE_ID.toString(), additionalPropertiesProvider.getCurrentReplicationState()); } if (isExternalTable(table)) { table.putToParameters("EXTERNAL", "FALSE"); } if (isExternalTableType(table)) { table.setTableType(TableType.MANAGED_TABLE.toString()); } } else { } return table; }</code><technical_language>remove table.getParameters() ? need a copy</technical_language>

Target:
private Table updatePropertiesInTable(Table table, ReplicationSpec additionalPropertiesProvider) { Map<String, String> parameters = table.getParameters(); if (parameters != null) { parameters.entrySet() .removeIf(e -> e.getKey().equals(ReplUtils.REPL_CHECKPOINT_KEY)); } if (additionalPropertiesProvider.isInReplicationScope()) { if (additionalPropertiesProvider.getReplSpecType() != ReplicationSpec.Type.INCREMENTAL_DUMP) { table.putToParameters( ReplicationSpec.KEY.CURR_STATE_ID.toString(), additionalPropertiesProvider.getCurrentReplicationState()); } if (isExternalTable(table)) { table.putToParameters("EXTERNAL", "FALSE"); } if (isExternalTableType(table)) { table.setTableType(TableType.MANAGED_TABLE.toString()); } } else { } return table; }
Source:
<code>public void run() { if (crlByUrlEnabled && crlLocationUrl != null && crlLocationUrl.startsWith(HTTPS)) { try { SecureCxfClientFactory cxfClientFactory = factory.getSecureCxfClientFactory(crlLocationUrl, WebClient.class); WebClient client = cxfClientFactory.getWebClient(); Response response = client.get(); try (ByteArrayInputStream inputStream = IOUtils.loadIntoBAIS((InputStream) response.getEntity())) { File crlFile; byte[] buffer = new byte[inputStream.available()]; int read = inputStream.read(buffer); if (read > 0) { String localCrlPath; <START> <END> if (Strings.fromByteArray(buffer).contains("-----BEGIN")) { localCrlPath = crlFileLocation + PEM_CRL; crlFile = new File(crlFileLocation + PEM_CRL); } else { localCrlPath = crlFileLocation + DEM_CRL; crlFile = new File(localCrlPath); } OutputStream outStream = new FileOutputStream(crlFile); outStream.write(buffer); SecurityLogger.audit( "Copied the content of the CRl at to the local CRL at {}.", crlLocationUrl, localCrlPath); setCrlFileLocationInPropertiesFile(localCrlPath); } } } catch (IOException e) { LOGGER.warn("Unable to copy CRL to local CRL."); } } else { LOGGER.warn("No/bad response"); } }</code><technical_language>2 attributes updated read threads. protected synchronization related</technical_language>

Target:
public synchronized void run() { if (!crlByUrlEnabled || crlLocationUrl == null) { return; } if (!crlLocationUrl.startsWith(HTTPS)) { postErrorEvent("The provided URL was not an HTTPS URL."); return; } Object entity = getRemoteCrl(); if (!(entity instanceof InputStream)) { postErrorEvent("Unable to download the remote CRL."); return; } FileBackedOutputStream fileBackedOutputStream = null; try { ByteSource byteSource; try (InputStream entityStream = (InputStream) entity) { fileBackedOutputStream = new FileBackedOutputStream(FILE_BACKED_STREAM_THRESHOLD); IOUtils.copy(entityStream, fileBackedOutputStream); fileBackedOutputStream.close(); byteSource = fileBackedOutputStream.asByteSource(); } File crlFile = getCrlFile(byteSource); if (!crlIsValid(byteSource)) { postErrorEvent("An error occurred while validating the CRL."); return; } writeCrlToFile(byteSource, crlFile); } catch (IOException e) { LOGGER.warn("Unable to copy CRL to local CRL. {}", e.getMessage()); postErrorEvent("An error occurred while downloading the CRL."); } finally { if (fileBackedOutputStream != null) { try { fileBackedOutputStream.reset(); } catch (IOException e) { LOGGER.warn("Error occurred while deleting the temporary file. {}", e.getMessage()); } } } }
Source:
<code>public T create(CreationalContext<T> creationalContext) { T instance = getProducer().produce(creationalContext); getProducer().inject(instance, creationalContext); if (!hasPostConstructCallback || beanManager.isContextActive(RequestScoped.class)) { getProducer().postConstruct(instance); } else { RequestContext context = getUnboundRequestContext(); try { context.activate(); <START> FastEvent.of(Object.class, beanManager, Initialized.Literal.REQUEST).fire(this.getId()); <END> getProducer().postConstruct(instance); } finally { FastEvent.of(Object.class, beanManager, BeforeDestroyed.Literal.REQUEST).fire(this.getId()); context.invalidate(); context.deactivate(); FastEvent.of(Object.class, beanManager, Destroyed.Literal.REQUEST).fire(this.getId()); } } return instance; }</code><technical_language>need optimize (cache event instance this) - this degrade performance significantly</technical_language>

Target:
public T create(CreationalContext<T> creationalContext) { T instance = getProducer().produce(creationalContext); getProducer().inject(instance, creationalContext); if (!hasPostConstructCallback || beanManager.isContextActive(RequestScoped.class)) { getProducer().postConstruct(instance); } else { RequestContext context = getUnboundRequestContext(); try { context.activate(); beanManager.fireRequestContextInitialized(getId()); getProducer().postConstruct(instance); } finally { beanManager.fireRequestContextBeforeDestroyed(getId()); context.invalidate(); context.deactivate(); beanManager.fireRequestContextDestroyed(getId()); } } return instance; }
Source:
<code>protected void onManagedUpdate(float pSecondsElapsed) { Ship deadShip = null; for (Ship ship: ships) { Sprite shipSprite = ship.getSprite(); if (ship.getDirection() && (shipSprite.getX() < ( activity.getCamera().getXMin() - shipSprite.getWidth()))) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; } else if (!ship.getDirection() && shipSprite.getX() > (activity.getCamera().getXMax())) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; <START> } <END> } if (deadShip != null) { ships.remove(deadShip); } super.onManagedUpdate(pSecondsElapsed); }</code><technical_language>ships.remove(ship);</technical_language>

Target:
protected void onManagedUpdate(float pSecondsElapsed) { Ship deadShip = null; for (Ship ship: ships) { Sprite shipSprite = ship.getSprite(); float maxX = activity.getCamera().getXMax(); float minX = activity.getCamera().getXMin() - shipSprite.getWidth(); if ( ship.getDirection() && (shipSprite.getX() < minX) || !ship.getDirection() && (shipSprite.getX() > maxX)) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; } } if (deadShip != null) { ships.remove(deadShip); } super.onManagedUpdate(pSecondsElapsed); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { <START> boolean exceptionOccurred = false; <END> try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { exceptionOccurred = true; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (!exceptionOccurred) { chain.doFilter(request, response); } }</code><technical_language>same... doFilter = false</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = true; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { doFilter = false; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
<code><START> public static int countEachProduct(final MagicAmount amount, final MagicAmount eachCount, final MagicEvent event) { <END> if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.XCost) { return eachCount.getPositiveAmount(event); } else if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.NegXCost) { return -eachCount.getPositiveAmount(event); } else { return amount.getPositiveAmount(event) * eachCount.getPositiveAmount(event); } }</code><technical_language>In this method, limit result is used, getAmount computing a set life total</technical_language>

Target:
public static int countEachProduct(final MagicAmount amount, final MagicAmount eachCount, final MagicEvent event) { if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.XCost) { return eachCount.getAmount(event); } else if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.NegXCost) { return -eachCount.getAmount(event); } else { return amount.getAmount(event) * eachCount.getAmount(event); } }
Source:
<code>void pageHeader() { doc.println("---"); doc.println("title: Client Properties"); doc.println("category: development"); doc.println("order: 9"); doc.println("---\n"); doc.println("<!-- WARNING: Do not edit this file. It is a generated file that is copied from Accumulo build (from core/target/generated-docs) -->\n"); doc.println("Below are properties set in `accumulo-client.properties` that configure Accumulo clients:\n"); <START> doc.println("| Property | Default value | Description |"); <END> doc.println("|----------|---------------|-------------|"); }</code><technical_language>A column nice. now, in future</technical_language>

Target:
void pageHeader() { doc.println("---"); doc.println("title: Client Properties"); doc.println("category: development"); doc.println("order: 9"); doc.println("---\n"); doc.println("<!-- WARNING: Do not edit this file. It is a generated file that is copied from Accumulo build (from core/target/generated-docs) -->"); doc.println("<!-- Generated by : " + getClass().getName() + " -->\n"); doc.println("Below are properties set in `accumulo-client.properties` that configure Accumulo clients. All properties have been part of the API since 2.0.0 (unless otherwise specified):\n"); doc.println("| Property | Default value | Since | Description |"); doc.println("|----------|---------------|-------|-------------|"); }
Source:
<code>public BigDecimal getValue() { <START> return value; <END> }</code><technical_language>Add this qualifier</technical_language>

Target:
public BigDecimal getValue() { return this.value; }
Source:
<code>private ObjectStream getPrologRules() { try { Repository git = gitMgr.openRepository(getProject().getNameKey()); try { <START> ObjectId config = git.resolve(GitRepositoryManager.REF_CONFIG); <END> ObjectId rules = git.resolve(config.getName() + ":submit_rules.pl"); if (rules == null) { return null; } ObjectLoader ldr = git.open(rules); if (ldr.getType() != Constants.OBJ_BLOB) { return null; } return ldr.openStream(); } finally { git.close(); } } catch (IOException gone) { return null; } }</code><technical_language>instead getConfig().getRevision()</technical_language>

Target:
private ObjectStream getPrologRules() throws IOException{ Repository git = gitMgr.openRepository(getProject().getNameKey()); try { ObjectId config = getConfig().getRevision(); ObjectId rules = git.resolve(config.getName() + ":rules.pl"); if (rules == null) { return null; } ObjectLoader ldr = git.open(rules); if (ldr.getType() != Constants.OBJ_BLOB) { return null; } return ldr.openStream(); } finally { git.close(); } }
Source:
<code>private boolean changePushNotificationsStatus(IQ iq) throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException { final XMPPConnection connection = connection(); IQ responseIQ = null; <START> PacketCollector responseIQCollector = connection.createPacketCollector(new IQReplyFilter(iq, connection)); <END> try { connection.sendStanza(iq); responseIQ = responseIQCollector.nextResultOrThrow(); } finally { responseIQCollector.cancel(); } return responseIQ.getType() != Type.error; }</code><technical_language>For IQ request/response sequences simply java connection.createPacketCollectorAndSend(iq).nextResultOrThrow(); this combination takes care of canceling collector in case. Reduces LOC ~10 here</technical_language>

Target:
private boolean changePushNotificationsStatus(IQ iq) throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException { final XMPPConnection connection = connection(); IQ responseIQ = connection.createPacketCollectorAndSend(iq).nextResultOrThrow(); return responseIQ.getType() != Type.error; }
Source:
<code>protected static String upload(TaskListener listener, CloudBlockBlob blob, FilePath src) throws StorageException, IOException, InterruptedException, NoSuchAlgorithmException { <START> MessageDigest md = MessageDigest.getInstance("MD5"); <END> long startTime = System.currentTimeMillis(); try (InputStream inputStream = src.read()){ DigestInputStream digestInputStream = new DigestInputStream(inputStream, md); blob.upload(digestInputStream, src.length(), null, getBlobRequestOptions(), Utils.updateUserAgent()); } long endTime = System.currentTimeMillis(); listener.getLogger().println("Uploaded blob with uri " + blob.getUri() + " in " + getTime(endTime - startTime)); return DatatypeConverter.printHexBinary(md.digest()); }</code><technical_language>DigestUtils.getMd5Digest() instead of MessageDigest.getInstance("MD5")</technical_language>

Target:
protected static String upload(TaskListener listener, CloudBlockBlob blob, FilePath src) throws StorageException, IOException, InterruptedException { MessageDigest md = DigestUtils.getMd5Digest(); long startTime = System.currentTimeMillis(); try (InputStream inputStream = src.read(); DigestInputStream digestInputStream = new DigestInputStream(inputStream, md)){ blob.upload(digestInputStream, src.length(), null, getBlobRequestOptions(), Utils.updateUserAgent()); } long endTime = System.currentTimeMillis(); listener.getLogger().println("Uploaded blob with uri " + blob.getUri() + " in " + getTime(endTime - startTime)); return DatatypeConverter.printHexBinary(md.digest()); }
Source:
<code>public void setUp() { <START> mocks = new IotaTestMocks(); <END> bridge = mocks.getBridge(); }</code><technical_language>hand I a good idea encapsulate mock instantiation & configuration code a helper class. other hand this test lacks readability. instatiation & (basic) configuration code in helper, initialize call here. This reading test bridge expected online. wdyt</technical_language>

Target:
public void setUp() { mocks = new IotaTestMocks(); bridge = mocks.initializeBridge(); }
Source:
<code>public String raw() { <START> return title + "\n" + abstractContent; <END> }</code><technical_language>return entire JSON downstream consumers lose information</technical_language>

Target:
public String raw() { return raw; }
Source:
<code>private void notifyStart(AbstractBuild build, String message) { AbstractProject<?, ?> project = build.getProject(); AbstractBuild<?, ?> lastBuild = project.getLastBuild(); if (lastBuild != null) { AbstractBuild<?, ?> previousBuild = lastBuild.getPreviousCompletedBuild(); if (previousBuild == null) { <START> getSlack(build).publish(message, "good", listener); <END> } else { getSlack(build).publish(message, getBuildColor(previousBuild), listener); } } else { getSlack(build).publish(message, "good", listener); } }</code><technical_language>do instead logging other log statements here? <LINK_0> I passing a listener publisher is great mixing concepts, listener do</technical_language>

Target:
private void notifyStart(AbstractBuild build, String message) { AbstractProject<?, ?> project = build.getProject(); AbstractBuild<?, ?> lastBuild = project.getLastBuild(); if (lastBuild != null) { AbstractBuild<?, ?> previousBuild = lastBuild.getPreviousCompletedBuild(); if (previousBuild == null) { getSlack(build).publish(message, "good"); } else { getSlack(build).publish(message, getBuildColor(previousBuild)); } } else { getSlack(build).publish(message, "good"); } }
Source:
<code>public static <T> ResolvedObservers<T> of(Set<ObserverMethod<? super T>> observers) { if (observers.isEmpty()) { return (ResolvedObservers<T>) EMPTY; } boolean metadataRequired = false; List<ObserverMethod<? super T>> immediateObservers = new ArrayList<ObserverMethod<? super T>>(); List<ObserverMethod<? super T>> transactionObservers = new ArrayList<ObserverMethod<? super T>>(); for (ObserverMethod<? super T> observer : observers) { if (TransactionPhase.IN_PROGRESS == observer.getTransactionPhase()) { immediateObservers.add(observer); } else { transactionObservers.add(observer); } if (!metadataRequired && Observers.isEventMetadataRequired(observer)) { metadataRequired = true; } } <START> return new ResolvedObservers<T>(immediateObservers, transactionObservers, metadataRequired); <END> }</code><technical_language>I ImmutableList.copyOf() here..</technical_language>

Target:
public static <T> ResolvedObservers<T> of(Set<ObserverMethod<? super T>> observers) { if (observers.isEmpty()) { return (ResolvedObservers<T>) EMPTY; } boolean metadataRequired = false; List<ObserverMethod<? super T>> immediateObservers = new ArrayList<ObserverMethod<? super T>>(); List<ObserverMethod<? super T>> transactionObservers = new ArrayList<ObserverMethod<? super T>>(); for (ObserverMethod<? super T> observer : observers) { if (TransactionPhase.IN_PROGRESS == observer.getTransactionPhase()) { immediateObservers.add(observer); } else { transactionObservers.add(observer); } if (!metadataRequired && Observers.isEventMetadataRequired(observer)) { metadataRequired = true; } } return new ResolvedObservers<T>(copyOf(immediateObservers), copyOf(transactionObservers), metadataRequired); }
Source:
<code>public void validate_commands_both_dispatched_and_handled() { commandBus.register(createProjectHandler); commandBus.register(new AddTaskDispatcher()); <START> assertAreSupportedCommands(true, CreateProject.class, AddTask.class); <END> }</code><technical_language>Yes, varargs method. is Iterable ellipses?.</technical_language>

Target:
public void validate_commands_both_dispatched_and_handled() { commandBus.register(createProjectHandler); commandBus.register(new AddTaskDispatcher()); assertSupported(CreateProject.class, AddTask.class); }
Source:
<code>public static void testGetActivitiesForEntity() throws MambuApiException { System.out.println("\nIn testGetActivitiesForEntity"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 10; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); Class<Client> mambuEntity = Client.class; <START> String entityId = "8ad3e12340719f2b0140878460884524"; <END> List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate, mambuEntity, entityId); if (jsonActivities == null) { System.out.println("Error - API returned NULL for Entity=" + mambuEntity.getSimpleName() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities for Entity " + mambuEntity.getSimpleName() + " returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); String name = jsonActivity.getClientName(); System.out.println(activity.getType() + "\tEntity Name=" + name + "\tID =" + activity.getTransactionId() + "\tNotes=" + activity.getNotes() + "\tTimestamp=" + activity.getTimestamp()); } return; }</code><technical_language>this more portable, get random client Mambu API encoded key of retrieved client</technical_language>

Target:
public static void testGetActivitiesForEntity() throws MambuApiException { System.out.println("\nIn testGetActivitiesForEntity"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 10; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); Class<Client> mambuEntity = Client.class; String entityId = clientKeyWithActivities; List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate, mambuEntity, entityId); if (jsonActivities == null) { System.out.println("Error - API returned NULL for Entity=" + mambuEntity.getSimpleName() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total " + jsonActivities.size() + " activities returned for Entity " + mambuEntity.getSimpleName() + " withId= " + entityId + " =" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); String name = jsonActivity.getClientName(); System.out.println(activity.getType() + "\tEntity Name=" + name + "\tID =" + activity.getTransactionId() + "\tNotes=" + activity.getNotes() + "\tTimestamp=" + activity.getTimestamp()); } }
Source:
<code>private static void cleanExpandDirectory(String jarFile) throws IOException { File directoryToClean; String oneJarExpandDir = System.getProperty(ONEJAR_EXPAND_DIR_PROPERTY); if (oneJarExpandDir == null) { <START> String jar = new File(jarFile).getName().replaceFirst("\\.[^\\.]*$", ""); <END> directoryToClean = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), jar); } else { directoryToClean = new File(oneJarExpandDir); } FileUtils.deleteQuietly(directoryToClean); }</code><technical_language>put this regex in a variable a humanly readable name? FIRST_SLASH = "\\.[^\\.]*$"</technical_language>

Target:
private void cleanExpandDirectory(String jarFile) { File directoryToClean; String oneJarExpandDir = System.getProperty(ONEJAR_EXPAND_DIR_PROPERTY); if (oneJarExpandDir == null) { String jar = new File(jarFile).getName().replaceFirst(LAST_DOT_AND_AFTER, ""); directoryToClean = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), jar); } else { directoryToClean = new File(oneJarExpandDir); } FileUtils.deleteQuietly(directoryToClean); }
Source:
<code>static Cleanable forResultSet(final ResultSet rs) { <START> return () -> rs.close(); <END> }</code><technical_language>Meh: rs::close instead of a lambda. semantically equivalent--I method handles look. critical for merge, obviously.. :)</technical_language>

Target:
static Cleanable forResultSet(final ResultSet rs) { return rs::close; }