auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public T call(ConfigBag parameters) { String baseUri = Preconditions.checkNotNull(entity().getConfig(MIRRORED_ENTITY_URL), "Cannot be invoked without an entity URL"); HttpClientBuilder builder = HttpTool.httpClientBuilder() .trustAll() .laxRedirect(true) .uri(baseUri); if (entity().getConfig(MANAGEMENT_USER)!=null) builder.credentials(new UsernamePasswordCredentials(entity().getConfig(MANAGEMENT_USER), entity().getConfig(MANAGEMENT_PASSWORD))); HttpClient client = builder.build(); <START> byte[] result = submit(client, URI.create(Urls.mergePaths(baseUri, "effectors/"+remoteEffectorName)), parameters.getAllConfig()); <END> if (resultParser!=null) return resultParser.apply(result); else return null; }</code><technical_language>Path escape remoteEffectorName</technical_language>

Target:
public T call(ConfigBag parameters) { String baseUri = Preconditions.checkNotNull(entity().getConfig(MIRRORED_ENTITY_URL), "Cannot be invoked without an entity URL"); HttpClientBuilder builder = HttpTool.httpClientBuilder() .trustAll() .laxRedirect(true) .uri(baseUri); if (entity().getConfig(MANAGEMENT_USER)!=null) builder.credentials(new UsernamePasswordCredentials(entity().getConfig(MANAGEMENT_USER), entity().getConfig(MANAGEMENT_PASSWORD))); HttpClient client = builder.build(); byte[] result = submit(client, URI.create(Urls.mergePaths(baseUri, "effectors", Urls.encode(remoteEffectorName))), parameters.getAllConfig()); if (resultParser!=null) return resultParser.apply(result); else return null; }
Source:
<code>public String poll(long timeout, TimeUnit unit) throws InterruptedException { if (slow.get()) { <START> Thread.sleep(300); <END> } return super.poll(timeout, unit); }</code><technical_language>sad arbitrary sleeps in a test. a Phaser CountDownLatch instead</technical_language>

Target:
public String poll(long timeout, TimeUnit unit) throws InterruptedException { lock = true; countDownLatch.await(1, TimeUnit.MINUTES); lock = false; return super.poll(timeout, unit); }
Source:
<code>@Override protected void run(JsonNode jsonNode) { String cacheName = jsonNode.get(PARAM_CACHE_NAME).asText(); <START> boolean infinite = jsonNode.hasNonNull(PARAM_INFINITE) && jsonNode.get(PARAM_INFINITE).asBoolean(); <END> boolean optimized = !jsonNode.hasNonNull(PARAM_OPTIMIZED) || jsonNode.get(PARAM_OPTIMIZED).asBoolean(); int range = jsonNode.get(PARAM_RANGE).asInt(); if (infinite) { Random rnd = new Random(); CountDownLatch exitLatch = new CountDownLatch(1); Thread th = new Thread(() -> { log.info(WATCHEABLE_BEGIN_DATA_GEN_MSG); boolean error = false; try { while (!terminated()) generateData(cacheName, range, (idx) -> rnd.nextInt(range), optimized); log.info("Background data generation finished."); } catch (Exception e) { if (!X.hasCause(e, NodeStoppingException.class)) { error = true; log.error("Failed to generate data in background.", e); } } finally { if (error) markBroken(); else markFinished(); exitLatch.countDown(); } }, DataGenerationApplication.class.getName() + "_cacheLoader"); th.start(); markInitialized(); try { exitLatch.await(); } catch (InterruptedException e) { log.warn("Interrupted waiting for background loading."); } } else { log.info("Generating data..."); generateData(cacheName, range, Function.identity(), optimized); log.info("Data generation finished. Generated " + range + " entries."); markSyncExecutionComplete(); } }</code><technical_language>asBoolean(dflt) instead</technical_language>

Target:
@Override protected void run(JsonNode jsonNode) { log.info("Creating cache..."); IgniteCache<Integer, Integer> cache = ignite.createCache(jsonNode.get("cacheName").asText()); try (IgniteDataStreamer<Integer, Integer> stmr = ignite.dataStreamer(cache.getName())) { for (int i = 0; i < jsonNode.get("range").asInt(); i++) { stmr.addData(i, i); if (i % 10_000 == 0) log.info("Streamed " + i + " entries"); } } markSyncExecutionComplete(); }
Source:
<code>public List<String> getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { checkPaginatedGetChildren(); try { @SuppressWarnings("unchecked") List<String> children = (List<String>) (_isPaginationSupported <START> ? _getChildrenMethod.invoke(_zk, path, watch, -1, -1, -1) : _getChildrenMethod.invoke(_zk, path, watch)); <END> return children; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof KeeperException.UnimplementedException) { LOG.warn("Paginated getChildren is unimplemented in ZK server! " + "Falling back to non-paginated getChildren"); _isPaginationSupported = false; try { _getChildrenMethod = ZooKeeper.class.getMethod("getChildren", String.class, boolean.class); } catch (NoSuchMethodException ex) { LOG.error("getChildren is not supported in this zookeeper version!", cause); } throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } if (cause instanceof KeeperException) { throw KeeperException.create(((KeeperException) cause).code(), path); } throw KeeperException.create(KeeperException.Code.APIERROR, path); } catch (IllegalAccessException e) { LOG.error("Unable to get children for {}", path, e); throw KeeperException.create(KeeperException.Code.APIERROR, path); } }</code><technical_language>This implementation confusing... a ifelse statement call function explicitly</technical_language>

