auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void putUnlessExists(long startTimestamp, long commitTimestamp) throws KeyAlreadyExistsException { if (!isTimestampValid(startTimestamp)) { <START> throw new SafeIllegalStateException("Attempted to putUnlessExists({}, {}) which is unexpected.", <END> SafeArg.of("startTimestamp", startTimestamp), SafeArg.of("commitTimestamp", commitTimestamp)); } delegate.putUnlessExists(startTimestamp, commitTimestamp); }</code><technical_language>'disallowed' 'unexpected' clearer this is a bad do, a case consider</technical_language>

Target:
public void putUnlessExists(long startTimestamp, long commitTimestamp) throws KeyAlreadyExistsException { if (!isTimestampValid(startTimestamp)) { throw new SafeIllegalStateException("Attempted to putUnlessExists({}, {}) which is disallowed.", SafeArg.of("startTimestamp", startTimestamp), SafeArg.of("commitTimestamp", commitTimestamp)); } delegate.putUnlessExists(startTimestamp, commitTimestamp); }
Source:
<code>private LauncherDiscoveryListener getLauncherDiscoveryListener(ConfigurationParameters configurationParameters) { <START> LauncherDiscoveryListener defaultDiscoveryListener = LauncherDiscoveryListeners.fromConfigurationParameter( <END> configurationParameters); if (discoveryListeners.isEmpty()) { return defaultDiscoveryListener; } if (discoveryListeners.contains(defaultDiscoveryListener)) { return LauncherDiscoveryListeners.composite(discoveryListeners); } List<LauncherDiscoveryListener> allDiscoveryListeners = new ArrayList<>(discoveryListeners); allDiscoveryListeners.add(defaultDiscoveryListener); return LauncherDiscoveryListeners.composite(allDiscoveryListeners); }</code><technical_language>naming - configuredDiscoveryListener configuredDefaultDiscoveryListener convey intent more clearly</technical_language>

Target:
private LauncherDiscoveryListener getLauncherDiscoveryListener(ConfigurationParameters configurationParameters) { LauncherDiscoveryListener defaultDiscoveryListener = configurationParameters.get( DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME) .map(value -> LauncherDiscoveryListeners.fromConfigurationParameter( DEFAULT_DISCOVERY_LISTENER_CONFIGURATION_PROPERTY_NAME, value)) .orElseGet(LauncherDiscoveryListeners::abortOnFailure); if (discoveryListeners.isEmpty()) { return defaultDiscoveryListener; } if (discoveryListeners.contains(defaultDiscoveryListener)) { return LauncherDiscoveryListeners.composite(discoveryListeners); } List<LauncherDiscoveryListener> allDiscoveryListeners = new ArrayList<>(discoveryListeners); allDiscoveryListeners.add(defaultDiscoveryListener); return LauncherDiscoveryListeners.composite(allDiscoveryListeners); }
Source:
<code>private Map<String, String> normalizeHeaders(Map<String,String> headerMap) { Map<String,String> normHeaderMap = new HashMap<String,String>(); for (Map.Entry<String, String> entry : headerMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (amzHeaders.contains(key.toLowerCase(Locale.US))) { key = "x-amz-" + key; } else if (!standardHeaders.contains(key.toLowerCase(Locale.US)) <START> && !key.toLowerCase(Locale.US).startsWith("x-amz-")) { <END> key = "x-amz-meta-" + key; } normHeaderMap.put(key, value); } return normHeaderMap; }</code><technical_language>String headerKey = key.toLowerCase(Locale.US) avoid repeated case conversion</technical_language>

Target:
private Map<String, String> normalizeHeaders(Map<String,String> headerMap) { Map<String,String> normHeaderMap = new HashMap<String,String>(); for (Map.Entry<String, String> entry : headerMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String keyLowerCased = key.toLowerCase(Locale.US); if (amzHeaders.contains(keyLowerCased)) { key = "x-amz-" + key; } else if (!standardHeaders.contains(keyLowerCased) && !keyLowerCased.startsWith("x-amz-")) { key = "x-amz-meta-" + key; } normHeaderMap.put(key, value); } return normHeaderMap; }
Source:
<code>public MysqlSchemaStore(ConnectionPool maxwellConnectionPool, ConnectionPool replicationConnectionPool, Long serverID, BinlogPosition initialPosition, CaseSensitivity caseSensitivity, MaxwellFilter filter, boolean replayMode) { super(replicationConnectionPool, caseSensitivity, filter); <START> this.caseSensitivity = caseSensitivity; <END> this.serverID = serverID; this.maxwellConnectionPool = maxwellConnectionPool; this.initialPosition = initialPosition; this.replayMode = replayMode; }</code><technical_language>needed</technical_language>

