auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void validateClusterName(String clusterName) { if (clusterName == null) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be null"); } if (clusterName.isEmpty()) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be empty"); } <START> Pattern clusterNamePtrn = Pattern.compile(CLUSTER_NAME_VALIDATION_REGEXP); <END> Matcher mtch = clusterNamePtrn.matcher(clusterName); if(!mtch.matches()){ throw new IllegalArgumentException("Invalid arguments, cluster name should contains only alphabetical, numeric, '_' and '-' characters and length 1-100 characters"); } }</code><technical_language>recompile this, compile this a static final property</technical_language>

Target:
public static void validateClusterName(String clusterName) { if (clusterName == null) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be null"); } if (clusterName.isEmpty()) { throw new IllegalArgumentException("Invalid arguments, cluster name should not be empty"); } Matcher mtch = CLUSTER_NAME_PTRN.matcher(clusterName); if(!mtch.matches()){ throw new IllegalArgumentException("Invalid arguments, cluster name should contains only alphabetical, numeric, '_' and '-' characters and length 1-100 characters"); } }
Source:
<code>public String getVendor() { if (_vendor == null) { int[] mib = { SystemB.CTL_MACHDEP, SystemB.MACHDEP_CPU, SystemB.MACHDEP_CPU_VENDOR }; IntByReference size = new IntByReference(100); Pointer p = new Memory(size.getValue()); <START> SystemB.INSTANCE.sysctl(mib, mib.length, p, size, null, 0); <END> _vendor = p.getString(0); } return _vendor; }</code><technical_language>this fail</technical_language>

Target:
public String getVendor() { if (_vendor == null) { int[] mib = { SystemB.CTL_MACHDEP, SystemB.MACHDEP_CPU, SystemB.MACHDEP_CPU_VENDOR }; IntByReference size = new IntByReference(); if (0 != SystemB.INSTANCE.sysctl(mib, mib.length, null, size, null, 0)) throw new LastErrorException("Error code: " + Native.getLastError()); Pointer p = new Memory(size.getValue() + 1); if (0 != SystemB.INSTANCE.sysctl(mib, mib.length, p, size, null, 0)) throw new LastErrorException("Error code: " + Native.getLastError()); _vendor = p.getString(0); } return _vendor; }
Source:
<code>public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (final DockerRequestException ex) { switch (ex.status()) { case 406: <START> throw new DockerException("Server not part of swarm.", ex); <END> case 409: throw new ConflictException("Name conflicts with an existing object.", ex); default: throw ex; } } }</code><technical_language>this a new Exception class</technical_language>

Target:
public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (final DockerRequestException ex) { switch (ex.status()) { case 406: throw new NonSwarmNodeException("Server not part of swarm.", ex); case 409: throw new ConflictException("Name conflicts with an existing object.", ex); default: throw ex; } } }
Source:
<code>private Schema.Builder loadSchemaObject(JsonObject o) { Schema.Builder builder; if (ls.schemaJson().containsKey("enum")) { builder = buildEnumSchema(); } else if (ls.schemaJson().containsKey("const") && (config.specVersion != DRAFT_4)) { builder = buildConstSchema(); <START> } else if (config.specVersion.compareTo(DRAFT_6) > 0 && schemaHasAnyOf(CONDITIONAL_SCHEMA_KEYWORDS)) { <END> builder = buildConditionalSchema(); } else { builder = new CombinedSchemaLoader(ls, this).load() .orElseGet(() -> { if (!ls.schemaJson().containsKey("type") || ls.schemaJson().containsKey("$ref")) { return buildSchemaWithoutExplicitType(); } else { return loadForType(ls.schemaJson().require("type")); } }); } loadCommonSchemaProperties(builder); return builder; }</code><technical_language>move #sniffSchemaByProps() somehow</technical_language>

Target:
private Schema.Builder loadSchemaObject(JsonObject o) { Schema.Builder builder; if (ls.schemaJson().containsKey("enum")) { builder = buildEnumSchema(); } else if (ls.schemaJson().containsKey("const") && (config.specVersion != DRAFT_4)) { builder = buildConstSchema(); } else { builder = new CombinedSchemaLoader(ls, this).load() .orElseGet(() -> { if (!ls.schemaJson().containsKey("type") || ls.schemaJson().containsKey("$ref")) { return buildSchemaWithoutExplicitType(); } else { return loadForType(ls.schemaJson().require("type")); } }); } loadCommonSchemaProperties(builder); return builder; }
Source:
<code>private int getNewTaskCount() { if (scheduledNodes.isEmpty()) { return 1; } double fullTasks = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .map(TaskStatus::isOutputBufferOverutilized) .mapToDouble(full -> full ? 1.0 : 0.0) .average().orElse(0.0); long writtenBytes = writerTasksProvider.get().stream() .map(TaskStatus::getPhysicalWrittenDataSize) .mapToLong(DataSize::toBytes) .sum(); <START> if ((fullTasks >= 0.5) && (writtenBytes >= (writerMinSizeBytes * scheduledNodes.size()))) { <END> return 1; } if (optimizedScaleWriterProducerBuffer) { double totalProducerBufferUtilization = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .mapToDouble(TaskStatus::getOutputBufferUtilization) .sum(); if (noMoreTaskScheduledRoundCount >= SCHEDULED_ROUND_REQUIRED_FOR_EQUILIBRIUM && totalProducerBufferUtilization >= scheduledNodes.size() * MAX_PRODUCER_BUFFER_UTILIZATION_TO_CONSUMER_RATIO && writtenBytes >= writerMinSizeBytes * scheduledNodes.size()) { return 1; } } return 0; }</code><technical_language>a bit confused this loging. I thinking more changing condition if 50% overutilized 90% empty - add more writer. Thoughts</technical_language>