Target:
public List<String> getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { if (_getChildrenMethod == null) { lookupGetChildrenMethod(); } try { @SuppressWarnings("unchecked") List<String> children = (List<String>) _getChildrenMethod.invoke(_zk, path, watch); return children; } catch (InvocationTargetException e) { handleInvokedMethodException(e.getCause()); } catch (IllegalAccessException e) { LOG.error("Unable to get children for {}", path, e); } throw KeeperException.create(KeeperException.Code.APIERROR, path); }
Source:
<code>public final IJSRuntimeInstall createRuntimeInstall(String id) { if (JSRuntimeManager.getJSRuntimeInstall(id) != null) { throw new IllegalArgumentException( <START> NLS.bind(RuntimeMessages.AbstractJSRuntimeType_DuplicateRuntimeInstall_Error, <END> new String[] { id })); } IJSRuntimeInstall runtimeInstall = null; synchronized (this) { runtimeInstall = doCreateRuntimeInstall(id); } return runtimeInstall; }</code><technical_language>is a version of bind() need creation of array</technical_language>

Target:
public final IJSRuntimeInstall createRuntimeInstall(String id) { if (JSRuntimeManager.getJSRuntimeInstall(id) != null) { throw new IllegalArgumentException( NLS.bind(RuntimeMessages.AbstractJSRuntimeType_DuplicateRuntimeInstall_Error, id)); } IJSRuntimeInstall runtimeInstall = null; runtimeInstall = doCreateRuntimeInstall(id); return runtimeInstall; }
Source:
<code>public void setMode(Mode newMode) { try { switch (newMode) { case BATCH_EDIT: dbConnection.setConnectionMode(true, false); break; <START> case READ_ONLY: <END> dbConnection.setConnectionMode(false, true); break; case READ_WRITE: dbConnection.setConnectionMode(false, false); break; default: log.warn("New context mode detected that has nog been configured."); break; } } catch(SQLException ex) { log.warn("Unable to set database connection mode", ex); } this.mode = newMode; }</code><technical_language>afraid reset cache entering read mode do track policy changes in cache. In parts of code read-only mode, check authorizations, read-write read-only mode. This result in wrong cache entries. Resetting cache decrease performance, long do follow policy changes in cache, is ensure cache entries. Another reset cache ResourecPolicyService.create ResourcePolicy.set*() called</technical_language>

Target:
public void setMode(Mode newMode) { try { switch (newMode) { case BATCH_EDIT: dbConnection.setConnectionMode(true, false); break; case READ_ONLY: dbConnection.setConnectionMode(false, true); break; case READ_WRITE: dbConnection.setConnectionMode(false, false); break; default: log.warn("New context mode detected that has nog been configured."); break; } } catch(SQLException ex) { log.warn("Unable to set database connection mode", ex); } if(mode != Mode.READ_ONLY || newMode != Mode.READ_ONLY) { readOnlyCache.clear(); } mode = newMode; }
Source:
<code>public int removeRecipient(String channelName, String selectorExpression) { int counter = 0; for (Iterator<Recipient> it = this.recipients.iterator();it.hasNext();) { Recipient next = it.next(); MessageSelector selector = next.getSelector(); MessageChannel channel = next.getChannel(); if(selector instanceof ExpressionEvaluatingSelector && <START> channel.equals(this.getBeanFactory().getBean(channelName)) && <END> ((ExpressionEvaluatingSelector)selector).getExpressionString().equals(selectorExpression)) { it.remove(); counter++; } } return counter; }</code><technical_language>is done iteration moved beginning of method local variable</technical_language>

Target:
public int removeRecipient(String channelName, String selectorExpression) { int counter = 0; MessageChannel targetChannel = this.getBeanFactory().getBean(channelName, MessageChannel.class); for (Iterator<Recipient> it = this.recipients.iterator();it.hasNext();) { Recipient next = it.next(); MessageSelector selector = next.getSelector(); MessageChannel channel = next.getChannel(); if(selector instanceof ExpressionEvaluatingSelector && channel == targetChannel && ((ExpressionEvaluatingSelector) selector).getExpressionString().equals(selectorExpression)) { it.remove(); counter++; } } return counter; }
Source:
<code><START> public void should_allow_to_specify_type_comparator_after_using_extracting_with_single_parameter_on_object() { <END> Person obiwan = new Person("Obi-Wan"); obiwan.setHeight(new BigDecimal("1.820")); assertThat(obiwan).extracting("height") .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) .isEqualTo(new BigDecimal("1.82")); }</code><technical_language>usingComparatorForType is in context of field field comparison. a specific comparator isEqualTo, call public usingComparator(Comparator<? super ACTUAL> customComparator) in case ACTUAL = Object is a BigDecimal comparator. allow this case, need allow users type of extracted + changing signature of extracting to: public <T> AbstractObjectAssert<?, T> extracting(String propertyOrField, Class<T> extractedType) a bunch of other changes cascade introduction of generic parameter T. is I valuable in another pull request</technical_language>

Target:
public void should_allow_to_specify_type_comparator_after_using_extracting_with_single_parameter_on_object() { Person obiwan = new Person("Obi-Wan"); obiwan.setHeight(new BigDecimal("1.820")); Comparator<Object> heightComparator = (o1, o2) -> { if (o1 instanceof BigDecimal) return BIG_DECIMAL_COMPARATOR.compare((BigDecimal) o1, (BigDecimal) o2); throw new IllegalStateException("only supported for BigDecimal"); }; assertThat(obiwan).extracting("height") .usingComparator(heightComparator) .isEqualTo(new BigDecimal("1.82")); }
Source:
<code>public InMemoryFormat getInMemoryFormat() { <START> return getMapContainer().getMapConfig().getInMemoryFormat(); <END> }</code><technical_language>do longer return in field</technical_language>