Target:
public MysqlSchemaStore(ConnectionPool maxwellConnectionPool, ConnectionPool replicationConnectionPool, Long serverID, BinlogPosition initialPosition, CaseSensitivity caseSensitivity, MaxwellFilter filter, boolean replayMode) { super(replicationConnectionPool, caseSensitivity, filter); this.serverID = serverID; this.maxwellConnectionPool = maxwellConnectionPool; this.initialPosition = initialPosition; this.replayMode = replayMode; }
Source:
<code>public MultiDataSetIterator getTrainIterator() { return new MultiDataSetIterator() { @Override public MultiDataSet next(int num) { throw new UnsupportedOperationException("To be implemented yet"); } @Override public void setPreProcessor(MultiDataSetPreProcessor preProcessor) { backedIterator.setPreProcessor(preProcessor); } @Override public MultiDataSetPreProcessor getPreProcessor() { return backedIterator.getPreProcessor(); } @Override public boolean resetSupported() { <START> return backedIterator.asyncSupported(); <END> } @Override public boolean asyncSupported() { return backedIterator.asyncSupported(); } @Override public void reset() { resetPending.set(true); } @Override public boolean hasNext() { if (resetPending.get()) { backedIterator.reset(); counter.set(0); resetPending.set(false); } val state = backedIterator.hasNext(); if (state && counter.get() < numTrain) return true; else return false; } @Override public MultiDataSet next() { counter.incrementAndGet(); return backedIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>Wrong method</technical_language>

Target:
public MultiDataSetIterator getTrainIterator() { return new MultiDataSetIterator() { @Override public MultiDataSet next(int num) { throw new UnsupportedOperationException("To be implemented yet"); } @Override public void setPreProcessor(MultiDataSetPreProcessor preProcessor) { backedIterator.setPreProcessor(preProcessor); } @Override public MultiDataSetPreProcessor getPreProcessor() { return backedIterator.getPreProcessor(); } @Override public boolean resetSupported() { return backedIterator.resetSupported(); } @Override public boolean asyncSupported() { return backedIterator.asyncSupported(); } @Override public void reset() { resetPending.set(true); } @Override public boolean hasNext() { if (resetPending.get()) { if (resetSupported()) { backedIterator.reset(); counter.set(0); resetPending.set(false); } else throw new UnsupportedOperationException("Reset isn't supported by underlying iterator"); } val state = backedIterator.hasNext(); if (state && counter.get() < numTrain) return true; else return false; } @Override public MultiDataSet next() { counter.incrementAndGet(); val p = backedIterator.next(); if (counter.get() == 1 && firstTrain == null) { firstTrain = (org.nd4j.linalg.dataset.MultiDataSet) p.copy(); firstTrain.detach(); } else if (counter.get() == 1) { int cnt = 0; for (val c: p.getFeatures()) if (!c.equalsWithEps(firstTrain.getFeatures()[cnt++], 1e-5)) throw new ND4JIllegalStateException("First examples do not match. Randomization was used?"); } return p; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
<code>public byte[] encode() { StringBuilder builder = new StringBuilder(name); builder.append('\0').append(type); builder.append('\0').append(server); builder.append('\0').append(saveLogin ? username : ""); builder.append('\0').append(saveLogin ? password : ""); builder.append('\0').append(dnsServers); builder.append('\0').append(searchDomains); builder.append('\0').append(routes); builder.append('\0').append(mppe); builder.append('\0').append(l2tpSecret); builder.append('\0').append(ipsecIdentifier); builder.append('\0').append(ipsecSecret); builder.append('\0').append(ipsecUserCert); builder.append('\0').append(ipsecCaCert); builder.append('\0').append(ipsecServerCert); builder.append('\0').append(proxy != null ? <START> proxy.getHost() <END> : ""); builder.append('\0').append(proxy != null ? proxy.getPort() : ""); builder.append('\0').append(proxy != null ? proxy.getExclusionListAsString() : ""); builder.append('\0').append(proxy != null ? proxy.getPacFileUrl().toString() : ""); return builder.toString().getBytes(StandardCharsets.UTF_8); }</code><technical_language>getHost() return null</technical_language>

Target:
public byte[] encode() { StringBuilder builder = new StringBuilder(name); builder.append('\0').append(type); builder.append('\0').append(server); builder.append('\0').append(saveLogin ? username : ""); builder.append('\0').append(saveLogin ? password : ""); builder.append('\0').append(dnsServers); builder.append('\0').append(searchDomains); builder.append('\0').append(routes); builder.append('\0').append(mppe); builder.append('\0').append(l2tpSecret); builder.append('\0').append(ipsecIdentifier); builder.append('\0').append(ipsecSecret); builder.append('\0').append(ipsecUserCert); builder.append('\0').append(ipsecCaCert); builder.append('\0').append(ipsecServerCert); if (proxy != null) { builder.append('\0').append(proxy.getHost() != null ? proxy.getHost() : ""); builder.append('\0').append(proxy.getPort()); builder.append('\0').append(proxy.getExclusionListAsString() != null ? proxy.getExclusionListAsString() : ""); builder.append('\0').append(proxy.getPacFileUrl().toString()); } return builder.toString().getBytes(StandardCharsets.UTF_8); }
Source:
<code><START> void init() { <END> dragArea.onmousedown = this::onDragAreaMouseDown; dragArea.onmouseup = this::onDragAreaMouseUp; dragArea.onmousemove = this::onDragAreaMouseMove; }</code><technical_language>I this method private: suggestion private void init() {</technical_language>

Target:
private void init() { dragArea.onmousedown = this::onDragAreaMouseDown; dragArea.onmouseup = this::onDragAreaMouseUp; dragArea.onmousemove = this::onDragAreaMouseMove; }
Source:
<code>private boolean acquireTokensForJob(JobDescriptorImpl job) { final String requiredLicenses = job.getInternal().getRuntimeGenericInformation().get(REQUIRED_LICENSES); final String jobId = job.getJobId().value(); if (requiredLicenses != null) { logger.debug("For job considering licenses " + requiredLicenses); final HashSet<String> requiredLicensesSet = new HashSet<String>(Arrays.asList(requiredLicenses.split(","))); for (String requiredLicense : requiredLicensesSet) { if (!licenseSynchronization.containsLicense(requiredLicense)) { logger.debug("The required software is not specified in the license properties file, keep job pending"); return false; } if (!licenseSynchronization.containsJobId(requiredLicense, jobId) && !canGetToken(requiredLicense)) { logger.debug("Token for " + requiredLicense + " not available, keep job pending"); return false; } } for (String requiredLicense : requiredLicensesSet) { if (!licenseSynchronization.containsJobId(requiredLicense, jobId)) { licenseSynchronization.addJobToLicense(requiredLicense, jobId); <START> licenseSynchronization.acquireToken(requiredLicense); <END> licenseSynchronization.getAndPutForJobsLicensePersist(requiredLicense); } } logger.debug("Job eligible since it can get all tokens"); licenseSynchronization.persist(); return true; } else { logger.debug("Job eligible since it does not require any license"); return true; } }</code><technical_language>addJobToLicense acquireToken done in a single call (the called first)</technical_language>

Target:
private boolean acquireTokensForJob(JobDescriptorImpl job) { final String requiredLicenses = job.getInternal().getRuntimeGenericInformation().get(REQUIRED_LICENSES); final String jobId = job.getJobId().value(); if (requiredLicenses != null) { logger.debug("For job considering licenses " + requiredLicenses); final HashSet<String> requiredLicensesSet = new HashSet<String>(Arrays.asList(requiredLicenses.split(","))); for (String requiredLicense : requiredLicensesSet) { if (!licenseSynchronization.containsLicense(requiredLicense)) { logger.debug("The required software is not specified in the license properties file, keep job pending"); return false; } if (!licenseSynchronization.containsJobId(requiredLicense, jobId) && !canGetToken(requiredLicense)) { logger.debug("Token for " + requiredLicense + " not available, keep job pending"); return false; } } for (String requiredLicense : requiredLicensesSet) { if (!licenseSynchronization.containsJobId(requiredLicense, jobId)) { licenseSynchronization.addJobToLicense(requiredLicense, jobId); licenseSynchronization.markJobLicenseChange(requiredLicense); } } logger.debug("Job eligible since it can get all tokens"); licenseSynchronization.persist(); return true; } else { logger.debug("Job eligible since it does not require any license"); return true; } }
Source:
<code>public void handlesOptional() throws Exception { TypedValue result = expressionLanguage.evaluate("'hello' as String {class: 'java.util.Optional'}", testEvent(), BindingContext.builder().build()); <START> assertThat(result.getValue(), is(instanceOf(Optional.class))); <END> }</code><technical_language>checking value? create OptionalMatcher checks Class</technical_language>

Target:
public void handlesOptional() throws Exception { TypedValue result = expressionLanguage.evaluate("'hello' as String {class: 'java.util.Optional'}", testEvent(), BindingContext.builder().build()); assertThat(result.getValue(), is(instanceOf(Optional.class))); assertThat(((Optional) result.getValue()).get(), is("hello")); }
Source:
<code><START> public List<Integer> getQuarks() { <END> String[] paths = fPath.split(SPLIT_STRING); int i = 0; @SuppressWarnings("null") @NonNull List<Integer> quarks = Collections.singletonList(IXmlStateSystemContainer.ROOT_QUARK); while (i < paths.length) { List<Integer> subQuarks = new LinkedList<>(); String name = paths[i].replaceAll("\\*", ".*"); for (int relativeQuark : quarks) { try { for (int quark : fStateSystem.getSubAttributes(relativeQuark, false, name)) { subQuarks.add(quark); } } catch (AttributeNotFoundException e) { } } quarks = subQuarks; i++; } return quarks; }</code><technical_language>I some modifications this part (*rewrites everything*): private static final Pattern WILDCARD_PATTERN = Pattern.compile("\\*"); public List<Integer> getQuarks() { /* Get list of quarks process this path */ String[] paths = fPath.split(SPLIT_STRING); @SuppressWarnings("null") @NonNull List<Integer> quarks = Collections.singletonList(IXmlStateSystemContainer.ROOT_QUARK); try { for (String path : paths) { List<Integer> subQuarks = new LinkedList<>(); /* Replace * .* a regex string */ String name = WILDCARD_PATTERN.matcher(path).replaceAll(".*"); for (int relativeQuark : quarks) { subQuarks.addAll(fStateSystem.getSubAttributes(relativeQuark, false, name)); } quarks = subQuarks; } } catch (AttributeNotFoundException e) { /* * get attributes state system itself, this * happen. */ throw new IllegalStateException(); } return quarks; } * If a regex times, faster compile beforehand. * .addAll(Collection) add elements of Collection another. * Moved 'try' of for loops. AFAIU, hit exception in normal behavior. try a slight performance impact, if do loop</technical_language>

Target:
public List<Integer> getQuarks() { String[] paths = fPath.split(SPLIT_STRING); @SuppressWarnings("null") @NonNull List<Integer> quarks = Collections.singletonList(IXmlStateSystemContainer.ROOT_QUARK); try { for (String path : paths) { List<Integer> subQuarks = new LinkedList<>(); String name = WILDCARD_PATTERN.matcher(path).replaceAll(".*"); for (int relativeQuark : quarks) { subQuarks.addAll(fStateSystem.getSubAttributes(relativeQuark, false, name)); } quarks = subQuarks; } } catch (AttributeNotFoundException e) { throw new IllegalStateException(); } return quarks; }
Source:
<code><START> public AbstractHorizontalScrollViewAssert hasMaximumScrollAmount(int amount) { <END> isNotNull(); int actualAmount = actual.getMaxScrollAmount(); assertThat(actualAmount) .overridingErrorMessage("Expected maximum scroll amount <%s> but was <%s>.", amount, actualAmount) .isEqualTo(amount); return this; }</code><technical_language>return S need trick (copy/paste other abstract ones)</technical_language>

Target:
public S hasMaximumScrollAmount(int amount) { isNotNull(); int actualAmount = actual.getMaxScrollAmount(); assertThat(actualAmount) .overridingErrorMessage("Expected maximum scroll amount <%s> but was <%s>.", amount, actualAmount) .isEqualTo(amount); return myself; }
Source:
<code>public void checkApplicationIsBeingInitialized(Activity activity, ProgressDialog progressDialog) { startApplication(); synchronized (OsmandApplication.this) { if (startDialog != null) { if (osmandSettings.usingEnglishNames()) { try { <START> SpecialPhrases.setLanguage(this, new Locale("en")); <END> } catch (IOException e) { LOG.error("I/O exception", e); Toast error = Toast.makeText(this, "Error while reading the special phrases. Restart OsmAnd if possible", Toast.LENGTH_LONG); error.show(); } } else { try { SpecialPhrases.setLanguage(this, Locale.getDefault()); } catch (IOException e) { LOG.error("I/O exception", e); Toast error = Toast.makeText(this, "Error while reading the special phrases. Restart OsmAnd if possible", Toast.LENGTH_LONG); error.show(); } } progressDialog.setTitle(getString(R.string.loading_data)); progressDialog.setMessage(getString(R.string.reading_indexes)); activity.showDialog(PROGRESS_DIALOG); startDialog.setDialog(progressDialog); } else if (startingWarnings != null) { showWarnings(startingWarnings, activity); } } }</code><technical_language>Create like, SpecialPhrases.getLanguageLocal(osmandSettings) : Locale, osmandSettings.getSpecialPhrasesLanguage(), this reduce this duplication more readable</technical_language>

Target:
public void checkApplicationIsBeingInitialized(Activity activity, ProgressDialog progressDialog) { startApplication(); synchronized (OsmandApplication.this) { if (startDialog != null) { try { SpecialPhrases.setLanguage(this, osmandSettings); } catch (IOException e) { LOG.error("I/O exception", e); Toast error = Toast.makeText(this, "Error while reading the special phrases. Restart OsmAnd if possible", Toast.LENGTH_LONG); error.show(); } progressDialog.setTitle(getString(R.string.loading_data)); progressDialog.setMessage(getString(R.string.reading_indexes)); activity.showDialog(PROGRESS_DIALOG); startDialog.setDialog(progressDialog); } else if (startingWarnings != null) { showWarnings(startingWarnings, activity); } } }
Source:
<code>public Collection<Symptom> detect(Collection<Measurement> measurements) { Collection<Symptom> result = new ArrayList<>(); MeasurementsTable waitQueueMetrics = MeasurementsTable.of(measurements).type (METRIC_WAIT_Q_SIZE.text()); for (String component : waitQueueMetrics.uniqueComponents()) { <START> Set<String> addresses = new HashSet<>(); <END> double maxSlope = computeWaitQueueSizeTrend(waitQueueMetrics.component(component)); if (maxSlope > rateLimit) { LOG.info(String.format("Detected growing wait queues for %s, max rate %f", component, maxSlope)); addresses.add(component); result.add(new Symptom(SYMPTOM_GROWING_WAIT_Q.text(), context.checkpoint(), addresses)); } } return result; }</code><technical_language>new addresses put in if block</technical_language>

Target:
public Collection<Symptom> detect(Collection<Measurement> measurements) { Collection<Symptom> result = new ArrayList<>(); MeasurementsTable waitQueueMetrics = MeasurementsTable.of(measurements).type(METRIC_WAIT_Q_SIZE.text()); for (String component : waitQueueMetrics.uniqueComponents()) { double maxSlope = computeWaitQueueSizeTrend(waitQueueMetrics.component(component)); if (maxSlope > rateLimit) { LOG.info(String.format("Detected growing wait queues for %s, max rate %f", component, maxSlope)); Collection<String> addresses = Collections.singletonList(component); result.add(new Symptom(SYMPTOM_GROWING_WAIT_Q.text(), context.checkpoint(), addresses)); } } return result; }
Source:
<code>public void setup(Context.OperatorContext context) { this.timeIncrement = context.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT) * context.getValue(Context.DAGContext.STREAMING_WINDOW_SIZE_MILLIS); validate(); <START> windowStateMap.setup(context); <END> dataStorage.setup(context); if (retractionStorage != null) { retractionStorage.setup(context); } for (Component component : components.values()) { component.setup(context); } if (this.windowOption instanceof WindowOption.GlobalWindow) { windowStateMap.put(Window.GlobalWindow.getInstance(), new WindowState()); } }</code><technical_language>thinking if provide automatic call method set annotation field IoC frameworks do</technical_language>

Target:
public void setup(Context.OperatorContext context) { this.timeIncrement = context.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT) * context.getValue(Context.DAGContext.STREAMING_WINDOW_SIZE_MILLIS); validate(); windowStateMap.setup(context); dataStorage.setup(context); if (retractionStorage != null) { retractionStorage.setup(context); } for (Component component : components.values()) { component.setup(context); } if (this.windowOption instanceof WindowOption.GlobalWindow) { windowStateMap.put(Window.GlobalWindow.INSTANCE, new WindowState()); } }
Source:
<code>public Inventory parent() { <START> return this.parent == null ? this : this.parent(); <END> }</code><technical_language>return this.parent == null ? this : this.parent;</technical_language>

Target:
public Inventory parent() { return this.parent == null ? this : this.parent; }
Source:
<code>public Subscription(final String id, final DateTime createdAt, final DateTime updatedAt, final SubscriptionBase subscriptionBase) { <START> super(subscriptionBase, id); <END> this.id = id; this.createdAt = createdAt; this.updatedAt = updatedAt; }</code><technical_language>is this necessary</technical_language>

Target:
public Subscription(final String id, final DateTime createdAt, final DateTime updatedAt, final SubscriptionBase subscriptionBase) { super(subscriptionBase); this.id = id; this.createdAt = createdAt; this.updatedAt = updatedAt; }
Source:
<code><START> public FilterMessageTableModel getFilterMessageTableModel() { <END> return filterMessageTableModel; }</code><technical_language>worth leaving package accessible for now</technical_language>

Target:
FilterMessageTableModel getFilterMessageTableModel() { return filterMessageTableModel; }
Source:
<code>public void asyncLogContainerWithDetails() throws Exception { CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox") <START> .withCmd("--log-driver", "journald", "--log-opt", "env=ENV_VAR", "-e", "ENV_VAR=logtester.1234", "flyinprogrammer/logtester") <END> .exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerRule.getClient().startContainerCmd(container.getId()) .exec(); LogContainerTestCallback loggingCallback = new LogContainerTestCallback(true); dockerRule.getClient().logContainerCmd(container.getId()) .withStdErr(true) .withStdOut(true) .withDetails(true) .exec(loggingCallback); loggingCallback.awaitCompletion(3, TimeUnit.SECONDS); assertTrue(loggingCallback.toString().contains("ENV_VAR=logtester.1234")); }</code><technical_language>this work</technical_language>

Target:
public void asyncLogContainerWithDetails() throws Exception { HashMap<String, String> config = new HashMap<>(); config.put("env", "ENV_VAR"); LogConfig logConfig = new LogConfig(LogConfig.LoggingType.JOURNALD, config); CreateContainerResponse container = dockerRule.getClient().createContainerCmd("flyinprogrammer/logtester") .withEnv("ENV_VAR=logtester.1234") .withLogConfig(logConfig) .exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerRule.getClient().startContainerCmd(container.getId()) .exec(); LogContainerTestCallback loggingCallback = new LogContainerTestCallback(true); dockerRule.getClient().logContainerCmd(container.getId()) .withStdErr(true) .withStdOut(true) .withDetails(true) .exec(loggingCallback); loggingCallback.awaitCompletion(3, TimeUnit.SECONDS); assertTrue(loggingCallback.toString().contains("ENV_VAR=logtester.1234")); }
Source:
<code>private Artifact deploy(ArtifactoryBuildInfoClient client, File deployedFile, String extension) throws Exception { String artifactName = version + "." + extension; Map<String, String> checksums = FileChecksumCalculator.calculateChecksums(deployedFile, MD5, SHA1); DeployDetails deployDetails = new DeployDetails.Builder() .file(deployedFile) .targetRepository(deploymentRepo) .addProperties(properties) .artifactPath(moduleName + "/@v/" + artifactName) .md5(checksums.get(MD5)).sha1(checksums.get(SHA1)) .build(); <START> ArtifactoryUploadResponse response = ((ArtifactoryBuildInfoClient) client).deployArtifact(deployDetails); <END> Artifact deployedArtifact = new ArtifactBuilder(moduleName + ":" + artifactName) .md5(response.getChecksums().getMd5()) .sha1(response.getChecksums().getSha1()) .build(); return deployedArtifact; }</code><technical_language>suggestion ArtifactoryUploadResponse response = client.deployArtifact(deployDetails);</technical_language>

Target:
private Artifact deploy(ArtifactoryBuildInfoClient client, File deployedFile, String extension) throws Exception { String artifactName = version + "." + extension; Map<String, String> checksums = FileChecksumCalculator.calculateChecksums(deployedFile, MD5, SHA1); DeployDetails deployDetails = new DeployDetails.Builder() .file(deployedFile) .targetRepository(deploymentRepo) .addProperties(properties) .artifactPath(moduleName + "/@v/" + artifactName) .md5(checksums.get(MD5)).sha1(checksums.get(SHA1)) .build(); ArtifactoryUploadResponse response = client.deployArtifact(deployDetails); Artifact deployedArtifact = new ArtifactBuilder(moduleName + ":" + artifactName) .md5(response.getChecksums().getMd5()) .sha1(response.getChecksums().getSha1()) .build(); return deployedArtifact; }
Source:
<code>private static String insertUninitVar(String cmd){ <START> int randLength = ThreadLocalRandom.current().nextInt(1,11); <END> byte[] array = new byte[randLength+1]; array[0]='$'; for(int i=1;i<randLength+1;++i){ array[i]=(byte)ThreadLocalRandom.current().nextInt(97,123); } String generatedName = new String(array); StringBuffer res = new StringBuffer(cmd); for(int i=0;i<res.length();++i){ if(res.charAt(i)==' '||res.charAt(i)=='/'){ res.insert(i,generatedName); i+=randLength+1; } } return res.toString(); }</code><technical_language>For 2 cents 11 especially if inserted multiple times is knock length/size constraints. suggest nextint(1,2) here</technical_language>

Target:
private static String insertUninitVar(String cmd){ int varLength = ThreadLocalRandom.current().nextInt(1,3)+1; char[] array = new char[varLength]; array[0]='$'; for(int i=1;i<varLength;++i){ array[i]=(char)ThreadLocalRandom.current().nextInt(97,123); } String var = new String(array); return cmd.replaceAll("\\s",Matcher.quoteReplacement(var+" ")).replaceAll("\\/",Matcher.quoteReplacement(var+"/")); }
Source:
<code>public void testModifyOfExistingMacPool() throws Exception { final MacPoolPerDc pool = new MacPoolPerDc(); <START> MacPool macPool = createMacPool("00:00:00:00:00:01", "00:00:00:00:00:01"); <END> StoragePool dataCenter = createStoragePool(macPool); when(dbFacade.getAuditLogDao()).thenReturn(auditLogDao); mockStoragePool(dataCenter); mockGettingAllMacPools(macPool); pool.initialize(); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(macFrom), is(true)); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(macFrom), is(false)); pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(); try { pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(); Assert.fail("this allocation should not succeed."); } catch (VdcBLLException e) { } macPool.setAllowDuplicateMacAddresses(true); final MacRange macRange = new MacRange(); macRange.setMacFrom("00:00:00:00:00:01"); macRange.setMacTo("00:00:00:00:00:02"); macPool.setRanges(Collections.singletonList(macRange)); pool.modifyPool(macPool); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(macFrom), is(true)); assertThat(pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(), notNullValue()); }</code><technical_language>"00:00:00:00:00:01" extracted a local constant</technical_language>

Target:
public void testModifyOfExistingMacPool() throws Exception { final String macAddress1 = "00:00:00:00:00:01"; final String macAddress2 = "00:00:00:00:00:02"; MacPool macPool = createMacPool(macAddress1, macAddress1); StoragePool dataCenter = createStoragePool(macPool); mockStoragePool(dataCenter); mockGettingAllMacPools(macPool); pool.initialize(); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(MAC_FROM), is(true)); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(MAC_FROM), is(false)); assertThat(pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(), is(macAddress1)); try { pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(); Assert.fail("this allocation should not succeed."); } catch (VdcBLLException e) { } macPool.setAllowDuplicateMacAddresses(true); final MacRange macRange = new MacRange(); macRange.setMacFrom(macAddress1); macRange.setMacTo(macAddress2); macPool.setRanges(Collections.singletonList(macRange)); pool.modifyPool(macPool); assertThat(pool.poolForDataCenter(dataCenter.getId()).addMac(MAC_FROM), is(true)); assertThat(pool.poolForDataCenter(dataCenter.getId()).allocateNewMac(), is(macAddress2)); }
Source:
<code>protected AbstractConfigValue value() { if (Tokens.isValue(token)) return Tokens.getValue(token); else if (Tokens.isUnquotedText(token)) return new ConfigString.Unquoted(token.origin(), Tokens.getUnquotedText(token)); else if (Tokens.isSubstitution(token)) { List<Token> expression = Tokens.getSubstitutionPathExpression(token); Path path = PathParser.parsePathExpression(expression.iterator(), token.origin()); boolean optional = Tokens.getSubstitutionOptional(token); return new ConfigReference(token.origin(), new SubstitutionExpression(path, optional)); } <START> return null; <END> }</code><technical_language>suspicious of this null - happen? call a method return null valueOrNull for clarity, depending I if exception instead, what</technical_language>

Target:
protected AbstractConfigValue value() { if (Tokens.isValue(token)) return Tokens.getValue(token); else if (Tokens.isUnquotedText(token)) return new ConfigString.Unquoted(token.origin(), Tokens.getUnquotedText(token)); else if (Tokens.isSubstitution(token)) { List<Token> expression = Tokens.getSubstitutionPathExpression(token); Path path = PathParser.parsePathExpression(expression.iterator(), token.origin()); boolean optional = Tokens.getSubstitutionOptional(token); return new ConfigReference(token.origin(), new SubstitutionExpression(path, optional)); } throw new ConfigException.BugOrBroken("ConfigNodeSimpleValue did not contain a valid value token"); }
Source:
<code><START> public static String toUserAgentString(String applicationId, String sdkName, String sdkVersion, <END> Configuration configuration) { StringBuilder userAgentBuilder = new StringBuilder(); if (applicationId != null) { applicationId = applicationId.length() > 24 ? applicationId.substring(0, 24) : applicationId; userAgentBuilder.append(applicationId).append(" "); } userAgentBuilder.append(String.format(DEFAULT_USER_AGENT_FORMAT, sdkName, sdkVersion)); if (!isTelemetryDisabled(configuration)) { userAgentBuilder.append(" ") .append("(") .append(getPlatformInfo()) .append(")"); } return userAgentBuilder.toString(); }</code><technical_language>Thoughts offering this API begin? trivial add reduced parameter overloads remove shipped</technical_language>

Target:
public static String toUserAgentString(String applicationId, String sdkName, String sdkVersion, Configuration configuration) { StringBuilder userAgentBuilder = new StringBuilder(); if (applicationId != null) { applicationId = applicationId.length() > MAX_APP_ID_LENGTH ? applicationId.substring(0, MAX_APP_ID_LENGTH) : applicationId; userAgentBuilder.append(applicationId).append(" "); } userAgentBuilder.append(DEFAULT_USER_AGENT_HEADER) .append("-") .append(sdkName) .append("/") .append(sdkVersion); if (!isTelemetryDisabled(configuration)) { userAgentBuilder.append(" ") .append("(") .append(getPlatformInfo()) .append(")"); } return userAgentBuilder.toString(); }
Source:
<code>private void index(IndexWriter writer, Path inputFile) throws IOException { TopicLuceneDocumentGenerator transformer = new TopicLuceneDocumentGenerator(); transformer.config(args); transformer.setCounters(counters); int cnt = 0; ObjectTriplesIterator iter = new ObjectTriplesIterator(inputFile); while (iter.hasNext()) { ObjectTriples d = iter.next(); String subject = d.getSubject(); <START> Topic topic = new Topic(subject); <END> Map<String, List<String>> predicateValues = d.getPredicateValues(); for(Map.Entry<String, List<String>> entry: predicateValues.entrySet()) { String predicate = entry.getKey(); List<String> objects = entry.getValue(); for (String object : objects) topic.addPredicateAndValue(predicate, object); } Document doc = transformer.createDocument(topic); if (doc != null) { writer.addDocument(doc); cnt++; } if (cnt % 100000 == 0) { LOG.debug("Number of indexed entity document: {}", cnt); } doc = null; d = null; } iter.close(); LOG.info(inputFile.getParent().getFileName().toString() + File.separator + inputFile.getFileName().toString() + ": " + cnt + " docs added."); counters.indexedDocuments.addAndGet(cnt); }</code><technical_language>I remove ObjectTriples... Originally, I created a Map. modify ObjectTriplesIterator TopicIterator returns a Topic object .next() is called</technical_language>

Target:
private void index(IndexWriter writer, Path inputFile) throws IOException { TopicLuceneDocumentGenerator transformer = new TopicLuceneDocumentGenerator(); transformer.config(args); transformer.setCounters(counters); int cnt = 0; ObjectTriplesIterator iter = new ObjectTriplesIterator(inputFile); while (iter.hasNext()) { ObjectTriples d = iter.next(); Document doc = transformer.createDocument(d); if (doc != null) { writer.addDocument(doc); cnt++; } if (cnt % 100000 == 0) { LOG.debug("Number of indexed entity document: {}", cnt); } d = null; doc = null; } iter.close(); LOG.info(inputFile.getParent().getFileName().toString() + File.separator + inputFile.getFileName().toString() + ": " + cnt + " docs added."); counters.indexedDocuments.addAndGet(cnt); }
Source:
<code>public Response runComponentIntegration( @PathParam("componentId") @RequiredParam String componentId) { ComponentIntegration integration = service.getPersistenceService().findById(ComponentIntegration.class, componentId); if (integration != null) { <START> if (integration.getStatus().equals(RunStatus.WORKING)) { <END> JobManager.runComponentIntegrationNow(componentId, null); return Response.ok().build(); } return Response.status(Response.Status.NOT_MODIFIED).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } }</code><technical_language>I this working...as run if is currently working</technical_language>

Target:
public Response runComponentIntegration( @PathParam("componentId") @RequiredParam String componentId) { ComponentIntegration integration = service.getPersistenceService().findById(ComponentIntegration.class, componentId); if (integration != null) { if (integration.getActiveStatus().equals(ComponentIntegration.INACTIVE_STATUS)) { if (integration.getStatus().equals(RunStatus.WORKING)) { integration.setStatus(RunStatus.COMPLETE); service.getComponentService().saveComponentIntegration(integration); } return Response.status(Response.Status.NOT_MODIFIED).build(); } else { if (!integration.getStatus().equals(RunStatus.WORKING)) { JobManager.runComponentIntegrationNow(componentId, null); return Response.ok().build(); } return Response.status(Response.Status.NOT_MODIFIED).build(); } } else { return Response.status(Response.Status.NOT_FOUND).build(); } }
Source:
<code>static void move(File src, File dest) throws IOException { try { <START> Files.move(src.toPath(), dest.toPath()); <END> } catch (Exception x) { throw new IOException(x); } }</code><technical_language>catch IOException rethrow avoid wrapping IOException IOException</technical_language>

Target:
static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (IOException x) { throw x; } catch (Exception x) { throw new IOException(x); } }
Source:
<code>public void withoutForceSucceedsIn31Cluster() { validator = spy(new GlusterVolumeValidator()); ValidationResult result = validator.isForceCreateVolumeAllowed(Version.v3_1, false); <START> assertEquals(ValidationResult.VALID, result); <END> }</code><technical_language>project introduced ValidationResultMatchers class for validity assertion, preferred ? assertThat(result, isValid());</technical_language>