Target:
private int getNewTaskCount() { if (scheduledNodes.isEmpty()) { return 1; } double fullTasks = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .map(TaskStatus::isOutputBufferOverutilized) .mapToDouble(full -> full ? 1.0 : 0.0) .average().orElse(0.0); long writtenBytes = writerTasksProvider.get().stream() .map(TaskStatus::getPhysicalWrittenDataSize) .mapToLong(DataSize::toBytes) .sum(); if ((fullTasks >= 0.5) && (writtenBytes >= (writerMinSizeBytes * scheduledNodes.size()))) { return 1; } if (optimizedScaleWriterProducerBuffer) { double totalProducerBufferUtilization = sourceTasksProvider.get().stream() .filter(task -> !task.getState().isDone()) .mapToDouble(TaskStatus::getOutputBufferUtilization) .sum(); if (totalProducerBufferUtilization >= scheduledNodes.size() && writtenBytes >= writerMinSizeBytes * scheduledNodes.size()) { return 1; } } return 0; }
Source:
<code>public String getPropertyValue(String property){ String paramProperty = getParamProperty(property); if (!item.containsKey(paramProperty)) return null; Object value = item.get(paramProperty); if (value instanceof List<?>) { List<?> values = (List<?>)value; if (values.size() == 0) return null; String paramPropertyIndex = getPropertyValue(paramProperty + "id"); int propertyIndex = 0; <START> if (!StringUtils.isEmpty(paramPropertyIndex)) { <END> try { propertyIndex = Integer.parseInt(paramPropertyIndex); } catch (NumberFormatException e) { return null; } if (propertyIndex < 0 || propertyIndex >= values.size()) return null; } value = values.get(propertyIndex); } if (value == null) return null; return value.toString(); }</code><technical_language>fine Marcel - I do differently is explicit check for a missing paramPropertyIndex return element in array - is obvious reading code in this case if is a missing indexer return item. Minor refactoring tho, fine otherwise</technical_language>

Target:
public String getPropertyValue(String property){ String paramProperty = getParamProperty(property); if (!item.containsKey(paramProperty)) return null; Object value = item.get(paramProperty); if (value instanceof List<?>) { List<?> values = (List<?>)value; if (values.size() == 0) return null; String paramPropertyIndex = getPropertyValue(paramProperty + "id"); int propertyIndex; if (!StringUtils.isEmpty(paramPropertyIndex)) { try { propertyIndex = Integer.parseInt(paramPropertyIndex); } catch (NumberFormatException e) { return null; } if (propertyIndex < 0 || propertyIndex >= values.size()) return null; } else { propertyIndex = 0; } value = values.get(propertyIndex); } if (value == null) return null; return value.toString(); }
Source:
<code>public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); <START> Search.getFullTextEntityManager(em).flushToIndexes(); <END> }</code><technical_language>is need flush</technical_language>

Target:
public void indexMembers() throws InterruptedException { MassIndexer mi = Search.getFullTextEntityManager(em).createIndexer(Member.class); mi.startAndWait(); }
Source:
<code>private boolean hasAcceptMessagePropertyEnabled(XmlCheckContext context, Node bean) { <START> return hasAttributeValue(bean, "p:acceptMessagesWhileStopping") <END> || hasPropertyAsChild(context, bean, acceptMessageWhileStoppingPropertyExpression); }</code><technical_language>Namespace prefix 'p:' hard coded. This generate some false positives if namespace definition 'p:', for example: xml <beans xmlns:x="<LINK_0>"> <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer" x:acceptMessagesWhileStopping="true"></bean> </beans></technical_language>

Target:
private boolean hasAcceptMessagePropertyEnabled(XmlCheckContext context, Node bean) { return hasAttributeValue(bean, "acceptMessagesWhileStopping") || hasPropertyAsChild(context, bean, acceptMessageWhileStoppingPropertyExpression); }
Source:
<code>public List<? extends Certificate> getCertificateChain() { if (!isSecured()) { return null; <START> } else { <END> HttpsURLConnection conn = null; final List<X509Certificate> chain = new ArrayList<X509Certificate>(); try { SSLContext ctx; ctx = SSLContext.getInstance(SSL_PROTOCOL); ctx.init( null, new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } public void checkClientTrusted( X509Certificate[] certs, String authType ) { } public void checkServerTrusted( X509Certificate[] certs, String authType ) { for (X509Certificate cert : certs) { chain.add(cert); } } } }, null ); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.connect(); return chain; } catch (SSLHandshakeException e) { return chain; } catch (NoSuchAlgorithmException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } catch (KeyManagementException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } catch (IOException e) { handleException(VdcBllErrors.PROVIDER_FAILURE, e); } finally { if (conn != null) { conn.disconnect(); } } } return null; }</code><technical_language>remove else returned a value</technical_language>

Target:
public List<? extends Certificate> getCertificateChain() { if (!isSecured()) { return null; } HttpsURLConnection conn = null; final List<X509Certificate> chain = new ArrayList<X509Certificate>(); try { SSLContext ctx; ctx = SSLContext.getInstance(SSL_PROTOCOL); ctx.init(null, createTrustManager(chain), null); conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.connect(); return chain; } catch (SSLHandshakeException e) { return chain; } catch (NoSuchAlgorithmException e) { handleException(e); } catch (KeyManagementException e) { handleException(e); } catch (IOException e) { handleException(e); } finally { if (conn != null) { conn.disconnect(); } } return null; }
Source:
<code>public void closeJob(GeneralSecurityException gse) { <START> callback.onCompletion(new DecryptJobResult(blobId, null, null), gse); <END> }</code><technical_language>result null</technical_language>