Target:
public InMemoryFormat getInMemoryFormat() { return inMemoryFormat; }
Source:
<code>boolean deleteService() { try { final Response response = coreClient.deleteNamespacedServiceCall(getTopologyName(), getNamespace(), null, null, 0, null, KubernetesConstants.DELETE_OPTIONS_PROPAGATION_POLICY, null, null).execute(); if (response.isSuccessful()) { LOG.log(Level.INFO, "Headless Service for the Job [" + getTopologyName() + "] in namespace [" + getNamespace() + "] is deleted."); return true; } else { if (response.code() == HTTP_NOT_FOUND) { LOG.log(Level.INFO, "Kubernetes headless service does not exist for Topology: " + getTopologyName()); return true; } LOG.log(Level.SEVERE, "Error when deleting the Service of the job [" + getTopologyName() + "] in namespace [" + getNamespace() + "]"); LOG.log(Level.SEVERE, "Error killing topoogy message:" + response.message()); KubernetesUtils.logResponseBodyIfPresent(LOG, response); throw new TopologyRuntimeManagementException( KubernetesUtils.errorMessageFromResponse(response)); } } catch (ApiException e) { if (e.getCode() == HTTP_NOT_FOUND) { LOG.log(Level.INFO, "Kubernetes headless service does not exist for Topology: " + getTopologyName()); return true; } <START> } catch (IOException e) { <END> KubernetesUtils.logExceptionWithDetails(LOG, "Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); return false; } return false; }</code><technical_language>catch Exception instead</technical_language>

Target:
void deleteService() { try (Response response = coreClient.deleteNamespacedServiceCall(getTopologyName(), getNamespace(), null, null, 0, null, KubernetesConstants.DELETE_OPTIONS_PROPAGATION_POLICY, null, null).execute()) { if (!response.isSuccessful()) { if (response.code() == HTTP_NOT_FOUND) { LOG.log(Level.WARNING, "Deleting non-existent Kubernetes headless service for Topology: " + getTopologyName()); return; } LOG.log(Level.SEVERE, "Error when deleting the Service of the job [" + getTopologyName() + "] in namespace [" + getNamespace() + "]"); LOG.log(Level.SEVERE, "Error killing topology message:" + response.message()); KubernetesUtils.logResponseBodyIfPresent(LOG, response); throw new TopologyRuntimeManagementException( KubernetesUtils.errorMessageFromResponse(response)); } } catch (ApiException e) { if (e.getCode() == HTTP_NOT_FOUND) { LOG.log(Level.WARNING, "Tried to delete a non-existent Kubernetes service for Topology: " + getTopologyName()); return; } throw new TopologyRuntimeManagementException("Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); } catch (IOException e) { throw new TopologyRuntimeManagementException("Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); } LOG.log(Level.INFO, "Headless Service for the Job [" + getTopologyName() + "] in namespace [" + getNamespace() + "] is deleted."); }
Source:
<code>public void testIterationWithConcurrentClearedCacheException() { try (CacheManager cacheManager = createTestCacheManager()) { Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class); byte[] data = new byte[10 * 1024]; range(0, 20).forEach(k -> cache.put(k, data)); Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator(); cache.clear(); <START> try { <END> while (true) { iterator.next(); } } catch (NoSuchElementException e) { } } }</code><technical_language>this test count numbers of entries returned similar assert full cache is returned</technical_language>

Target:
public void testIterationWithConcurrentClearedCacheException() { try (CacheManager cacheManager = createTestCacheManager()) { Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class); byte[] data = new byte[10 * 1024]; Set<Long> initialKeySet = new HashSet<>(); range(0, 20).forEach(k -> { cache.put(k, data); initialKeySet.add(k); }); Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator(); cache.clear(); HashSet<Long> foundKeys = new HashSet<>(); try { while (true) { assertThat(foundKeys.add(iterator.next().getKey()), is(true)); } } catch (NoSuchElementException e) { } foundKeys.forEach(k -> assertThat(k, isIn(initialKeySet))); } }
Source:
<code>public static boolean isValidDefinition(URL definitionURL, String definitionType) <START> throws EndpointRegistryException { <END> DefinitionValidator schemaValidator = definitionValidatorMap.get(definitionType); if (schemaValidator != null) { return schemaValidator.validate(definitionURL); } throw new EndpointRegistryException("No Schema Validator found for the given definition type: '" + definitionType + "'"); }</code><technical_language>Define a exception for this, SchemaValidationException</technical_language>

Target:
public static boolean isValidDefinition(URL definitionURL, String definitionType) throws DefinitionValidationException { DefinitionValidator definitionValidator = definitionValidatorMap.get(definitionType); if (definitionValidator != null) { return definitionValidator.validate(definitionURL); } throw new DefinitionValidationException("No Definition Validator found for the given definition type: '" + definitionType + "'"); }
Source:
<code>private long getMaxRead(long position, long count) throws IOException { count = Math.min( maxRemoteSize == 0 || (position + count >= maxRemoteSize && activeFile) ? reallyGetLength() - position : maxRemoteSize - position, count); <START> return (count == 0) ? 0 : count; <END> }</code><technical_language>return count? :)</technical_language>