Target:
public void withoutForceSucceedsIn31Cluster() { validator = spy(new GlusterVolumeValidator()); ValidationResult result = validator.isForceCreateVolumeAllowed(Version.v3_1, false); assertThat(result, isValid()); }
Source:
<code>protected @Nullable ITmfTreeViewerEntry updateElements(ITmfTrace trace, long start, long end, boolean isSelection) { TmfAbstractAnalysisModule analysisModule = fModule; <START> <END> SegmentStoreStatisticsDataProvider provider = null; if (analysisModule instanceof AbstractSegmentStatisticsAnalysis && trace.equals(analysisModule.getTrace())) { AbstractSegmentStatisticsAnalysis module = (AbstractSegmentStatisticsAnalysis) analysisModule; provider = SegmentStoreStatisticsDataProvider.getOrCreate(trace, module); } if (provider == null) { provider = DataProviderManager.getInstance().getDataProvider(trace, fProviderId, SegmentStoreStatisticsDataProvider.class); } if (provider == null) { return null; } TmfModelResponse<List<SegmentStoreStatisticsModel>> response = provider.fetchTree(new FilterTimeQueryFilter(start, end, 2, isSelection), null); List<SegmentStoreStatisticsModel> model = response.getModel(); if (model == null) { return null; } return modelToTree(model); }</code><technical_language>scatter chart updates checks "new" first, falls legacy implementation. do order too</technical_language>