Target:
public void closeJob(GeneralSecurityException gse) { callback.onCompletion(null, gse); }
Source:
<code>public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean hasSelection = (getSelectedItemPosition() >= 0); menu.findItem(MENU_ADD).setVisible(true); menu.findItem(MENU_EDIT).setVisible(hasSelection); menu.findItem(MENU_DELETE).setVisible(hasSelection); menu.findItem(MENU_DIAL).setVisible(hasSelection && <START> carrierConfig.getBoolean("config_fdn_direct_dial")); <END> return true; }</code><technical_language>In line 151, is call. define this method avoid duplication of code? e.g. private boolean isFdnDirectDialSupported()</technical_language>

Target:
public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean hasSelection = (getSelectedItemPosition() >= 0); menu.findItem(MENU_ADD).setVisible(true); menu.findItem(MENU_EDIT).setVisible(hasSelection); menu.findItem(MENU_DELETE).setVisible(hasSelection); menu.findItem(MENU_DIAL).setVisible(hasSelection && mFdnDialDirectlySupported); return true; }
Source:
<code>private boolean needToCheckIndentation(Element element) { if (element.getChildNodes().getLength() > 1) { return true; } Node previous = element.getPreviousSibling(); if (isNonEmptyTextNode(previous)) { return false; } Node next = element.getNextSibling(); if (isNonEmptyTextNode(next)) { return false; } for (Node parent = element.getParentNode(); parent != null && parent.getChildNodes().getLength() == 1; parent = parent.getParentNode()) { short parentType = parent.getNodeType(); if (parentType == Node.ELEMENT_NODE) { Node parentPrev = parent.getPreviousSibling(); <START> if (null != parentPrev && parentPrev.getNodeType() == Node.TEXT_NODE) { <END> String text = parentPrev.getTextContent(); text = text.trim(); if (!text.isEmpty()) { return false; } } } } return true; }</code><technical_language>reusing isNonEmptyTextNode() method? simplify this part a lot: java if (isNonEmptyTextNode(parent.getPreviousSibling())) { return false; }</technical_language>

Target:
private static boolean needToCheckIndentation(Element element) { if (element.getChildNodes().getLength() > 1) { return true; } Node previous = element.getPreviousSibling(); if (isNonEmptyTextNode(previous)) { return false; } Node next = element.getNextSibling(); if (isNonEmptyTextNode(next)) { return false; } for (Node parent = element.getParentNode(); parent != null && parent.getChildNodes().getLength() == 1; parent = parent.getParentNode()) { short parentType = parent.getNodeType(); if (parentType == Node.ELEMENT_NODE && isNonEmptyTextNode(parent.getPreviousSibling())) { return false; } } return true; }
Source:
<code>public void addNewComment(@NonNull DiscussionComment parent) { String parentId = parent.getIdentifier(); <START> if (!TextUtils.isEmpty(parentId)) { <END> for (DiscussionComment response : discussionResponses) { if (parentId.equals(response.getIdentifier())) { response.setChildCount(response.getChildCount() + 1); notifyDataSetChanged(); break; } } } }</code><technical_language>I need validate identifier this point. validation performed time of deserialization</technical_language>

Target:
public void addNewComment(@NonNull DiscussionComment parent) { String parentId = parent.getIdentifier(); for (DiscussionComment response : discussionResponses) { if (parentId.equals(response.getIdentifier())) { response.incrementChildCount(); notifyDataSetChanged(); break; } } }
Source:
<code>public boolean commitCursor(final String subscriptionId, final String eventType, final Cursor cursor) throws ServiceUnavailableException, NoSuchSubscriptionException { final String offsetPath = format("/nakadi/subscriptions/{0}/topics/{1}/{2}/offset", subscriptionId, eventType, cursor.getPartition()); try { return runLocked(() -> { final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET); if (topicRepository.compareOffsets(cursor.getOffset(), currentOffset) > 0) { zkHolder.get().setData().forPath(offsetPath, cursor.getOffset().getBytes(CHARSET)); return true; } else { return false; } }, zkLockFactory.createLock(offsetPath)); } catch (Exception e) { throw new ServiceUnavailableException("Error communicating with zookeeper", e); <START> } <END> }</code><technical_language>exception compareOffsets is eaten here. User able</technical_language>

Target:
private boolean commitCursor(final String subscriptionId, final String eventType, final Cursor cursor) throws ServiceUnavailableException, NoSuchSubscriptionException, InvalidCursorException { final String offsetPath = format("/nakadi/subscriptions/{0}/topics/{1}/{2}/offset", subscriptionId, eventType, cursor.getPartition()); try { return runLocked(() -> { final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET); if (topicRepository.compareOffsets(cursor.getOffset(), currentOffset) > 0) { zkHolder.get().setData().forPath(offsetPath, cursor.getOffset().getBytes(CHARSET)); return true; } else { return false; } }, zkLockFactory.createLock(offsetPath)); } catch (final IllegalArgumentException e) { throw new InvalidCursorException(CursorError.INVALID_FORMAT, cursor); } catch (Exception e) { throw new ServiceUnavailableException("Error communicating with zookeeper", e); } }
Source:
<code>public void deleteActionDefinition() throws Exception { respondWith(204); <START> HttpResponse resp = service.delete("concat"); <END> assertEquals(resp.getStatus(), 204); }</code><technical_language>ActionResponse instead of HttpResponse</technical_language>