Target:
private long getMaxRead(long position, long count) throws IOException { count = Math.min( maxRemoteSize == 0 || (position + count >= maxRemoteSize && activeFile) ? reallyGetLength() - position : maxRemoteSize - position, count); return count; }
Source:
<code>public ItemHolder(View view) { super(view); this.text = (TextView) view.findViewById(R.id.text); <START> this.container = (LinearLayout) view.findViewById(R.id.container); <END> }</code><technical_language>container is a View, need LinearLayout cast here</technical_language>

Target:
public ItemHolder(View view) { super(view); this.container = (LinearLayout) view.findViewById(R.id.container); this.text = (TextView) view.findViewById(R.id.text); }
Source:
<code>private void readHeaderData() throws IOException { setFileVersion(parseInt()); gencallVersion = parseString(); clusterVersion = parseString(); callVersion = parseString(); normalizationVersion = parseString(); dateCreated = parseString(); <START> skipBoolean(); <END> if (getFileVersion() == INVALID_FILE_VERSION) { throw new IOException("Version '" + INVALID_FILE_VERSION + "' unsupported"); } manifestName = parseString(); }</code><technical_language>parseBoolean()</technical_language>

Target:
private void readHeaderData() throws IOException { setFileVersion(parseInt()); gencallVersion = parseString(); clusterVersion = parseString(); callVersion = parseString(); normalizationVersion = parseString(); dateCreated = parseString(); isWGT = parseByte() != '\0'; if (getFileVersion() == INVALID_FILE_VERSION) { throw new IOException("Version '" + INVALID_FILE_VERSION + "' unsupported"); } manifestName = parseString(); }
Source:
<code><START> private void generatePositionEqualsRowWithPageMethod( <END> ClassDefinition classDefinition, CallSiteBinder callSiteBinder, List<Type> joinChannelTypes, List<FieldDefinition> joinChannelFields) { Parameter leftBlockIndex = arg("leftBlockIndex", int.class); Parameter leftBlockPosition = arg("leftBlockPosition", int.class); Parameter rightPosition = arg("rightPosition", int.class); Parameter page = arg("page", Page.class); Parameter rightChannels = arg("rightChannels", int[].class); MethodDefinition positionEqualsRowMethod = classDefinition.declareMethod( a(PUBLIC), "positionEqualsRow", type(boolean.class), leftBlockIndex, leftBlockPosition, rightPosition, page, rightChannels); Variable thisVariable = positionEqualsRowMethod.getThis(); BytecodeBlock body = positionEqualsRowMethod.getBody(); for (int index = 0; index < joinChannelTypes.size(); index++) { BytecodeExpression leftBlock = thisVariable .getField(joinChannelFields.get(index)) .invoke("get", Object.class, leftBlockIndex) .cast(Block.class); BytecodeExpression rightBlock = page.invoke("getBlock", Block.class, rightChannels.getElement(index)); body.append(new IfStatement() .condition(isDistinctFromGenerator.generateIsDistinctFrom( callSiteBinder, joinChannelTypes.get(index), leftBlock, leftBlockPosition, rightBlock, rightPosition)) .ifTrue(constantFalse().ret())); } body.append(constantTrue().ret()); }</code><technical_language>I call this generatePositionNotDistinctFromRowWithPageMethod, leave other method's name unchanged</technical_language>

Target:
private static void generatePositionEqualsRowWithPageMethod( ClassDefinition classDefinition, CallSiteBinder callSiteBinder, List<Type> joinChannelTypes, List<FieldDefinition> joinChannelFields) { Parameter leftBlockIndex = arg("leftBlockIndex", int.class); Parameter leftBlockPosition = arg("leftBlockPosition", int.class); Parameter rightPosition = arg("rightPosition", int.class); Parameter page = arg("page", Page.class); Parameter rightChannels = arg("rightChannels", int[].class); MethodDefinition positionEqualsRowMethod = classDefinition.declareMethod( a(PUBLIC), "positionEqualsRow", type(boolean.class), leftBlockIndex, leftBlockPosition, rightPosition, page, rightChannels); Variable thisVariable = positionEqualsRowMethod.getThis(); BytecodeBlock body = positionEqualsRowMethod.getBody(); for (int index = 0; index < joinChannelTypes.size(); index++) { BytecodeExpression type = constantType(callSiteBinder, joinChannelTypes.get(index)); BytecodeExpression leftBlock = thisVariable .getField(joinChannelFields.get(index)) .invoke("get", Object.class, leftBlockIndex) .cast(Block.class); BytecodeExpression rightBlock = page.invoke("getBlock", Block.class, rightChannels.getElement(index)); body.append(new IfStatement() .condition(typeEquals(type, leftBlock, leftBlockPosition, rightBlock, rightPosition)) .ifFalse(constantFalse().ret())); } body.append(constantTrue().ret()); }
Source:
<code>protected Optional<DyeColor> getVal(EntityShulker container) { <START> if (!(container instanceof IMixinShulker)) <END> return Optional.empty(); return Optional.of(((IMixinShulker) container).getColor()); }</code><technical_language>Braces</technical_language>