Target:
protected @Nullable ITmfTreeViewerEntry updateElements(ITmfTrace trace, long start, long end, boolean isSelection) { SegmentStoreStatisticsDataProvider provider = DataProviderManager.getInstance().getDataProvider(trace, fProviderId, SegmentStoreStatisticsDataProvider.class); TmfAbstractAnalysisModule analysisModule = fModule; if (provider == null && analysisModule instanceof AbstractSegmentStatisticsAnalysis && trace.equals(analysisModule.getTrace())) { AbstractSegmentStatisticsAnalysis module = (AbstractSegmentStatisticsAnalysis) analysisModule; provider = SegmentStoreStatisticsDataProvider.getOrCreate(trace, module); } if (provider == null) { return null; } FilterTimeQueryFilter filter = new FilterTimeQueryFilter(start, end, 2, isSelection); TmfModelResponse<List<SegmentStoreStatisticsModel>> response = provider.fetchTree(filter, null); List<SegmentStoreStatisticsModel> model = response.getModel(); if (model == null) { return null; } return modelToTree(model); }
Source:
<code>public Property sorted() { return property(arbPriorityQueueIntegerString, pq -> { List<P2<Integer, String>> expected = pq.toList().sort(Ord.p2Ord1(Ord.intOrd.reverse())); List<P2<Integer, String>> actual = pq.toList(); <START> assertThat(actual, equalTo(expected)); <END> return prop(actual.equals(expected)); }); }</code><technical_language>assert removed tested property</technical_language>