Target:
public void deleteActionDefinition() throws Exception { respondWith(204); ActionResponse resp = service.delete("concat"); assertEquals(resp.getCode(), 200); }
Source:
<code>public Configuration getConfiguration(GraphContext context) { ConditionBuilder applicationProjectModelsFound = Query .fromType(WindupConfigurationModel.class); AbstractIterationOperation<WindupConfigurationModel> addApplicationReport = new AbstractIterationOperation<WindupConfigurationModel>() { @Override public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { for (FileModel inputPath : payload.getInputPaths()) { ProjectModel projectModel = inputPath.getProjectModel(); if (projectModel == null) { throw new WindupException("Error, no project found in: " + inputPath.getFilePath()); } createReport(event.getGraphContext(), projectModel); } } @Override public String toString() { <START> return "CreateJavaApplicationOverviewReport"; <END> } }; return ConfigurationBuilder.begin() .addRule() .when(applicationProjectModelsFound) .perform(addApplicationReport); }</code><technical_language>This left-over copy-paste</technical_language>

Target:
public Configuration getConfiguration(GraphContext context) { ConditionBuilder applicationProjectModelsFound = Query .fromType(WindupConfigurationModel.class); AbstractIterationOperation<WindupConfigurationModel> addApplicationReport = new AbstractIterationOperation<WindupConfigurationModel>() { @Override public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { for (FileModel inputPath : payload.getInputPaths()) { ProjectModel projectModel = inputPath.getProjectModel(); if (projectModel == null) { throw new WindupException("Error, no project found in: " + inputPath.getFilePath()); } createReport(event.getGraphContext(), projectModel); } } @Override public String toString() { return "CreatePotentialIssuesReportRuleProvider"; } }; return ConfigurationBuilder.begin() .addRule() .when(applicationProjectModelsFound) .perform(addApplicationReport); }
Source:
<code>public static boolean checkImageConfiguration(storage_domain_static storageDomain, DiskImageBase diskInfo, List<String> messages, boolean isCopyCollapse) { boolean result = true; if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW) <START> || !isCopyCollapse && isVolTypeAndFormatSupportedByBlockDevice(storageDomain, diskInfo) <END> || (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) { result = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString()); } return result; }</code><technical_language>I && takes precedence ||, adding brackets improve readability here</technical_language>

Target:
public static boolean checkImageConfiguration(storage_domain_static storageDomain, DiskImageBase diskInfo, List<String> messages, boolean isCopyCollapse) { boolean result = true; if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW) || (!isCopyCollapse && isVolTypeAndFormatSupportedByBlockDevice(storageDomain, diskInfo)) || (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) { result = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString()); } return result; }
Source:
<code>private void backupConfig(File backupDir) throws IOException { String configDirectory = systemEnvironment.getConfigDir(); <START> try (ZipOutputStream configZip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File(backupDir, CONFIG_BACKUP_ZIP))));) { <END> File cruiseConfigFile = new File(systemEnvironment.getCruiseConfigFile()); File cipherFile = systemEnvironment.getCipherFile(); new DirectoryStructureWalker(configDirectory, configZip, cruiseConfigFile, cipherFile).walk(); configZip.putNextEntry(new ZipEntry(cruiseConfigFile.getName())); IOUtils.write(goConfigService.xml(), configZip); configZip.putNextEntry(new ZipEntry(cipherFile.getName())); IOUtils.write(new CipherProvider(systemEnvironment).getKey(), configZip); } }</code><technical_language>semi-colon is unnecessary. :)</technical_language>

Target:
private void backupConfig(File backupDir) throws IOException { String configDirectory = systemEnvironment.getConfigDir(); try (ZipOutputStream configZip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File(backupDir, CONFIG_BACKUP_ZIP))))) { File cruiseConfigFile = new File(systemEnvironment.getCruiseConfigFile()); File cipherFile = systemEnvironment.getCipherFile(); new DirectoryStructureWalker(configDirectory, configZip, cruiseConfigFile, cipherFile).walk(); configZip.putNextEntry(new ZipEntry(cruiseConfigFile.getName())); IOUtils.write(goConfigService.xml(), configZip); configZip.putNextEntry(new ZipEntry(cipherFile.getName())); IOUtils.write(new CipherProvider(systemEnvironment).getKey(), configZip); } }
Source:
<code>private HttpHost getHttpProxy(OMElement profile, String targetHosts) throws AxisFault { String proxyHost; String proxyPortStr; QName proxyHostQName = new QName("proxyHost"); QName proxyPortQName = new QName("proxyPort"); OMElement proxyHostEle = profile.getFirstChildWithName(proxyHostQName); if (proxyHostEle != null) { proxyHost = proxyHostEle.getText(); OMElement proxyPortEle = profile.getFirstChildWithName(proxyPortQName); if (proxyPortEle != null) { proxyPortStr = proxyPortEle.getText(); } else { <START> throw new AxisFault("Proxy Port didn't configure correctly in proxy profile ["+targetHosts+"]"); <END> } } else { throw new AxisFault("Proxy Host didn't configure correctly in proxy profile ["+targetHosts+"]"); } int proxyPort = Integer.parseInt(proxyPortStr); return new HttpHost(proxyHost, proxyPort >= 0 ? proxyPort : 80); }</code><technical_language>Code formatting issues</technical_language>