Target:
protected Optional<DyeColor> getVal(EntityShulker container) { return Optional.of(((IMixinShulker) container).getColor()); }
Source:
<code>public MaxRateRegistry provide() { ConsumerMaxRateRegistryType type; try { type = ConsumerMaxRateRegistryType.fromString(configFactory.getStringProperty(Configs.CONSUMER_MAXRATE_REGISTRY_TYPE)); } catch (Exception e) { logger.error("Could not configure max rate registry", e); throw e; } logger.info("Max rate registry type chosen: {}", type.getConfigValue()); switch (type) { case HIERARCHICAL: return new HierarchicalCacheMaxRateRegistry(configFactory, curator, objectMapper, zookeeperPaths, pathSerializer, subscriptionCache); case FLAT_BINARY: return new FlatBinaryMaxRateRegistry(configFactory, subscriptionAssignmentCache::getAssignedConsumers, <START> subscriptionAssignmentCache::getConsumerSubscriptions, curator, zookeeperPaths, subscriptionIds); <END> default: throw new UnsupportedOperationException("Max-rate type not supported."); } }</code><technical_language>split lines</technical_language>

Target:
public MaxRateRegistry provide() { ConsumerMaxRateRegistryType type; try { String typeString = configFactory.getStringProperty(Configs.CONSUMER_MAXRATE_REGISTRY_TYPE); type = ConsumerMaxRateRegistryType.fromString(typeString); } catch (Exception e) { logger.error("Could not configure max rate registry", e); throw e; } logger.info("Max rate registry type chosen: {}", type.getConfigValue()); switch (type) { case HIERARCHICAL: return new HierarchicalCacheMaxRateRegistry( configFactory, curator, objectMapper, zookeeperPaths, pathSerializer, subscriptionCache ); case FLAT_BINARY: return new FlatBinaryMaxRateRegistry( configFactory, subscriptionAssignmentCache::getAssignedConsumers, subscriptionAssignmentCache::getConsumerSubscriptions, curator, zookeeperPaths, subscriptionIds ); default: throw new UnsupportedOperationException("Max-rate type not supported."); } }
Source:
<code>private boolean canTypeBeAnalyzed(String fieldType) { <START> return "string".equals( fieldType ); <END> }</code><technical_language>Time add constants for types</technical_language>

Target:
private boolean canTypeBeAnalyzed(String fieldType) { return TYPE_STRING.equals( fieldType ); }
Source:
<code>private String getFieldCheckRequired(String column, boolean required) throws IOException { String str = reader.get(column); if (str == null) { if (!missingRequiredColumns.contains(column)) { <START> feed.errors.add(new MissingColumnError(tableName, row, column)); <END> missingRequiredColumns.add(column); } } else if (str.isEmpty()) { if (required) { feed.errors.add(new EmptyFieldError(tableName, row, column)); } str = null; } return str; }</code><technical_language>this row 0</technical_language>

Target:
private String getFieldCheckRequired(String column, boolean required) throws IOException { String str = reader.get(column); if (str == null) { if (!missingRequiredColumns.contains(column)) { feed.errors.add(new MissingColumnError(tableName, column)); missingRequiredColumns.add(column); } } else if (str.isEmpty()) { if (required) { feed.errors.add(new EmptyFieldError(tableName, row, column)); } str = null; } return str; }
Source:
<code>public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context){ <START> StartedDrugOrderCohortDefinition cd = (StartedDrugOrderCohortDefinition) cohortDefinition; <END> context = ObjectUtil.nvl(context, new EvaluationContext()); HqlQueryBuilder q = new HqlQueryBuilder(); q.select("do.patient.patientId"); q.from(DrugOrder.class, "do"); q.wherePatientIn("do.patient.patientId", context); q.whereEqual("do.action", Action.NEW); q.whereNull("do.previousOrder"); if (cd.getActiveOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateActivated", cd.getActiveOnOrBefore()); q.whereGreaterOrNull("do.dateStopped", cd.getActiveOnOrBefore()); } if (cd.getActiveOnOrAfter() != null) { q.whereNotNull("do.dateActivated"); q.whereGreaterEqualOrNull("do.dateStopped", cd.getActiveOnOrAfter()); } if (cd.getStartedOnOrAfter()!= null) { q.whereGreaterOrEqualTo("do.dateStopped", cd.getStartedOnOrAfter()); } if (cd.getStartedOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateStopped", cd.getStartedOnOrBefore()); } if (cd.getDrugSet() != null && cd.getDrugSet().size() > 0) { q.whereInAny("do.drugs", cd.getDrugSet().toArray()); } if (cd.getGenericDrugList() != null && cd.getGenericDrugList().size() > 0) { q.whereInAny("do.concept", cd.getGenericDrugList().toArray()); } List<Integer> pIds = evaluationService.evaluateToList(q, Integer.class, context); Cohort c = new Cohort(pIds); return new EvaluatedCohort(c, cd, context); }</code><technical_language>this space is unnecessary</technical_language>