Target:
public Property sorted() { return property(arbPriorityQueueIntegerString, pq -> { List<P2<Integer, String>> expected = pq.toList().sort(Ord.p2Ord1(Ord.intOrd.reverse())); List<P2<Integer, String>> actual = pq.toList(); return prop(actual.equals(expected)); }); }
Source:
<code>public void addExceptionalYield(SymbolicValue target, ProgramState exceptionalState, String exceptionFullyQualifiedName, SECheck check) { if (isPartOfMethodParameters(target)) { Type exceptionType = semanticModel.getClassType(exceptionFullyQualifiedName); ProgramState newExceptionalState = exceptionalState.clearStack().stackValue(constraintManager.createExceptionalSymbolicValue(exceptionType)); <START> int sizeBeforeEnqueue = workList.size(); <END> enqueueExceptionalPaths(newExceptionalState); int nbNewNode = workList.size() - sizeBeforeEnqueue; for (int i = 0; i < nbNewNode; i++) { ExplodedGraph.Node workListFirstNode = workList.peekFirst(); if (workListFirstNode.programState.equals(newExceptionalState) && workListFirstNode.programPoint.block.isMethodExitBlock()) { methodBehavior.createExceptionalCheckBasedYield(workListFirstNode, exceptionType, check); } workList.pop(); } } }</code><technical_language>This required if rely explodedGrah.getNode method</technical_language>