Target:
private HttpHost getHttpProxy(OMElement profile, String targetHosts) throws AxisFault { String proxyHost; String proxyPortStr; OMElement proxyHostEle = profile.getFirstChildWithName(Q_PROXY_HOST); if (proxyHostEle != null) { proxyHost = proxyHostEle.getText(); OMElement proxyPortEle = profile.getFirstChildWithName(Q_PROXY_PORT); if (proxyPortEle != null) { proxyPortStr = proxyPortEle.getText(); } else { throw new AxisFault("Proxy Port didn't configure correctly in proxy profile [" + targetHosts + "]"); } } else { throw new AxisFault("Proxy Host didn't configure correctly in proxy profile [" + targetHosts + "]"); } int proxyPort = Integer.parseInt(proxyPortStr); return new HttpHost(proxyHost, proxyPort >= 0 ? proxyPort : 80); }
Source:
<code>private Predicate<? super Node<E>> is(final E element) { return new Predicate<Node<E>>() { public boolean apply(Node<E> input) { <START> return input != null && element != null && element.equals(input.getElement()); <END> } }; }</code><technical_language>input != null && input.getElement().equals(element) is sufficient Node constructor refuses null elements</technical_language>

Target:
private Predicate<? super Node<E>> is(final E element) { return new Predicate<Node<E>>() { public boolean apply(Node<E> input) { return input != null && input.getElement().equals(element); } }; }
Source:
<code>public static void assertResult(TupleQueryResult result, Matcher<BindingSet>... bindingMatchers) { int position = 0; try { for (Matcher<BindingSet> bindingMatcher : bindingMatchers) { position++; assertTrue("There should be at least " + position + " results", result.hasNext()); BindingSet bs = result.next(); assertThat(bs, bindingMatcher); <START> System.out.println("#"+position+" "+bs); <END> } assertFalse("There should be no more than " + position + " result", result.hasNext()); result.close(); } catch (QueryEvaluationException e) { throw new RuntimeException(e); } finally { try { while (result.hasNext()) { position++; BindingSet bs = result.next(); System.out.println("#"+position+" "+bs); } } catch (QueryEvaluationException e) { e.printStackTrace(); } } }</code><technical_language>This here, debug output</technical_language>

Target:
public static void assertResult(TupleQueryResult result, Matcher<BindingSet>... bindingMatchers) { try { int position = 0; for (Matcher<BindingSet> bindingMatcher : bindingMatchers) { position++; assertTrue("There should be at least " + position + " results", result.hasNext()); assertThat(result.next(), bindingMatcher); } assertFalse("There should be no more than " + position + " result", result.hasNext()); result.close(); } catch (QueryEvaluationException e) { throw new RuntimeException(e); } }
Source:
<code>public void compileInMemoryJarfile(InMemoryJarfile jarfile) throws IOException { List<VoltCompilerReader> ddlReaderList = new ArrayList<>(); Entry<String, byte[]> entry = jarfile.firstEntry(); while (entry != null) { String path = entry.getKey(); if (path.toLowerCase().endsWith(".sql")) { ddlReaderList.add(new VoltCompilerJarFileReader(jarfile, path)); compilerLog.trace("Added SQL file from jarfile to compilation: " + path); } entry = jarfile.higherEntry(entry.getKey()); } ClassLoader originalClassLoader = m_classLoader; try { m_classLoader = jarfile.getLoader(); <START> InMemoryJarfile jarOut = compileInternal(null, null, ddlReaderList, jarfile, false); <END> if (jarOut != null) { compilerLog.debug("Successfully recompiled InMemoryJarfile"); } else { String errString = "Adhoc DDL failed"; if (m_errors.size() > 0) { errString = m_errors.get(m_errors.size() - 1).getLogString(); } int fronttrim = errString.indexOf("DDL Error"); if (fronttrim < 0) { fronttrim = 0; } int endtrim = errString.indexOf(" in statement starting"); if (endtrim < 0) { endtrim = errString.length(); } String trimmed = errString.substring(fronttrim, endtrim); throw new IOException(trimmed); } } finally { m_classLoader = originalClassLoader; } }</code><technical_language>add version of compile methods flag calls in default false</technical_language>