Target:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) { StartedDrugOrderCohortDefinition cd = (StartedDrugOrderCohortDefinition) cohortDefinition; context = ObjectUtil.nvl(context, new EvaluationContext()); HqlQueryBuilder q = new HqlQueryBuilder(); q.select("do.patient.patientId"); q.from(DrugOrder.class, "do"); q.wherePatientIn("do.patient.patientId", context); q.whereEqual("do.action", Action.NEW); q.whereNull("do.previousOrder"); if (cd.getActiveOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateActivated", cd.getActiveOnOrBefore()); q.whereGreaterOrNull("do.dateStopped", cd.getActiveOnOrBefore()); } if (cd.getActiveOnOrAfter() != null) { q.whereNotNull("do.dateActivated"); q.whereGreaterEqualOrNull("do.dateStopped", cd.getActiveOnOrAfter()); } if (cd.getStartedOnOrAfter() != null) { q.whereGreaterOrEqualTo("do.dateStopped", cd.getStartedOnOrAfter()); } if (cd.getStartedOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateStopped", cd.getStartedOnOrBefore()); } if (cd.getDrugSet() != null && cd.getDrugSet().size() > 0) { q.whereInAny("do.drug", cd.getDrugSet().toArray()); } if (cd.getGenericDrugList() != null && cd.getGenericDrugList().size() > 0) { q.whereInAny("do.drug", cd.getGenericDrugList().toArray()); } List<Integer> pIds = evaluationService.evaluateToList(q, Integer.class, context); Cohort c = new Cohort(pIds); return new EvaluatedCohort(c, cd, context); }
Source:
<code>private void bulkPrepare(BulkOperations bulkOperations, Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = getStoredVariantAnnotations(variantAnnotations); for (Map.Entry<String, VariantAnnotation> entry : variantAnnotations.entrySet()) { <START> final String key = entry.getKey(); <END> if (storedVariantAnnotations.containsKey(key)) { bulkUpdate(bulkOperations, key, storedVariantAnnotations.get(key).concatenate(entry.getValue())); } else { bulkAddToSet(bulkOperations, key, entry.getValue()); } } }</code><technical_language>variantId? final String variantId = entry.getKey(); express key of entry is variantId in query</technical_language>

Target:
private void bulkPrepare(BulkOperations bulkOperations, Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = getStoredVariantAnnotations(variantAnnotations); for (Map.Entry<String, VariantAnnotation> entry : variantAnnotations.entrySet()) { final String variantId = entry.getKey(); if (storedVariantAnnotations.containsKey(variantId)) { bulkUpdate(bulkOperations, variantId, storedVariantAnnotations.get(variantId).concatenate(entry.getValue())); } else { bulkAddToSet(bulkOperations, variantId, entry.getValue()); } } }
Source:
<code>public Optional<Instant> nextRun(final Optional<Instant> lastRun) { final Duration fullPeriod = Duration.of(_periodCount, _period); final Instant now = _clock.instant(); final Instant start = lastRun .filter(run -> run.compareTo(now) >= 0) .map(run -> run.plus(fullPeriod)) .orElse(now); final long epochMillis = start.toEpochMilli(); <START> final Instant nextRun = Instant.ofEpochMilli((epochMillis / fullPeriod.toMillis()) * fullPeriod.toMillis()); <END> return Optional.of(nextRun); }</code><technical_language>I with: D = TS % INT NEXT = TS - D</technical_language>

Target:
public Optional<Instant> nextRun(final Optional<Instant> lastRun) { final Instant now = _clock.instant(); final Instant start = lastRun .filter(run -> run.compareTo(now) >= 0) .map(run -> run.plus(_fullPeriod)) .orElse(now); final long excessMillis = start.toEpochMilli() % _fullPeriod.toMillis(); return Optional.of(start.minusMillis(excessMillis)); }
Source:
<code>private void waitForPartitionsFetchedOnce() { while ((partitions.isEmpty() || partitionCount == 0) && client.getConnectionManager().isAlive()) { ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); if (!processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist)) { throw new NoDataMemberInClusterException( "Cluster could not initialize the partition table "); <START> } <END> } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }</code><technical_language>Previous code check for lite members I do check here? Is this intentional</technical_language>

Target:
private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); if (memberList.isEmpty()) { break; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }
Source:
<code>public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { DSpaceRestPermission restPermission = DSpaceRestPermission.convert(permission); if (!DSpaceRestPermission.READ.equals(restPermission) <START> || !StringUtils.equals(targetType, "WORKFLOWITEM")) { <END> return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); XmlWorkflowItem workflowItem = workflowItemService.find(context, dsoId); if (ePerson.equals(workflowItem.getSubmitter())) { return true; } if (poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } if (claimedTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }</code><technical_language>above, a Constant, needing hardcode string in multiple places</technical_language>

Target:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { DSpaceRestPermission restPermission = DSpaceRestPermission.convert(permission); if (!DSpaceRestPermission.READ.equals(restPermission) || !StringUtils.equalsIgnoreCase(WorkflowItemRest.NAME, targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); XmlWorkflowItem workflowItem = workflowItemService.find(context, dsoId); if (ePerson.equals(workflowItem.getSubmitter())) { return true; } if (poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } if (claimedTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }
Source:
<code>public void shouldThrowNullPointerOnJoinWithStreamWhenStreamJoinedIsNull() { final StreamJoined joined = null; <START> testStream.join(testStream, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10)), joined); <END> }</code><technical_language>super-nit: this variable (joined) get added auto-refactoring? seems... unnecessary</technical_language>

Target:
public void shouldThrowNullPointerOnJoinWithStreamWhenStreamJoinedIsNull() { testStream.join(testStream, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10)), nullStreamJoinedForTest); }
Source:
<code>BitmapBuilder findObjects(Set<? extends ObjectId> start, BitmapBuilder seen, boolean ignoreMissingStart) throws MissingObjectException, IncorrectObjectTypeException, IOException { final BitmapBuilder bitmapResult = bitmapIndex.newBitmapBuilder(); <START> countOfBitmapIndexMisses = 0; <END> for (ObjectId obj : start) { Bitmap bitmap = bitmapIndex.getBitmap(obj); if (bitmap != null) bitmapResult.or(bitmap); } boolean marked = false; for (ObjectId obj : start) { try { if (!bitmapResult.contains(obj)) { walker.markStart(walker.parseAny(obj)); marked = true; } } catch (MissingObjectException e) { if (ignoreMissingStart) continue; throw e; } } if (marked) { BitmapRevFilter filter = newRevFilter(seen, bitmapResult); walker.setRevFilter(filter); while (walker.next() != null) { pm.update(1); } RevObject ro; while ((ro = walker.nextObject()) != null) { bitmapResult.add(ro, ro.getType()); pm.update(1); } countOfBitmapIndexMisses = filter.getCountOfLoadedCommits(); } return bitmapResult; }</code><technical_language>I want zero here? PackWriter runs 2 invocations of findObjects(); for "have" another for "want". clearing counter report last. Is correct</technical_language>