Target:
public void addExceptionalYield(SymbolicValue target, ProgramState exceptionalState, String exceptionFullyQualifiedName, SECheck check) { if (methodBehavior != null && methodBehavior.parameters().contains(target)) { Type exceptionType = semanticModel.getClassType(exceptionFullyQualifiedName); ProgramState newExceptionalState = exceptionalState.clearStack().stackValue(constraintManager.createExceptionalSymbolicValue(exceptionType)); ExplodedGraph.Node exitNode = explodedGraph.node(node.programPoint, newExceptionalState); methodBehavior.createExceptionalCheckBasedYield(exitNode, exceptionType, check); } }
Source:
<code>private Resource constructResources(Model model, Element aggregateEl, List<Element> topChildren, METSHelper helper) { if (topChildren.size() == 1) { Resource rootResource = model.createResource(METSHelper.getPIDURI(topChildren.get(0))); model.add(rootResource, RDF.type, Cdr.FileObject); helper.addFileAssociations(model, true); String location = rootResource.getProperty(CdrDeposit.stagingLocation).getString(); String filename = location.substring("data/".length()).toLowerCase(); model.add(rootResource, CdrDeposit.label, filename); return rootResource; } Bag rootObject = model.createBag(METSHelper.getPIDURI(aggregateEl)); <START> model.add(rootObject, RDF.type, Cdr.Folder); <END> model.add(rootObject, RDF.type, Cdr.Work); for (Element childEl : topChildren) { Resource child = model.createResource(METSHelper.getPIDURI(childEl)); rootObject.add(child); } helper.addFileAssociations(model, true); NodeIterator children = rootObject.iterator(); try { while (children.hasNext()) { Resource child = children.nextNode().asResource(); String location = child.getProperty(CdrDeposit.stagingLocation).getString(); String filename = location.substring("data/".length()).toLowerCase(); model.add(child, CdrDeposit.label, filename); } } finally { children.close(); } return rootObject; }</code><technical_language>Remove Cdr.Folder assignment. In previous model Aggregate identified Container Aggregate content models, while in new model a Work is a Work</technical_language>