Target:
public void compileInMemoryJarfile(InMemoryJarfile jarfile) throws IOException { List<VoltCompilerReader> ddlReaderList = new ArrayList<>(); Entry<String, byte[]> entry = jarfile.firstEntry(); while (entry != null) { String path = entry.getKey(); if (path.toLowerCase().endsWith(".sql")) { ddlReaderList.add(new VoltCompilerJarFileReader(jarfile, path)); compilerLog.trace("Added SQL file from jarfile to compilation: " + path); } entry = jarfile.higherEntry(entry.getKey()); } ClassLoader originalClassLoader = m_classLoader; try { m_classLoader = jarfile.getLoader(); InMemoryJarfile jarOut = compileInternal(null, null, ddlReaderList, jarfile); if (jarOut != null) { compilerLog.debug("Successfully recompiled InMemoryJarfile"); } else { String errString = "Adhoc DDL failed"; if (m_errors.size() > 0) { errString = m_errors.get(m_errors.size() - 1).getLogString(); } int fronttrim = errString.indexOf("DDL Error"); if (fronttrim < 0) { fronttrim = 0; } int endtrim = errString.indexOf(" in statement starting"); if (endtrim < 0) { endtrim = errString.length(); } String trimmed = errString.substring(fronttrim, endtrim); throw new IOException(trimmed); } } finally { m_classLoader = originalClassLoader; } }
Source:
<code>private Description testType(Tree type) { if (type == null) { return Description.NO_MATCH; } Type realType = ASTHelpers.getType(type); if (realType != null && realType.isRaw()) { return buildDescription(type) .setMessage("Avoid raw types; add appropriate type parameters if possible. " + "The type was: " <START> + realType <END> + "\nThis can be suppressed with @SuppressWarnings(\"rawtypes\") " + "where necessary, such as when interacting with older library code.") .build(); } if (type.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { return testTypes(((ParameterizedTypeTree) type).getTypeArguments()); } return Description.NO_MATCH; }</code><technical_language>types render in odd ways, especially include other generic type information. prettyType a bit cleaner: suggestion + MoreSuggestedFixes.prettyType(null, null, realType)</technical_language>

Target:
private Description testType(Tree type) { if (type == null) { return Description.NO_MATCH; } Type realType = ASTHelpers.getType(type); if (realType != null && realType.isRaw()) { return buildDescription(type) .setMessage("Avoid raw types; add appropriate type parameters if possible. " + "The type was: " + MoreSuggestedFixes.prettyType(null, null, realType) + "\nThis can be suppressed with @SuppressWarnings(\"rawtypes\") " + "where necessary, such as when interacting with older library code.") .build(); } if (type.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { return testTypes(((ParameterizedTypeTree) type).getTypeArguments()); } return Description.NO_MATCH; }
Source:
<code>public static void removeDirectoryEntryToDelete(String directoryName, String entryId) { Optional.ofNullable(directoryEntryIdsToDelete.get(directoryName)) <START> .ifPresent(entryIds -> entryIds.remove(entryId)); <END> }</code><technical_language>a suggestion, do about: directoryEntryIdsToDelete.getOrDefault(directoryName, Collections.emptySet()).remove(entryId);</technical_language>

Target:
public static void removeDirectoryEntryToDelete(String directoryName, String entryId) { directoryEntryIdsToDelete.getOrDefault(directoryName, Collections.emptySet()).remove(entryId); }
Source:
<code>private static boolean hasAuthAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { <START> if (annotation.annotationType() == HeaderParam.class) { <END> String value = ((HeaderParam) annotation).value(); if (value.equals(HttpHeaders.AUTHORIZATION)) { return true; } } } return false; }</code><technical_language>nit: suggestion if (HeaderParam.class.equals(annotation.annotationType())) {</technical_language>

Target:
private static boolean hasAuthAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (HeaderParam.class.equals(annotation.annotationType())) { String value = ((HeaderParam) annotation).value(); if (HttpHeaders.AUTHORIZATION.equals(value)) { return true; } } } return false; }
Source:
<code>private void bindProperty(String prefix, String name, String value) { String key = prefix == null ? name : (prefix + name); Set<String> aliasesForName = bindMap.get(name); if (value == null) { LOG.debug("Binding `{}` to `null`", key); bind(String.class).annotatedWith(Names.named(key)).toProvider(Providers.<String>of(null)); if (aliasesForName != null) { for (String alias : aliasesForName) { <START> LOG.debug("Binding `{}` to `null`", alias); <END> bind(String.class) .annotatedWith(Names.named(prefix == null ? alias : prefix + alias)) .toProvider(Providers.<String>of(null)); } } } else { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant().annotatedWith(Names.named(key)).to(value); if (aliasesForName != null) { for (String alias : aliasesForName) { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant() .annotatedWith(Names.named(prefix == null ? alias : prefix + alias)) .to(value); } } } }</code><technical_language>precise if prefix != null</technical_language>

Target:
private void bindProperty(String prefix, String name, String value) { String key = prefix == null ? name : (prefix + name); Set<String> aliasesForName = bindMap.get(name); if (value == null) { LOG.debug("Binding `{}` to `null`", key); bind(String.class).annotatedWith(Names.named(key)).toProvider(Providers.<String>of(null)); if (aliasesForName != null) { for (String alias : aliasesForName) { String bindKey = prefix == null ? alias : prefix + alias; LOG.debug("Binding `{}` to `null`", bindKey); bind(String.class) .annotatedWith(Names.named(bindKey)) .toProvider(Providers.<String>of(null)); } } } else { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant().annotatedWith(Names.named(key)).to(value); if (aliasesForName != null) { for (String alias : aliasesForName) { String bindKey = prefix == null ? alias : prefix + alias; LOG.debug("Binding `{}` to `{}`", bindKey, value); bindConstant().annotatedWith(Names.named(bindKey)).to(value); } } } }
Source:
<code>private void resetCluster(FileSystemMaster fsm) throws Exception { if (!mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().isServing()) { <START> mCluster.mLocalAlluxioCluster.start(); <END> fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); } fsm.updateUfsMode(new AlluxioURI(fsm.getUfsAddress()), UfsMode.READ_WRITE); for (FileInfo fileInfo : fsm .listStatus(new AlluxioURI("/"), ListStatusContext.defaults())) { fsm.delete(new AlluxioURI(fileInfo.getPath()), DeleteContext .create(DeletePOptions.newBuilder().setUnchecked(true).setRecursive(true))); } }</code><technical_language>condition check is for master, this start everything. do individual check process start if is running</technical_language>

Target:
private void resetCluster(FileSystemMaster fsm) throws Exception { fsm.updateUfsMode(new AlluxioURI(fsm.getUfsAddress()), UfsMode.READ_WRITE); for (FileInfo fileInfo : fsm .listStatus(new AlluxioURI("/"), ListStatusContext.defaults())) { fsm.delete(new AlluxioURI(fileInfo.getPath()), DeleteContext .create(DeletePOptions.newBuilder().setUnchecked(true).setRecursive(true))); } }
Source:
<code>private boolean isEntity(Object o){ Class<? extends Object> varClass = o.getClass(); <START> EntityManager em = getEntityManager(); <END> if( em != null ){ Set<EntityType<?>> entities = em.getMetamodel().getEntities(); for( EntityType<?> entity : entities ){ if( varClass.getCanonicalName().equals( entity.getJavaType().getCanonicalName() ) ){ return true; } } } return false; }</code><technical_language>entity manager factory get metamodel</technical_language>