Target:
BitmapBuilder findObjects(Set<? extends ObjectId> start, BitmapBuilder seen, boolean ignoreMissingStart) throws MissingObjectException, IncorrectObjectTypeException, IOException { final BitmapBuilder bitmapResult = bitmapIndex.newBitmapBuilder(); for (ObjectId obj : start) { Bitmap bitmap = bitmapIndex.getBitmap(obj); if (bitmap != null) bitmapResult.or(bitmap); } boolean marked = false; for (ObjectId obj : start) { try { if (!bitmapResult.contains(obj)) { walker.markStart(walker.parseAny(obj)); marked = true; } } catch (MissingObjectException e) { if (ignoreMissingStart) continue; throw e; } } if (marked) { BitmapRevFilter filter = newRevFilter(seen, bitmapResult); walker.setRevFilter(filter); while (walker.next() != null) { pm.update(1); } RevObject ro; while ((ro = walker.nextObject()) != null) { bitmapResult.add(ro, ro.getType()); pm.update(1); } countOfBitmapIndexMisses += filter.getCountOfLoadedCommits(); } return bitmapResult; }
Source:
<code>private void checkVdsMemoryThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); if (stat.getmem_available() < minAvailableThreshold || stat.getusage_mem_percent() > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(); <START> logable.setVdsId(stat.getId()); <END> logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("AvailableMemory", stat.getmem_available().toString()); logable.AddCustomValue("UsedMemory", stat.getusage_mem_percent().toString()); logable.AddCustomValue("Threshold", stat.getmem_available() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, stat.getmem_available() < minAvailableThreshold ? AuditLogType.VDS_LOW_MEM : AuditLogType.VDS_HIGH_MEM_USE); } }</code><technical_language>i part of this change, create logable object vdsId in constructor instead of setting separatly this apply next changes</technical_language>

Target:
private void checkVdsMemoryThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); AuditLogType valueToLog = stat.getmem_available() < minAvailableThreshold ? AuditLogType.VDS_LOW_MEM : AuditLogType.VDS_HIGH_MEM_USE; if (stat.getmem_available() < minAvailableThreshold || stat.getusage_mem_percent() > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(stat.getId()); logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("AvailableMemory", stat.getmem_available().toString()); logable.AddCustomValue("UsedMemory", stat.getusage_mem_percent().toString()); logable.AddCustomValue("Threshold", stat.getmem_available() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, valueToLog); } }
Source:
<code>public void testNotOptional() { try { insert("value.text", getTestBeanEmpty()); fail("Shouldn't be reached"); } catch (IllegalArgumentException ex) { assertThat(select().isPresent()).isFalse(); <START> } <END> }</code><technical_language>Prefer AssertJ's assertThatThrownBy() try { fail() } catch blocks in tests: java assertThatThrownBy(() -> insert("value.text", getTestBeanEmpty())) .isInstanceOf(IllegalArgumentException.class); assertThat(select()).isEmpty();</technical_language>

Target:
public void testNotOptional() { assertThatThrownBy(() -> insert("value.text", getTestBeanEmpty())).isInstanceOf(IllegalArgumentException.class); assertThat(select().isPresent()).isFalse(); }
Source:
<code>public static void show(final Long sessionId) { <START> LightningTalk talk = LightningTalk.findById(sessionId); <END> if(talk != null) { render(talk); } else { } }</code><technical_language><LINK_0></technical_language>

Target:
public static void show(final Long sessionId) { LightningTalk talk = LightningTalk.findById(sessionId); notFoundIfNull(talk); render(talk); }
Source:
<code>protected void onGetComputedStyles(View element, ComputedStyleAccumulator styles) { <START> styles.store("left", "" + element.getLeft()); <END> styles.store("top", "" + element.getTop()); styles.store("right", "" + element.getRight()); styles.store("bottom", "" + element.getBottom()); }</code><technical_language>Instead of concatenating "" primitive returned element.get____(), Integer.toString(element.get___())</technical_language>

Target:
protected void onGetComputedStyles(View element, ComputedStyleAccumulator styles) { styles.store("left", Integer.toString(element.getLeft())); styles.store("top", Integer.toString(element.getTop())); styles.store("right", Integer.toString(element.getRight())); styles.store("bottom", Integer.toString(element.getBottom())); }
Source:
<code>private void updateLabels() { if <START> ((null != transition) && <END> (null != transition.getComment()) && !transition.getComment().isEmpty()) { tooltipContent.setText(transition.getComment()); } tooltipContent.setText("[not set]"); revalidate(); repaint(); }</code><technical_language>model of GEF transition get null. Editpart is created for a null transition editpart creates figure -> tooltip figure</technical_language>

Target:
private void updateLabels() { if ((null != transition.getComment()) && !transition.getComment().isEmpty()) { tooltipContent.setText(transition.getComment()); } else { tooltipContent.setText("[not set]"); } revalidate(); repaint(); }
Source:
<code>public List<String> getAlterTable(String tableName, Collection<SinkRecordField> fields) { final StringBuilder builder = new StringBuilder("ALTER TABLE "); builder.append(escaped(tableName)); builder.append(" ADD("); writeColumnsSpec(builder, fields); builder.append(")"); <START> log.trace("Alter Table query: " + builder.toString()); <END> return Collections.singletonList(builder.toString()); }</code><technical_language>logged INFO caller, remove this log line</technical_language>