Target:
private Resource constructResources(Model model, Element aggregateEl, List<Element> topChildren, METSHelper helper) { if (topChildren.size() == 1) { Resource rootResource = model.createResource(METSHelper.getPIDURI(topChildren.get(0))); model.add(rootResource, RDF.type, Cdr.FileObject); helper.addFileAssociations(model, true); String location = rootResource.getProperty(CdrDeposit.stagingLocation).getString(); String filename = location.substring("data/".length()).toLowerCase(); model.add(rootResource, CdrDeposit.label, filename); return rootResource; } Bag rootObject = model.createBag(METSHelper.getPIDURI(aggregateEl)); model.add(rootObject, RDF.type, Cdr.Work); for (Element childEl : topChildren) { Resource child = model.createResource(METSHelper.getPIDURI(childEl)); rootObject.add(child); } helper.addFileAssociations(model, true); NodeIterator children = rootObject.iterator(); try { while (children.hasNext()) { Resource child = children.nextNode().asResource(); String location = child.getProperty(CdrDeposit.stagingLocation).getString(); String filename = location.substring("data/".length()).toLowerCase(); model.add(child, CdrDeposit.label, filename); } } finally { children.close(); } return rootObject; }
Source:
<code>private void loadExistingEntries() { List<SubscriptionName> subscriptions = subscriptionsCache.listActiveSubscriptionNames(); int loadedMaxRates = 0; for (SubscriptionName subscriptionName : subscriptions) { try { List<String> assignedConsumers = consumersInRegistry(subscriptionName); if (setInitialMaxRates(subscriptionName, assignedConsumers)) { loadedMaxRates++; } } catch (Exception e) { logger.warn("Exception occurred when initializing cache for subscription {}", subscriptionName, e); } } <START> ; <END> logger.info("Loaded max-rates of out of subscriptions", loadedMaxRates, subscriptions.size()); }</code><technical_language>Leftover</technical_language>