Target:
private boolean isEntity(Object o){ Class<? extends Object> varClass = o.getClass(); return managedClasses.contains( varClass.getCanonicalName() ); }
Source:
<code>public void testResolveFragmentWithDistro_FAIL() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); <START> File index = IO.getFile("testdata/repo9/index.xml"); <END> File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (resolution.isOK()) { fail( "should have failed because there are no 'osgi.wiring.host' capablities added to the system resource"); } } }</code><technical_language>is this variable for? is used</technical_language>

Target:
public void testResolveFragmentWithDistro_FAIL() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (resolution.isOK()) { fail( "should have failed because there are no 'osgi.wiring.host' capablities added to the system resource"); } } }
Source:
<code>public int hashCode() { <START> int result = Objects.hash(type); <END> for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); TypeCodec thisCodec = this.codecRegistry().codecFor(innerThisType); if (thisCodec == null) { LOG.warn( "No codec found for tuple type " + innerThisType.toString() + " falling bytes for hashcode"); return 31 * Objects.hash(type) + Arrays.hashCode(values); } Object thisValue = this.codecRegistry() .codecFor(innerThisType) .decode(this.values[i], this.protocolVersion()); result = 31 * result + thisValue.hashCode(); } return result; }</code><technical_language>object is hashed here, this replaced type.hashCode(). line 161</technical_language>

Target:
public int hashCode() { int result = type.hashCode(); for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); Object thisValue = this.codecRegistry() .codecFor(innerThisType) .decode(this.values[i], this.protocolVersion()); result = 31 * result + thisValue.hashCode(); } return result; }
Source:
<code>private void performDirectEdit(SelectionRequest request) { NewInstanceDirectEditManager <START> directEditMaanger = <END> getManager(); directEditMaanger.updateRefPosition(new Point(request.getLocation().x, request.getLocation().y)); if (request.getExtendedData().isEmpty()) { directEditMaanger.show(); } else { Object key = request.getExtendedData().keySet().iterator().next(); if (key instanceof String) { directEditMaanger.show((String) key); } } }</code><technical_language>typo directEditManager</technical_language>

Target:
private void performDirectEdit(SelectionRequest request) { NewInstanceDirectEditManager directEditManager = getManager(); directEditManager.updateRefPosition(new Point(request.getLocation().x, request.getLocation().y)); if (request.getExtendedData().isEmpty()) { directEditManager.show(); } else { Object key = request.getExtendedData().keySet().iterator().next(); if (key instanceof String) { directEditManager.show((String) key); } } }
Source:
<code>protected void waitUntilServerIsUp(String host, long time, TimeUnit timeUnit) throws TimeoutException { long startTime = System.currentTimeMillis(); long waitMillis = timeUnit.toMillis(time); boolean connected = false; while (!connected) { if(System.currentTimeMillis() > startTime + waitMillis) { throw new TimeoutException("Server " + host + " is still down after " + waitMillis + " ms"); } try { URL healthUrl = new URL(host + "/dolphin"); URLConnection connection = healthUrl.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.connect(); <START> if(httpURLConnection.getResponseCode() == 405) { <END> connected = true; } } else { throw new IOException("URL " + healthUrl + " do not provide a HttpURLConnection!"); } } catch (Exception e) { } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }</code><technical_language>Method Allowed</technical_language>