Target:
public List<String> getAlterTable(String tableName, Collection<SinkRecordField> fields) { final StringBuilder builder = new StringBuilder("ALTER TABLE "); builder.append(escaped(tableName)); builder.append(" ADD("); writeColumnsSpec(builder, fields); builder.append(")"); return Collections.singletonList(builder.toString()); }
Source:
<code>private void captureStackTrace() { if (stackTraces.size() < options.maxStackSamples()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace.length > 3) { StackTraceElement[] slicedStackTrace = Arrays.copyOfRange(stackTrace, 3, stackTrace.length); <START> JobCancelabilityMonitor.StackTraceSample <END> newStackTraceSample = new StackTraceSample(slicedStackTrace); boolean found = false; Iterator<JobCancelabilityMonitor.StackTraceSample> it = stackTraces.iterator(); while (it.hasNext() && !found) { found = (it.next().hashCode == newStackTraceSample.hashCode); } if (!found) { stackTraces.add(newStackTraceSample); } } } }</code><technical_language>Redundant qualifier</technical_language>

Target:
private StackTraceElement[] captureStackTrace() { final StackTraceElement[] ret; StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace.length > 3) { ret = Arrays.copyOfRange(stackTrace, 3, stackTrace.length); } else { ret = stackTrace; } return ret; }
Source:
<code>private void testContent() throws Exception { ______TS("Typical case: empty profile values"); profilePage.verifyHtml("/studentProfilePageDefault.html"); ______TS("Typical case: existing profile values"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.verifyHtmlPart(By.id("editProfileDiv"), "/studentProfileEditDivExistingValues.html"); ______TS("Typical case: edit profile picture modal (without existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.showPictureEditor(); profilePage.verifyHtmlPart(By.id("studentPhotoUploader"), "/studentProfilePictureModalDefault.html"); ______TS("Typical case: edit profile picture modal (with existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.fillProfilePic("src/test/resources/images/profile_pic.png"); profilePage.uploadPicture(); profilePage.verifyStatusWithRetry(Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED, 10); <START> profilePage.verifyHtml("/studentProfilePageFilled.html"); <END> profilePage.click(By.className("close")); }</code><technical_language>Is a reason for full HTML check instead of main content check (or By.id check)</technical_language>

Target:
private void testContent() throws Exception { ______TS("Typical case: empty profile values"); profilePage.verifyHtml("/studentProfilePageDefault.html"); ______TS("Typical case: existing profile values"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.verifyHtmlPart(By.id("editProfileDiv"), "/studentProfileEditDivExistingValues.html"); ______TS("Typical case: edit profile picture modal (without existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.showPictureEditor(); profilePage.verifyHtmlPart(By.id("studentPhotoUploader"), "/studentProfilePictureModalDefault.html"); ______TS("Typical case: edit profile picture modal (with existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.fillProfilePic("src/test/resources/images/profile_pic.png"); profilePage.uploadPicture(); profilePage.verifyStatusWithRetry(Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED, 10); profilePage.verifyHtmlMainContent("/studentProfilePageFilled.html"); profilePage.click(By.className("close")); }
Source:
<code>protected List<Statement> generateCreateInstanceStatements(final ClassStructureBuilder<?> bodyBlockBuilder, final Injectable injectable, final DependencyGraph graph, final InjectionContext injectionContext) { final List<Statement> stmts = new ArrayList<>(); final String elementVar = "element"; stmts.add(declareFinalVariable(elementVar, elementClass(), elementInitialization())); for (final Property property : properties) { stmts.add(loadVariable(elementVar).invoke("setPropertyString", loadLiteral(property.name()), loadLiteral(property.value()))); } final String retValVar = "retVal"; <START> stmts.add(declareFinalVariable(retValVar, type, invokeStatic(Js.class, "uncheckedCast", loadVariable(elementVar)))); <END> if (implementsNativeHasValueAndRequiresGeneratedInvocation(type)) { stmts.add(Stmt.invokeStatic(NativeHasValueAccessors.class, "registerAccessor", loadVariable(retValVar), createAccessorImpl(type, retValVar))); } stmts.add(loadVariable(retValVar).returnValue()); return stmts; }</code><technical_language>Is this of spots planning change a checked cast</technical_language>

Target:
protected List<Statement> generateCreateInstanceStatements(final ClassStructureBuilder<?> bodyBlockBuilder, final Injectable injectable, final DependencyGraph graph, final InjectionContext injectionContext) { final List<Statement> stmts = new ArrayList<>(); final String elementVar = "element"; stmts.add(declareFinalVariable(elementVar, elementClass(), elementInitialization())); for (final Property property : properties) { stmts.add(loadVariable(elementVar).invoke("setPropertyString", loadLiteral(property.name()), loadLiteral(property.value()))); } final String retValVar = "retVal"; stmts.add(declareFinalVariable(retValVar, type, invokeStatic(Js.class, "cast", loadVariable(elementVar)))); if (implementsNativeHasValueAndRequiresGeneratedInvocation(type)) { stmts.add(Stmt.invokeStatic(NativeHasValueAccessors.class, "registerAccessor", loadVariable(retValVar), createAccessorImpl(type, retValVar))); } stmts.add(loadVariable(retValVar).returnValue()); return stmts; }