Target:
private void loadExistingEntries() { List<SubscriptionName> subscriptions = subscriptionsCache.listActiveSubscriptionNames(); int loadedMaxRates = 0; for (SubscriptionName subscriptionName : subscriptions) { try { List<String> assignedConsumers = consumersInRegistry(subscriptionName); if (setInitialMaxRates(subscriptionName, assignedConsumers)) { loadedMaxRates++; } } catch (Exception e) { logger.warn("Exception occurred when initializing cache for subscription {}", subscriptionName, e); } } logger.info("Loaded max-rates of out of subscriptions", loadedMaxRates, subscriptions.size()); }
Source:
<code>public Repo<Master> call(long tid, Master master) throws Exception { Utils.getIdLock().lock(); try { tableInfo <START> .setTableId(Utils.getNextId(tableInfo.getTableName(), master.getContext(), Table.ID::of)); <END> return new SetupPermissions(tableInfo); } finally { Utils.getIdLock().unlock(); } }</code><technical_language>This autoformat'ed put a line break else</technical_language>

Target:
public Repo<Master> call(long tid, Master master) throws Exception { Utils.getIdLock().lock(); try { String tName = tableInfo.getTableName(); tableInfo.setTableId(Utils.getNextId(tName, master.getContext(), Table.ID::of)); return new SetupPermissions(tableInfo); } finally { Utils.getIdLock().unlock(); } }
Source:
<code>public BinaryContent transform(Metacard metacard, Map<String, Serializable> map) throws CatalogTransformerException { if (metacard == null) { throw new CatalogTransformerException("Null metacard cannot be transformed to HTML"); } List<HtmlMetacardModel> metacardModelList = new ArrayList<>(); metacardModelList.add(new HtmlMetacardModel(metacard, getCategoryList())); String html = buildHtml(metacardModelList); if (html == null) { throw new CatalogTransformerException("Metacard cannot be transformed to HTML"); } else { <START> return new BinaryContentImpl(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8))); <END> } }</code><technical_language>two-arg constructor include mime-type</technical_language>

Target:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> map) throws CatalogTransformerException { if (metacard == null) { throw new CatalogTransformerException("Null metacard cannot be transformed to HTML"); } List<HtmlExportCategory> categoryList = HtmlMetacardUtility.sortCategoryList(htmlMetacardUtility.getCategoryList()); List<HtmlMetacardModel> metacardModelList = new ArrayList<>(); metacardModelList.add(new HtmlMetacardModel(metacard, categoryList)); String html = htmlMetacardUtility.buildHtml(metacardModelList); if (StringUtils.isEmpty(html)) { throw new CatalogTransformerException("Metacard cannot be transformed to HTML"); } return new BinaryContentImpl( new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), htmlMetacardUtility.getMimeType()); }