Target:
protected void waitUntilServerIsUp(String host, long time, TimeUnit timeUnit) throws TimeoutException { long startTime = System.currentTimeMillis(); long waitMillis = timeUnit.toMillis(time); boolean connected = false; while (!connected) { if(System.currentTimeMillis() > startTime + waitMillis) { throw new TimeoutException("Server " + host + " is still down after " + waitMillis + " ms"); } try { URL healthUrl = new URL(host + "/rest/health"); URLConnection connection = healthUrl.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.connect(); if(httpURLConnection.getResponseCode() == 200) { connected = true; } } else { throw new IOException("URL " + healthUrl + " do not provide a HttpURLConnection!"); } } catch (Exception e) { } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Source:
<code>public Value valueOf(@Nullable Object object) { if(object == null) { return nullValue(); } Class<?> type = object.getClass(); Collection<Coordinate> line = new ArrayList<Coordinate>(); if(type.equals(getJavaClass())) { if(((Collection<?>) object).isEmpty()) { throw new MagmaRuntimeException("A Line can't be empty"); } for(Object o : (List<?>) object) { if(o.getClass().equals(Coordinate.class)) { line.add((Coordinate) o); } else if(o.getClass().equals(String.class)) { line.add(Coordinate.valueOf((String) o)); } } return Factory.newValue(this, (Serializable) line); } if(type.equals(String.class)) { return valueOf((String) object); } if(type.equals(JSONArray.class)) { <START> return valueOf(object.toString()); <END> } throw new IllegalArgumentException( "Cannot construct " + getClass().getSimpleName() + " from type " + object.getClass() + "."); }</code><technical_language>toString() call: process JSONArray</technical_language>

Target:
public Value valueOf(@Nullable Object object) { if(object == null) { return nullValue(); } Class<?> type = object.getClass(); if(type.equals(String.class)) { return valueOf((String) object); } if(type.equals(JSONArray.class)) { return valueOf((JSONArray) object); } if(type.equals(getJavaClass())) { Collection<Coordinate> line = new ArrayList<Coordinate>(); for(Object o : (List<?>) object) { line.add(Coordinate.getCoordinateFrom(o)); } if(line.isEmpty()) { throw new MagmaRuntimeException("The Line can't be empty"); } return Factory.newValue(this, (Serializable) line); } throw new IllegalArgumentException( "Cannot construct " + getClass().getSimpleName() + " from type " + object.getClass() + "."); }
Source:
<code>public void testOpenApiYaml() { JsonResponse<Map<String, Object>> response = client.execute( prepareGet().setUri(uriForOpenJSon("/openapi/api.yaml")).build(), createFullJsonResponseHandler(MAP_CODEC)); <START> assertNotNull(response.getResponseBody()); <END> }</code><technical_language>Platform provide a YAML deserializer, this test a looser, fail if, for example, this returns JSON instead of YAML. Do some sort of spot check, TestWadlResource.testGetWadl() does</technical_language>

Target:
public void testOpenApiYaml() { StringResponse response = client.execute( prepareGet().setUri(uriForOpenSpec("/admin/openapi.yaml")).build(), createStringResponseHandler()); assertEquals(response.getStatusCode(), 200); assertEquals(response.getHeader("Content-Type"), "application/yaml"); assertContains(response.getBody(), "summary: Testing GET request"); assertContains(response.getBody(), "description: One or more query parameter(s) is null or empty"); }
Source:
<code>public List<AccurevTransaction> filterBySubpath(List<AccurevTransaction> transactions) { List<AccurevTransaction> trans = new ArrayList<>(); logger.info("using subpath:" + getSubpath()); List<String> subpaths = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(getSubpath(), ","); while (st.hasMoreElements()) { String path = st.nextToken().trim(); path = path.replace("*", ""); <START> logger.info("path:" + path); <END> subpaths.add(path); } logger.info("subpaths size:" + subpaths.size()); for (AccurevTransaction transaction : transactions) { boolean isValid = false; for (String rawPath : transaction.getAffectedRawPaths()) { if (isValid) { logger.info("transaction is valid :" + transaction.getId()); logger.info("no need check files in this transaction"); break; } logger.info("rawPath:" + rawPath); for (String subpath : subpaths) { logger.info("rawPath.contains(subpath):" + rawPath.contains(subpath)); if (rawPath.contains(subpath)) { isValid = true; break; } else { isValid = false; } } } if (!isValid) { logger.info("not adding transaction to list:" + transaction.getId()); } else { logger.info("adding transaction to list:" + transaction.getId()); trans.add(transaction); } } return trans; }</code><technical_language>log level info out this file</technical_language>

Target:
public List<AccurevTransaction> filterBySubpath(List<AccurevTransaction> transactions) { List<AccurevTransaction> trans = new ArrayList<>(); logger.fine("using subpath:" + getSubpath()); List<String> subpaths = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(getSubpath(), ","); while (st.hasMoreElements()) { String path = st.nextToken().trim(); path = path.replace("*", ""); logger.fine("path:" + path); subpaths.add(path); } logger.fine("subpaths size:" + subpaths.size()); for (AccurevTransaction transaction : transactions) { boolean isValid = false; for (String rawPath : transaction.getAffectedRawPaths()) { if (isValid) { logger.fine("transaction is valid :" + transaction.getId()); logger.fine("no need check files in this transaction"); break; } logger.fine("rawPath:" + rawPath); for (String subpath : subpaths) { logger.fine("rawPath.contains(subpath):" + rawPath.contains(subpath)); if (rawPath.contains(subpath)) { isValid = true; break; } else { isValid = false; } } } if (!isValid) { logger.fine("not adding transaction to list:" + transaction.getId()); } else { logger.fine("adding transaction to list:" + transaction.getId()); trans.add(transaction); } } return trans; }
Source:
<code>public Boolean getisValueTypeCorrect() { if (this.xmpNode.getChildren().size() != 5) { return Boolean.FALSE; } <START> VeraPDFXMPNode namespace = null; <END> VeraPDFXMPNode prefix = null; VeraPDFXMPNode property = null; VeraPDFXMPNode schema = null; VeraPDFXMPNode valueType = null; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_SCHEMA.equals(child.getNamespaceURI())) { switch (child.getName()) { case "namespaceURI": namespace = child; break; case "prefix": prefix = child; break; case "property": property = child; break; case "schema": schema = child; break; case "valueType": valueType = child; break; } } } return Boolean.valueOf(namespace != null && prefix != null && property != null && schema != null && valueType != null); }</code><technical_language>boolean flags</technical_language>

Target:
public Boolean getisValueTypeCorrect() { boolean isValid = true; boolean isNamespacePresent = false; boolean isPrefixPresent = false; boolean isPropertyPresent = false; boolean isSchemaPresent = false; boolean isValueTypePresent = false; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_SCHEMA.equals(child.getNamespaceURI())) { switch (child.getName()) { case "namespaceURI": if (isNamespacePresent) { isValid = false; } else { isNamespacePresent = true; } break; case "prefix": if (isPrefixPresent) { isValid = false; } else { isPrefixPresent = true; } break; case "property": if (isPropertyPresent) { isValid = false; } else { isPropertyPresent = true; } break; case "schema": if (isSchemaPresent) { isValid = false; } else { isSchemaPresent = true; } break; case "valueType": if (isValueTypePresent) { isValid = false; } else { isValueTypePresent = true; } break; default: isValid = false; } } else { isValid = false; } } return Boolean.valueOf(isValid); }
Source:
<code><START> public FetchCommand setProgressMonitor(ProgressMonitor monitor) { <END> this.monitor = monitor; return this; }</code><technical_language>Missing checkCallable()</technical_language>

Target:
public FetchCommand setProgressMonitor(ProgressMonitor monitor) { checkCallable(); this.monitor = monitor; return this; }